From bcb787becaf78df93ee5c0d9f447def0fdc7c3cd Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Mon, 16 Nov 2026 15:32:36 -0500 Subject: [PATCH 01/44] [Spark][DEDUP] Remove unused SchemaUtils.convertKernelSchemaToSparkSchema in the V2 connector (#8105) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description The V2 connector's `SchemaUtils` has a Kernel-to-Spark schema converter: `convertKernelSchemaToSparkSchema`, `convertKernelDataTypeToSparkDataType`, `convertKernelFieldMetadataToSparkMetadata`, and their private helpers. Main code never calls them. Table schemas are built with `convertKernelMetadataToSparkSchema`, which parses the log's schema string with `DataType.fromJson`. Since #7942, the converter also rejects collated strings. This PR: - removes the unused converter and its helpers. The Spark-to-Kernel direction is unchanged. - removes the `SchemaUtilsTest` cases that only covered the removed code, and the Kernel-to-Spark halves of the round-trip checks. - changes `PartitionUtilsTest` to get a snapshot's Spark schema through `convertKernelMetadataToSparkSchema`, as the connector does. ## How was this patch tested? `build/sbt "sparkV2/Test/javafmtCheck" "sparkV2/javafmtCheck" "sparkV2/testOnly org.apache.spark.sql.delta.v2.utils.SchemaUtilsTest org.apache.spark.sql.delta.v2.utils.PartitionUtilsTest"`: formatting checks are clean, and 65 JUnit cases pass (`SchemaUtilsTest` 42, `PartitionUtilsTest` 23). ## Does this PR introduce _any_ user-facing changes? No. --------- Signed-off-by: tdas --- .../spark/sql/delta/v2/utils/SchemaUtils.java | 193 ------------------ .../delta/v2/utils/PartitionUtilsTest.java | 17 +- .../sql/delta/v2/utils/SchemaUtilsTest.java | 99 --------- 3 files changed, 9 insertions(+), 300 deletions(-) diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/SchemaUtils.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/SchemaUtils.java index 121eb91251b..40a1218a98f 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/SchemaUtils.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/SchemaUtils.java @@ -42,9 +42,7 @@ import java.util.List; import org.apache.spark.sql.catalyst.util.CollationFactory; import org.apache.spark.sql.errors.QueryCompilationErrors; -import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.Metadata; -import org.apache.spark.sql.types.MetadataBuilder; import org.apache.spark.unsafe.Platform; import scala.jdk.CollectionConverters; @@ -66,93 +64,6 @@ public static org.apache.spark.sql.types.StructType convertKernelMetadataToSpark org.apache.spark.sql.types.DataType.fromJson(metadata.getSchemaString()); } - /** - * Converts a Delta Kernel schema to a Spark schema. String collations are not supported and fail - * the conversion, so use {@link #convertKernelMetadataToSparkSchema} for table schemas. - */ - public static org.apache.spark.sql.types.StructType convertKernelSchemaToSparkSchema( - StructType kernelSchema) { - requireNonNull(kernelSchema); - List fields = new ArrayList<>(); - - for (StructField field : kernelSchema.fields()) { - // Kernel records the collation of every non-UTF8_BINARY string in or under a field here. - if (field.getMetadata().contains(StructField.COLLATIONS_METADATA_KEY)) { - throw collationsNotSupported(field.getName()); - } - fields.add( - new org.apache.spark.sql.types.StructField( - field.getName(), - convertKernelDataTypeToSparkDataType(field.getDataType()), - field.isNullable(), - convertKernelFieldMetadataToSparkMetadata(field.getMetadata()))); - } - - return new org.apache.spark.sql.types.StructType( - fields.toArray(new org.apache.spark.sql.types.StructField[0])); - } - - private static IllegalArgumentException collationsNotSupported(String collated) { - return new IllegalArgumentException( - "Collated strings are not supported by this conversion: " - + collated - + ". Use convertKernelMetadataToSparkSchema to convert a table schema."); - } - - /** Converts a Delta Kernel data type to a Spark data type. Collated strings are rejected. */ - public static org.apache.spark.sql.types.DataType convertKernelDataTypeToSparkDataType( - DataType kernelDataType) { - requireNonNull(kernelDataType); - if (kernelDataType instanceof StringType) { - if (!((StringType) kernelDataType).isUTF8BinaryCollated()) { - throw collationsNotSupported(kernelDataType.toString()); - } - return DataTypes.StringType; - } else if (kernelDataType instanceof BooleanType) { - return DataTypes.BooleanType; - } else if (kernelDataType instanceof IntegerType) { - return DataTypes.IntegerType; - } else if (kernelDataType instanceof LongType) { - return DataTypes.LongType; - } else if (kernelDataType instanceof BinaryType) { - return DataTypes.BinaryType; - } else if (kernelDataType instanceof ByteType) { - return DataTypes.ByteType; - } else if (kernelDataType instanceof DateType) { - return DataTypes.DateType; - } else if (kernelDataType instanceof DecimalType) { - DecimalType kernelDecimal = (DecimalType) kernelDataType; - return DataTypes.createDecimalType(kernelDecimal.getPrecision(), kernelDecimal.getScale()); - } else if (kernelDataType instanceof DoubleType) { - return DataTypes.DoubleType; - } else if (kernelDataType instanceof FloatType) { - return DataTypes.FloatType; - } else if (kernelDataType instanceof ShortType) { - return DataTypes.ShortType; - } else if (kernelDataType instanceof TimestampType) { - return DataTypes.TimestampType; - } else if (kernelDataType instanceof TimestampNTZType) { - return DataTypes.TimestampNTZType; - } else if (kernelDataType instanceof ArrayType) { - ArrayType kernelArray = (ArrayType) kernelDataType; - return DataTypes.createArrayType( - convertKernelDataTypeToSparkDataType(kernelArray.getElementType()), - kernelArray.containsNull()); - } else if (kernelDataType instanceof MapType) { - MapType kernelMap = (MapType) kernelDataType; - return DataTypes.createMapType( - convertKernelDataTypeToSparkDataType(kernelMap.getKeyType()), - convertKernelDataTypeToSparkDataType(kernelMap.getValueType()), - kernelMap.isValueContainsNull()); - } else if (kernelDataType instanceof StructType) { - return convertKernelSchemaToSparkSchema((StructType) kernelDataType); - } else if (kernelDataType instanceof VariantType) { - return DataTypes.VariantType; - } else { - throw new IllegalArgumentException("unsupported data type " + kernelDataType); - } - } - /** * Projects the union of {@code readDataSchema} and {@code partitionSchema} into DDL order. Fields * not present in {@code rawSchema} (e.g. {@code _metadata}) are appended at the tail in insertion @@ -301,62 +212,6 @@ public static DataType convertSparkDataTypeToKernelDataType( // Field Metadata Conversion // /////////////////////////////// - /** - * Converts Kernel FieldMetadata to Spark Metadata. - * - * @param kernelMetadata the Kernel FieldMetadata to convert - * @return the equivalent Spark Metadata - */ - public static Metadata convertKernelFieldMetadataToSparkMetadata( - io.delta.kernel.types.FieldMetadata kernelMetadata) { - requireNonNull(kernelMetadata); - if (kernelMetadata.getEntries().isEmpty()) { - return Metadata.empty(); - } - MetadataBuilder builder = new MetadataBuilder(); - kernelMetadata - .getEntries() - .forEach( - (key, value) -> { - if (value instanceof Long) { - builder.putLong(key, (Long) value); - } else if (value instanceof Double) { - builder.putDouble(key, (Double) value); - } else if (value instanceof Boolean) { - builder.putBoolean(key, (Boolean) value); - } else if (value instanceof String) { - builder.putString(key, (String) value); - } else if (value instanceof io.delta.kernel.types.FieldMetadata) { - builder.putMetadata( - key, - convertKernelFieldMetadataToSparkMetadata( - (io.delta.kernel.types.FieldMetadata) value)); - } else if (value instanceof Long[]) { - builder.putLongArray(key, unboxLongArray((Long[]) value, key)); - } else if (value instanceof Double[]) { - builder.putDoubleArray(key, unboxDoubleArray((Double[]) value, key)); - } else if (value instanceof Boolean[]) { - builder.putBooleanArray(key, unboxBooleanArray((Boolean[]) value, key)); - } else if (value instanceof String[]) { - builder.putStringArray(key, (String[]) value); - } else if (value instanceof io.delta.kernel.types.FieldMetadata[]) { - io.delta.kernel.types.FieldMetadata[] kernelMetadatas = - (io.delta.kernel.types.FieldMetadata[]) value; - Metadata[] sparkMetadatas = - Arrays.stream(kernelMetadatas) - .map(SchemaUtils::convertKernelFieldMetadataToSparkMetadata) - .toArray(Metadata[]::new); - builder.putMetadataArray(key, sparkMetadatas); - } else if (value == null) { - builder.putNull(key); - } else { - throw new UnsupportedOperationException( - "Unsupported metadata value type: " + value.getClass().getName()); - } - }); - return builder.build(); - } - /** * Converts Spark Metadata to Kernel FieldMetadata. * @@ -418,52 +273,4 @@ public static io.delta.kernel.types.FieldMetadata convertSparkMetadataToKernelFi }); return builder.build(); } - - /** - * Unboxes a Long[] to long[], checking for nulls. - * - * @throws NullPointerException if any element is null - */ - private static long[] unboxLongArray(Long[] boxedArray, String key) { - long[] primitiveArray = new long[boxedArray.length]; - for (int i = 0; i < boxedArray.length; i++) { - requireNonNull( - boxedArray[i], - String.format("Null element at index %s in Long array for key '%s'", i, key)); - primitiveArray[i] = boxedArray[i]; - } - return primitiveArray; - } - - /** - * Unboxes a Double[] to double[], checking for nulls. - * - * @throws NullPointerException if any element is null - */ - private static double[] unboxDoubleArray(Double[] boxedArray, String key) { - double[] primitiveArray = new double[boxedArray.length]; - for (int i = 0; i < boxedArray.length; i++) { - requireNonNull( - boxedArray[i], - String.format("Null element at index %s in Double array for key '%s'", i, key)); - primitiveArray[i] = boxedArray[i]; - } - return primitiveArray; - } - - /** - * Unboxes a Boolean[] to boolean[], checking for nulls. - * - * @throws NullPointerException if any element is null - */ - private static boolean[] unboxBooleanArray(Boolean[] boxedArray, String key) { - boolean[] primitiveArray = new boolean[boxedArray.length]; - for (int i = 0; i < boxedArray.length; i++) { - requireNonNull( - boxedArray[i], - String.format("Null element at index %s in Boolean array for key '%s'", i, key)); - primitiveArray[i] = boxedArray[i]; - } - return primitiveArray; - } } diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/PartitionUtilsTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/PartitionUtilsTest.java index bdb815052bd..436da0e7e6f 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/PartitionUtilsTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/PartitionUtilsTest.java @@ -24,6 +24,7 @@ import io.delta.kernel.data.FilteredColumnarBatch; import io.delta.kernel.data.MapValue; import io.delta.kernel.data.Row; +import io.delta.kernel.internal.SnapshotImpl; import io.delta.kernel.internal.actions.AddFile; import io.delta.kernel.internal.actions.DeletionVectorDescriptor; import io.delta.kernel.internal.util.VectorUtils; @@ -387,7 +388,7 @@ public void testCreateDeltaParquetReaderFactory_Basic() { StructType readDataSchema = dataSchema; StructType ddlOrderedReadOutputSchema = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); Filter[] filters = new Filter[0]; @@ -429,7 +430,7 @@ public void testCreateDeltaParquetReaderFactory_isCDCRead() { StructType readDataSchema = dataSchema; StructType ddlOrderedReadOutputSchema = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); Filter[] filters = new Filter[0]; @@ -478,7 +479,7 @@ public void testCreateDeltaParquetReaderFactory_NotWriteTimeCDCRead() { StructType readDataSchema = dataSchema; StructType ddlOrderedReadOutputSchema = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); Filter[] filters = new Filter[0]; @@ -614,7 +615,7 @@ public void testDdlOrderedOutputSchema_PartitionInMiddleInterleavedAtDdlPosition StructType result = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); assertArrayEquals(new String[] {"id", "part", "col3"}, result.fieldNames()); @@ -642,7 +643,7 @@ public void testDdlOrderedOutputSchema_PartitionAtEndIsIdentity() { StructType result = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); assertArrayEquals(new String[] {"id", "col3", "part"}, result.fieldNames()); @@ -664,7 +665,7 @@ public void testDdlOrderedOutputSchema_NoPartitionsShortCircuits() { StructType result = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, emptyPartitions); // Returns the readDataSchema instance unchanged (short-circuit). @@ -704,7 +705,7 @@ public void testDdlOrderedOutputSchema_MetadataLeftoverAppendedAtEnd() { StructType result = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); assertArrayEquals(new String[] {"id", "part", "col3", "_metadata"}, result.fieldNames()); @@ -737,7 +738,7 @@ public void testDdlOrderedOutputSchema_MultiplePartitionsInterleaved() { StructType result = SchemaUtils.ddlOrderedOutputSchema( - SchemaUtils.convertKernelSchemaToSparkSchema(snapshot.getSchema()), + SchemaUtils.convertKernelMetadataToSparkSchema(((SnapshotImpl) snapshot).getMetadata()), readDataSchema, partitionSchema); assertArrayEquals(new String[] {"a", "p1", "b", "p2", "c"}, result.fieldNames()); diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java index 8678aac3a50..b3037c6c60c 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java @@ -40,9 +40,6 @@ import io.delta.kernel.types.TimestampNTZType; import io.delta.kernel.types.TimestampType; import io.delta.kernel.types.VariantType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import java.util.stream.Stream; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.types.DataTypes; @@ -220,92 +217,6 @@ public void testConvertSparkSchemaToKernelSchema() { assertEquals(expectedKernelSchema, actualKernelSchema); } - @Test - public void testConvertKernelSchemaToSparkSchema() { - StructType kernelSchema = - new StructType().add("a", IntegerType.INTEGER, true).add("b", StringType.STRING, false); - - org.apache.spark.sql.types.StructType expectedSparkSchema = - DataTypes.createStructType( - new org.apache.spark.sql.types.StructField[] { - DataTypes.createStructField("a", DataTypes.IntegerType, true), - DataTypes.createStructField("b", DataTypes.StringType, false) - }); - - org.apache.spark.sql.types.StructType actualSparkSchema = - SchemaUtils.convertKernelSchemaToSparkSchema(kernelSchema); - assertEquals(expectedSparkSchema, actualSparkSchema); - } - - @ParameterizedTest - @MethodSource("collations") - public void testCollatedStringsToSparkAreRejected(String sparkCollation, String kernelCollation) { - StringType kernelString = new StringType(kernelCollation); - List kernelSchemas = new ArrayList<>(); - kernelSchemas.add(new StructType().add("s", kernelString)); - kernelSchemas.add(new StructType().add("a", new ArrayType(kernelString, true))); - kernelSchemas.add(new StructType().add("outer", new StructType().add("s", kernelString))); - List kernelTypes = - Arrays.asList(kernelString, new MapType(StringType.STRING, kernelString, true)); - if (sparkCollation.equals("UTF8_BINARY")) { - kernelSchemas.forEach(SchemaUtils::convertKernelSchemaToSparkSchema); - kernelTypes.forEach(SchemaUtils::convertKernelDataTypeToSparkDataType); - return; - } - // A schema can also record a collation only in field metadata, on a binary string. - kernelSchemas.add( - new StructType() - .add( - "s", - StringType.STRING, - FieldMetadata.builder() - .putFieldMetadata( - "__COLLATIONS", - FieldMetadata.builder().putString("s", kernelCollation).build()) - .build())); - for (StructType kernelSchema : kernelSchemas) { - assertThrows( - IllegalArgumentException.class, - () -> SchemaUtils.convertKernelSchemaToSparkSchema(kernelSchema), - kernelSchema.toString()); - } - for (DataType kernelType : kernelTypes) { - assertThrows( - IllegalArgumentException.class, - () -> SchemaUtils.convertKernelDataTypeToSparkDataType(kernelType), - kernelType.toString()); - } - } - - static Stream nullInPrimitiveArraysProvider() { - return Stream.of( - Arguments.of( - "Long", - FieldMetadata.builder().putLongArray("ids", new Long[] {1L, null, 3L}).build(), - 1), - Arguments.of( - "Double", - FieldMetadata.builder().putDoubleArray("scores", new Double[] {1.1, 2.2, null}).build(), - 2), - Arguments.of( - "Boolean", - FieldMetadata.builder() - .putBooleanArray("flags", new Boolean[] {true, null, false}) - .build(), - 1)); - } - - @ParameterizedTest(name = "{0} array with null at index {2}") - @MethodSource("nullInPrimitiveArraysProvider") - public void testNullInPrimitiveArrays( - String typeName, FieldMetadata kernelMetadata, int expectedNullIndex) { - Exception ex = - assertThrows( - Exception.class, - () -> SchemaUtils.convertKernelFieldMetadataToSparkMetadata(kernelMetadata)); - assertTrue(ex.getMessage().contains("Null element at index " + expectedNullIndex)); - } - @Test public void testSchemaRoundTripWithFieldMetadata() { // Schema with field metadata (e.g., column mapping) @@ -334,20 +245,12 @@ public void testSchemaRoundTripWithFieldMetadata() { // Verify Spark → Kernel conversion StructType actualKernelSchema = SchemaUtils.convertSparkSchemaToKernelSchema(sparkSchema); assertEquals(expectedKernelSchema, actualKernelSchema); - - // Verify Kernel → Spark conversion - org.apache.spark.sql.types.StructType sparkSchema2 = - SchemaUtils.convertKernelSchemaToSparkSchema(actualKernelSchema); - assertEquals(sparkSchema, sparkSchema2); } private void checkConversion( org.apache.spark.sql.types.DataType sparkDataType, DataType kernelDataType) { DataType toKernel = SchemaUtils.convertSparkDataTypeToKernelDataType(sparkDataType); assertEquals(kernelDataType, toKernel); - org.apache.spark.sql.types.DataType toSpark = - SchemaUtils.convertKernelDataTypeToSparkDataType(kernelDataType); - assertEquals(sparkDataType, toSpark); } //////////////////////////////// @@ -474,8 +377,6 @@ public void testMetadataConversion( String typeName, Metadata sparkMetadata, FieldMetadata kernelMetadata) { assertEquals( kernelMetadata, SchemaUtils.convertSparkMetadataToKernelFieldMetadata(sparkMetadata)); - assertEquals( - sparkMetadata, SchemaUtils.convertKernelFieldMetadataToSparkMetadata(kernelMetadata)); } @Test From 34858de48f347b9cd08c9962a16249996c2a06e5 Mon Sep 17 00:00:00 2001 From: Ala Luszczak Date: Mon, 16 Nov 2026 22:05:52 +0100 Subject: [PATCH 02/44] [Spark] Make all nested output fields nullable on Delta writes (#8171) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Before writing data files, Delta makes the query's output attributes nullable (`TransactionalWrite.makeOutputNullable`), so that a query that under-reports nullability can't produce unreadable Parquet files. The helper it uses, `SchemaUtils.typeAsNullable`, skips primitive map values and the elements of nested arrays and maps. When such a field holds NULLs that the query reports as NOT NULL (e.g. from `lag`/`lead` with a NULL default), they land in a required Parquet field: the commit succeeds, but reading the table fails. This affects CTAS, RTAS, INSERT INTO, INSERT OVERWRITE, DataFrame writes and MERGE INSERT. This PR adds `SchemaUtils.typeAsFullyNullable`, which makes every nested field nullable, and uses it in `makeOutputNullable`. Only the Parquet schemas of the data files change; the table schema in the Delta log was already fully nullable. `typeAsNullable` is unchanged, because the DDL NOT NULL validation (`removeUnenforceableNotNullConstraints`) also uses it, and making it fully recursive would reject table schemas that are accepted today. Its doc now says what it leaves as it is. ## How was this patch tested? New tests in `SchemaUtilsSuite` cover what `typeAsNullable` and `typeAsFullyNullable` return for each kind of nested type. New tests in `TransactionalWriteSuite` write a query whose `lag`/`lead` defaults put NULLs into a primitive map value, nested array elements and values nested in map values, which the query reports as NOT NULL: - For each write (CTAS, RTAS, CREATE OR REPLACE TABLE AS SELECT, INSERT INTO, INSERT OVERWRITE, DataFrame save/append/overwrite, DataFrameWriterV2 append, MERGE INSERT, INSERT BY NAME, MERGE UPDATE, UPDATE), the NULLs read back correctly. - A check that the query reports these fields as NOT NULL but returns NULLs there, so the tests keep exercising the bug. ## Does this PR introduce _any_ user-facing changes? Yes, a bug fix: writes whose query reports a primitive map value or a nested array/map element as NOT NULL, but returns NULLs there, used to commit Parquet files that couldn't be read afterwards. They now produce readable files, and the NULLs read back. --- .../sql/delta/files/TransactionalWrite.scala | 2 +- .../spark/sql/delta/schema/SchemaUtils.scala | 18 +- .../delta/files/TransactionalWriteSuite.scala | 162 +++++++++++++++++- .../sql/delta/schema/SchemaUtilsSuite.scala | 71 ++++++++ 4 files changed, 249 insertions(+), 4 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala b/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala index 2680bc18330..0cd2ecd320f 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/files/TransactionalWrite.scala @@ -85,7 +85,7 @@ trait TransactionalWrite extends DeltaLogging { self: OptimisticTransactionImpl protected def makeOutputNullable(output: Seq[Attribute]): Seq[Attribute] = { output.map { case ref: AttributeReference => - val nullableDataType = SchemaUtils.typeAsNullable(ref.dataType) + val nullableDataType = SchemaUtils.typeAsFullyNullable(ref.dataType) ref.copy(dataType = nullableDataType, nullable = true)(ref.exprId, ref.qualifier) case attr => attr.withNullability(true) } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/schema/SchemaUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/schema/SchemaUtils.scala index 869a3287300..44304226296 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/schema/SchemaUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/schema/SchemaUtils.scala @@ -181,7 +181,12 @@ object SchemaUtils extends DeltaLogging { } } - /** Turns the data types to nullable in a recursive manner for nested columns. */ + /** + * Turns the data type nullable inside structs, and one level into arrays and into maps with + * struct keys or values. Unlike [[typeAsFullyNullable]], it leaves maps without struct keys or + * values, and the types nested in array elements or map values other than structs, as they are, + * which [[removeUnenforceableNotNullConstraints]] relies on. + */ def typeAsNullable(dt: DataType): DataType = dt match { case s: StructType => s.asNullable case a @ ArrayType(s: StructType, _) => a.copy(s.asNullable, containsNull = true) @@ -195,6 +200,17 @@ object SchemaUtils extends DeltaLogging { case other => other } + /** + * Turns the data type nullable at every nesting level: struct fields, array elements, and map + * values, including those of primitive type, which [[typeAsNullable]] leaves as they are. + */ + def typeAsFullyNullable(dt: DataType): DataType = dt match { + case s: StructType => s.toNullable + case a: ArrayType => a.toNullable + case m: MapType => m.toNullable + case other => other + } + /** * Drops null types from the DataFrame if they exist. We don't have easy ways of generating types * such as MapType and ArrayType, therefore if these types contain NullType in their elements, diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/files/TransactionalWriteSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/files/TransactionalWriteSuite.scala index 9b47e6697cd..afc58b73c82 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/files/TransactionalWriteSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/files/TransactionalWriteSuite.scala @@ -27,10 +27,10 @@ import org.apache.hadoop.fs.Path import org.apache.parquet.hadoop.ParquetFileReader import org.apache.parquet.hadoop.util.HadoopInputFile -import org.apache.spark.sql.{QueryTest, Row} +import org.apache.spark.sql.{DataFrame, QueryTest, Row} import org.apache.spark.sql.functions.column import org.apache.spark.sql.test.SharedSparkSession -import org.apache.spark.sql.types.{StringType, StructType} +import org.apache.spark.sql.types.{ArrayType, MapType, StringType, StructType} class TransactionalWriteSuite extends QueryTest with SharedSparkSession with DeltaSQLCommandTest { @@ -110,4 +110,162 @@ class TransactionalWriteSuite extends QueryTest with SharedSparkSession with Del } } } + + /** A way of writing the rows of [[NestedNullsWrite.query]] into the table at a path. */ + private case class NestedNullsWrite(name: String, write: String => Unit) + + private object NestedNullsWrite { + // lag and lead take their type from the input expression only, so the query reports the map + // values, the inner array elements and the values nested in a map value as NOT NULL, + // although the defaults put NULLs there for id 0. + val query: String = + """SELECT id, + | lag(map('k', v), 1, map('k', w)) OVER (ORDER BY id) AS m, + | lag(array(array(v)), 1, array(array(w))) OVER (ORDER BY id) AS a, + | lead(map('k', array(v)), 1, map('k', array(w))) OVER (ORDER BY id DESC) AS ma, + | lead(map('k', map('j', v)), 1, map('k', map('j', w))) OVER (ORDER BY id DESC) AS mm + |FROM ( + | SELECT CAST(id AS INT) AS id, CAST(id AS INT) AS v, + | IF(id = 0, NULL, CAST(id AS INT)) AS w + | FROM range(3)) + |""".stripMargin + + /** The rows of [[readValues]] after writing [[query]]. */ + val expectedRows: Seq[Row] = Seq( + Row(0, null, null, null, null), + Row(1, 0, 0, 0, 0), + Row(2, 1, 1, 1, 1)) + + /** Reads the nested values of the table at a path. */ + def readValues(path: String): DataFrame = + spark.read.format("delta").load(path) + .selectExpr("id", "m['k']", "a[0][0]", "ma['k'][0]", "mm['k']['j']") + + private val tableSchema = "id INT, m MAP, a ARRAY>, " + + "ma MAP>, mm MAP>" + + private def createEmptyTable(path: String): Unit = + sql(s"CREATE TABLE delta.`$path` ($tableSchema) USING delta") + + /** Creates a table with the ids of the query and placeholder values without NULLs. */ + private def createSeededTable(path: String): Unit = { + createEmptyTable(path) + sql(s"INSERT INTO delta.`$path` SELECT id, map('k', -1), array(array(-1)), " + + "map('k', array(-1)), map('k', map('j', -1)) FROM range(3)") + } + + /** The ways of writing [[query]] that the tests cover. */ + val all: Seq[NestedNullsWrite] = Seq( + NestedNullsWrite("CREATE TABLE AS SELECT", path => + sql(s"CREATE TABLE delta.`$path` USING delta AS $query")), + NestedNullsWrite("REPLACE TABLE AS SELECT", { path => + createEmptyTable(path) + sql(s"REPLACE TABLE delta.`$path` USING delta AS $query") + }), + NestedNullsWrite("CREATE OR REPLACE TABLE AS SELECT", { path => + createEmptyTable(path) + sql(s"CREATE OR REPLACE TABLE delta.`$path` USING delta AS $query") + }), + NestedNullsWrite("INSERT INTO", { path => + createEmptyTable(path) + sql(s"INSERT INTO delta.`$path` $query") + }), + NestedNullsWrite("INSERT OVERWRITE", { path => + createSeededTable(path) + sql(s"INSERT OVERWRITE delta.`$path` $query") + }), + NestedNullsWrite("DataFrame save", path => + sql(query).write.format("delta").save(path)), + NestedNullsWrite("DataFrame append", { path => + createEmptyTable(path) + sql(query).write.format("delta").mode("append").save(path) + }), + NestedNullsWrite("DataFrame overwrite", { path => + createSeededTable(path) + sql(query).write.format("delta").mode("overwrite").save(path) + }), + NestedNullsWrite("DataFrameWriterV2 append", { path => + createEmptyTable(path) + sql(query).writeTo(s"delta.`$path`").append() + }), + NestedNullsWrite("MERGE INSERT", { path => + createEmptyTable(path) + sql(s"MERGE INTO delta.`$path` t USING ($query) s ON t.id = s.id " + + "WHEN NOT MATCHED THEN INSERT *") + }), + NestedNullsWrite("INSERT INTO BY NAME", { path => + createEmptyTable(path) + sql(s"INSERT INTO delta.`$path` BY NAME $query") + }), + NestedNullsWrite("MERGE UPDATE SET *", { path => + createSeededTable(path) + sql(s"MERGE INTO delta.`$path` t USING ($query) s ON t.id = s.id " + + "WHEN MATCHED THEN UPDATE SET *") + }), + NestedNullsWrite("MERGE UPDATE SET columns", { path => + createSeededTable(path) + sql(s"MERGE INTO delta.`$path` t USING ($query) s ON t.id = s.id " + + "WHEN MATCHED THEN UPDATE SET m = s.m, a = s.a, ma = s.ma, mm = s.mm") + }), + NestedNullsWrite("UPDATE with scalar subqueries", { path => + createSeededTable(path) + for (id <- 0 until 3) { + val row = s"FROM ($query) WHERE id = $id" + sql(s"UPDATE delta.`$path` SET m = (SELECT m $row), a = (SELECT a $row), " + + s"ma = (SELECT ma $row), mm = (SELECT mm $row) WHERE id = $id") + } + }) + ) + } + + // The following tests verify that Delta defends against misbehaving Spark operators that + // produce NULLs but claim to return a NOT NULL data type. This test ensures that the query that + // generates the data to write reproduces this incorrect behavior. + test("ensure NestedNullsWrite.query produces NULLs but returns a NOT NULL data type") { + val df = sql(NestedNullsWrite.query) + val m = df.schema("m").dataType.asInstanceOf[MapType] + val a = df.schema("a").dataType.asInstanceOf[ArrayType] + val ma = df.schema("ma").dataType.asInstanceOf[MapType] + val mm = df.schema("mm").dataType.asInstanceOf[MapType] + if (m.valueContainsNull || + a.elementType.asInstanceOf[ArrayType].containsNull || + ma.valueContainsNull || ma.valueType.asInstanceOf[ArrayType].containsNull || + mm.valueContainsNull || mm.valueType.asInstanceOf[MapType].valueContainsNull) { + fail( + """Ooopsie! The tests in this suite that write NestedNullsWrite.query depend on a defect + |of the lag and lead window functions: with a NULL default, they produce NULLs in nested + |fields that their result type reports as NOT NULL. That defect appears to be at least + |partially fixed. + | + |UNPIVOT has it too, with spark.sql.legacy.unpivot.useFirstValueNestedNullability=true. + |For example, with that conf this query reports m as MAP although + |one of the values it unpivots is NULL: + | + | SELECT m FROM (SELECT map('k', 1) AS m1, map('k', CAST(NULL AS INT)) AS m2) + | UNPIVOT INCLUDE NULLS (m FOR c IN (m1, m2)) + | + |Rewrite NestedNullsWrite.query with UNPIVOT and that conf. If that doesn't work either, + |find another query with this defect. If there is none, disable the test cases that + |depend on it. + |""".stripMargin) + } + // The values are NULL nonetheless. to_json checks for NULLs whatever the reported nullability. + checkAnswer( + df.selectExpr("id", "to_json(m)", "to_json(a)", "to_json(ma)", "to_json(mm)"), + Seq( + Row(0, """{"k":null}""", "[[null]]", """{"k":[null]}""", """{"k":{"j":null}}"""), + Row(1, """{"k":0}""", "[[0]]", """{"k":[0]}""", """{"k":{"j":0}}"""), + Row(2, """{"k":1}""", "[[1]]", """{"k":[1]}""", """{"k":{"j":1}}"""))) + } + + for (write <- NestedNullsWrite.all) { + test("NULLs in nested fields that the query reports as NOT NULL are readable after " + + write.name) { + withTempDir { dir => + val path = dir.getCanonicalPath + write.write(path) + checkAnswer(NestedNullsWrite.readValues(path), NestedNullsWrite.expectedRows) + } + } + } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/schema/SchemaUtilsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/schema/SchemaUtilsSuite.scala index 34abfa905e6..b0d1e50c657 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/schema/SchemaUtilsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/schema/SchemaUtilsSuite.scala @@ -3382,6 +3382,77 @@ class SchemaUtilsSuite extends QueryTest ) } + ///////////////////////////////////////// + // typeAsNullable and typeAsFullyNullable + ///////////////////////////////////////// + test("typeAsNullable and typeAsFullyNullable") { + case class NullabilityCase( + inputType: DataType, + expectedTypeAsNullable: DataType, + expectedTypeAsFullyNullable: DataType) + + val int = IntegerType + def array(elementType: DataType, containsNull: Boolean): DataType = + ArrayType(elementType, containsNull) + def map(valueType: DataType, valueContainsNull: Boolean): DataType = + MapType(StringType, valueType, valueContainsNull) + def struct(fieldType: DataType, nullable: Boolean): StructType = + new StructType().add("f", fieldType, nullable) + + val cases = Seq( + NullabilityCase( + inputType = int, + expectedTypeAsNullable = int, + expectedTypeAsFullyNullable = int), + NullabilityCase( + inputType = array(int, false), + expectedTypeAsNullable = array(int, true), + expectedTypeAsFullyNullable = array(int, true)), + // typeAsNullable only makes the elements of the outer array nullable. + NullabilityCase( + inputType = array(array(int, false), false), + expectedTypeAsNullable = array(array(int, false), true), + expectedTypeAsFullyNullable = array(array(int, true), true)), + NullabilityCase( + inputType = array(struct(int, false), false), + expectedTypeAsNullable = array(struct(int, true), true), + expectedTypeAsFullyNullable = array(struct(int, true), true)), + // typeAsNullable leaves maps without struct keys or values as they are. + NullabilityCase( + inputType = map(int, false), + expectedTypeAsNullable = map(int, false), + expectedTypeAsFullyNullable = map(int, true)), + NullabilityCase( + inputType = map(array(int, false), false), + expectedTypeAsNullable = map(array(int, false), false), + expectedTypeAsFullyNullable = map(array(int, true), true)), + NullabilityCase( + inputType = map(map(int, false), false), + expectedTypeAsNullable = map(map(int, false), false), + expectedTypeAsFullyNullable = map(map(int, true), true)), + NullabilityCase( + inputType = map(struct(int, false), false), + expectedTypeAsNullable = map(struct(int, true), true), + expectedTypeAsFullyNullable = map(struct(int, true), true)), + NullabilityCase( + inputType = MapType(struct(int, false), int, valueContainsNull = false), + expectedTypeAsNullable = MapType(struct(int, true), int, valueContainsNull = true), + expectedTypeAsFullyNullable = MapType(struct(int, true), int, valueContainsNull = true)), + // Both make everything nested in a struct nullable. + NullabilityCase( + inputType = struct(map(array(int, false), false), false), + expectedTypeAsNullable = struct(map(array(int, true), true), true), + expectedTypeAsFullyNullable = struct(map(array(int, true), true), true))) + + cases.foreach { testCase => + val inputType = testCase.inputType + assert(SchemaUtils.typeAsNullable(inputType) == testCase.expectedTypeAsNullable, + s"typeAsNullable(${inputType.json})") + assert(SchemaUtils.typeAsFullyNullable(inputType) == testCase.expectedTypeAsFullyNullable, + s"typeAsFullyNullable(${inputType.json})") + } + } + //////////////////////////// // checkFieldNames //////////////////////////// From ed65441936642b6e3881596b9d9375757ddc5687 Mon Sep 17 00:00:00 2001 From: Dhruv Arya Date: Mon, 16 Nov 2026 13:41:15 -0800 Subject: [PATCH 03/44] [Spark] Reconstruct AMT commit change files per state reconstruction implementation (#8149) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Reconstruct the change files of an AMT commit per state reconstruction implementation. The change file reconstruction decodes each manifest row into an `AMTDataEntryExtended` and converts it with `DataEntryResolver`, while the columnar state reconstruction builds the same `AddFile`s as columns. This gives the columnar implementation a change file read built from those columns, so it has a single `AddFile` derivation. The per-row implementation keeps its read and stays the default and the fallback. Review it commit by commit in the stacked history this was exported from; the change is: - `trackingDerivedChangeActions` and `mdvDerivedChangeActions` are declared on `AMTCheckpointProviderImpl`. `PerRowAMTCheckpointProvider` keeps the existing per-row code. `ColumnarAMTCheckpointProvider` builds them from its `AddFile` columns. - Columnar change files: a live entry becomes its `add` column, stamped with the commit-level `dataChange` and without a back reference. Any other entry becomes a `RemoveFile` built from that `add` the way `removeWithTimestamp` builds it. `removeFileColumn` maps every `RemoveFile` field explicitly, so a new field fails the read until it is mapped. - `rootDataEntries` and `leafDataEntries` are shared by the snapshot reads, the MDV read and the tracking-derived change file read. `leafEntriesWithRowIdPrefix` is replaced by `leafDataEntries`. - `PerRowAMTCheckpointProvider` and `ColumnarAMTCheckpointProvider` move into their own files; `AMTCheckpointProvider` is no longer sealed. ## How was this patch tested? `AMTCommitReconstructionSuite` runs every test with both implementations and compares the reconstructed change files with the committed ones (adds, removes and MDV-derived removes). It also asserts the two implementations produce identical actions field by field, and that each reconstructed `RemoveFile` equals `AddFile.removeWithTimestamp` of the previous `AddFile`. `AMTAddFileFieldCoverageSuite` pins the `RemoveFile` fields and calls `removeFileColumn` for each. `AMTAddFileReconstructionSuite` checks that both implementations reject a leaf entry read from a manifest that is not one of its parent's leaves. ## Does this PR introduce _any_ user-facing changes? No. Co-authored-by: Isaac --- .../sql/delta/amt/AMTCheckpointProvider.scala | 134 ++++-------------- .../amt/ColumnarAMTCheckpointProvider.scala | 90 ++++++++++++ .../amt/PerRowAMTCheckpointProvider.scala | 53 +++++++ .../amt/AMTAddFileFieldCoverageSuite.scala | 60 +++++++- .../amt/AMTAddFileReconstructionSuite.scala | 35 +++++ .../amt/AMTCommitReconstructionSuite.scala | 68 ++++++++- 6 files changed, 323 insertions(+), 117 deletions(-) create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/amt/ColumnarAMTCheckpointProvider.scala create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/amt/PerRowAMTCheckpointProvider.scala diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala index 28ac76da075..1f37e2105bc 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala @@ -47,7 +47,7 @@ import org.apache.spark.sql.catalyst.types.DataTypeUtils.toAttributes import org.apache.spark.sql.execution.datasources.FileFormat.{FILE_PATH, METADATA_NAME} import org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat import org.apache.spark.sql.expressions.Window -import org.apache.spark.sql.functions.{coalesce, col, concat, element_at, lit, raise_error, struct, sum, udf, when} +import org.apache.spark.sql.functions.{coalesce, col, element_at, lit, struct, sum, when} import org.apache.spark.sql.types.{IntegerType, LongType, MapType, StringType, StructField, StructType} /** @@ -118,7 +118,7 @@ trait AMTCheckpointProviderBase * [[liveLeafManifestAbsolutePaths]] to resolve it against the table root. * @param tableRoot The table's data path. */ -sealed abstract class AMTCheckpointProvider( +abstract class AMTCheckpointProvider( override val manifestCommitVersion: Long, override val checkpointAction: Checkpoint, val leaves: Seq[DataManifestEntry], @@ -196,100 +196,6 @@ abstract class LazyCompleteAMTCheckpointProvider( } -/** - * An [[AMTCheckpointProvider]] whose state reconstruction decodes every manifest entry into an - * [[AMTCheckpointProvider.AMTDataEntryExtended]] and converts it to an `AddFile` on the executors. - * The default, kept as the fallback for [[ColumnarAMTCheckpointProvider]]. - */ -final class PerRowAMTCheckpointProvider( - manifestCommitVersion: Long, - checkpointAction: Checkpoint, - leaves: Seq[DataManifestEntry], - tableRoot: Path) - extends AMTCheckpointProvider(manifestCommitVersion, checkpointAction, leaves, tableRoot) { - - override protected def rootLiveAddSingleActions( - spark: SparkSession, deltaLog: DeltaLog): Dataset[SingleAction] = { - val index = DeltaLogFileIndex( - DeltaLogFileIndex.CHECKPOINT_FILE_FORMAT_PARQUET, Array(rootFile)) - val entries = liveDataEntries(deltaLog, index) - toAddSingleActions(entries, dataEntryResolverProvider(parentLeaves = Seq.empty)) - } - - override protected def leafLiveAddSingleActions(deltaLog: DeltaLog): Dataset[SingleAction] = - toAddSingleActions( - loadLeafDataEntriesWithRowIdPrefix(deltaLog, liveLeavesWithManifestFilters), - dataEntryResolverProvider(parentLeaves = liveLeaves)) - - override private[amt] def readLiveRootDataEntries( - spark: SparkSession, deltaLog: DeltaLog): Seq[AddFile] = - AMTCheckpointProvider.readLiveRootDataEntries(deltaLog, checkpointAction) -} - -/** - * An [[AMTCheckpointProvider]] whose state reconstruction builds each `AddFile` field as a column - * over the persisted manifest rows (see [[addFileColumn]]). Enabled by - * [[DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED]]. - * - * @param rootInfo The root's leaf pointers and optional prefetched rows. - */ -final class ColumnarAMTCheckpointProvider( - manifestCommitVersion: Long, - checkpointAction: Checkpoint, - tableRoot: Path, - private val rootInfo: AMTRootInfo) - extends AMTCheckpointProvider( - manifestCommitVersion, checkpointAction, rootInfo.leaves, tableRoot) { - - override protected def rootLiveAddSingleActions( - spark: SparkSession, deltaLog: DeltaLog): Dataset[SingleAction] = { - // Reuse the prefetched root if possible. - val entries = rootInfo.toDF(spark).map { root => - // The shared back-reference expression requires a non-null pos, unused for root entries. - withRootEntryContext(dataEntries(root.withColumn("pos", lit(0)))) - }.getOrElse(rootEntries(deltaLog)) - toAddSingleActions( - withStatuses(entries, Tracking.Status.liveEntryStatuses), - baseRowId = col("tracking.first_row_id")) - } - - override protected def leafLiveAddSingleActions(deltaLog: DeltaLog): Dataset[SingleAction] = - toAddSingleActions( - withStatuses( - leafEntriesWithRowIdPrefix(deltaLog, liveLeavesWithManifestFilters), - Tracking.Status.liveEntryStatuses), - baseRowId = inheritedBaseRowId) - - /** Reuses prefetched root for incremental writes as well as snapshot state reconstruction. */ - override private[amt] def readLiveRootDataEntries( - spark: SparkSession, deltaLog: DeltaLog): Seq[AddFile] = - rootLiveAddSingleActions(spark, deltaLog).collect().toSeq.map(_.add) -} - -object ColumnarAMTCheckpointProvider { - /** RFC-2396 encoding of an AMT `location`, as [[DataEntry.toAddFile]] does. */ - private[amt] val encodePath = - udf((location: String) => SparkPath.fromPathString(location).urlEncoded) - - /** Fails the read of an entry row with `reason`, naming the entry's data file. */ - private[amt] def malformedEntry(reason: Column*): Column = - raise_error(concat( - Seq(lit("Malformed AMT data entry '"), col("location"), lit("': ")) ++ reason: _*)) - - /** An AMT deletion vector struct -> Delta's descriptor, as [[DeletionVector.toDescriptor]]. */ - private[amt] def toDescriptor(tableRoot: Path) = udf { (dv: Row) => - Option(dv).map { dv => - DeletionVector.toDescriptor( - DeletionVector( - location = dv.getAs[String]("location"), - offset = dv.getAs[Long]("offset"), - size_in_bytes = dv.getAs[Long]("size_in_bytes"), - cardinality = dv.getAs[Long]("cardinality")), - tableRoot) - }.orNull - } -} - trait AMTCheckpointProviderImpl extends CheckpointProvider { self: AMTCheckpointProvider => @@ -453,7 +359,7 @@ trait AMTCheckpointProviderImpl extends CheckpointProvider { * Adds the entry context of entry rows read from `leaves`: the location of the leaf a row was * read from and the tracking its entries inherit from the leaf's root pointer. */ - private def withLeafEntryContext( + private[amt] def withLeafEntryContext( entries: DataFrame, leaves: Seq[DataManifestEntry]): DataFrame = { val tableRootString = tableRoot.toString val contextType = StructType(Seq( @@ -470,9 +376,14 @@ trait AMTCheckpointProviderImpl extends CheckpointProvider { parent.file_sequence_number, parent.first_row_id) }.toMap - val context = element_at( - Column(Literal.create(contextByManifestPath, MapType(StringType, contextType))), - col("leafPath")) + // The leaf scan reads exactly `leaves`, so a miss is a bug. Fail the read rather than leave + // the inherited fields null. + val context = coalesce( + element_at( + Column(Literal.create(contextByManifestPath, MapType(StringType, contextType))), + col("leafPath")), + ColumnarAMTCheckpointProvider.malformedEntry( + lit("no leaf manifest matches "), col("leafPath"), lit("."))) entries.select(col("*") +: lit(false).as(IS_ROOT_ENTRY_COLUMN) +: contextType.fieldNames.toIndexedSeq.map(name => context.getField(name).as(name)): _*) } @@ -1053,19 +964,24 @@ trait AMTCheckpointProviderImpl extends CheckpointProvider { */ private def removeFileStruct(timestamp: Column, dataChange: Column): Column = { val removeFileSchema = Action.logSchema("remove").dataType.asInstanceOf[StructType] - val addFileFieldNames = Action.addFileSchema.fieldNames.toSet struct(removeFileSchema.fields.toIndexedSeq.map { field => - (field.name match { - case "deletionTimestamp" => timestamp - case "dataChange" => dataChange - case "extendedFileMetadata" => lit(true) - case "snapshotId" | "backReference" => lit(null) - case name if addFileFieldNames.contains(name) => col("add").getField(name) - case _ => lit(null) - }).cast(field.dataType).as(field.name) + removeFileColumn(field, timestamp, dataChange).cast(field.dataType).as(field.name) }: _*) } + /** + * The RemoveFile field `field` of [[removeFileStruct]]. No fallback, so a RemoveFile field that + * AddFile does not have fails here until it is mapped. + */ + private[amt] def removeFileColumn( + field: StructField, timestamp: Column, dataChange: Column): Column = field.name match { + case "deletionTimestamp" => timestamp + case "dataChange" => dataChange + case "extendedFileMetadata" => lit(true) + case "snapshotId" | "backReference" => lit(null) + case name if Action.addFileSchema.fieldNames.contains(name) => col("add").getField(name) + } + /** * The AddFile and RemoveFile actions of [[reconstructChangeFiles]], stamped * with the commit-level `dataChange` and `commitTimestamp`, and optionally ordered. diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/ColumnarAMTCheckpointProvider.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/ColumnarAMTCheckpointProvider.scala new file mode 100644 index 00000000000..47e8e322823 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/ColumnarAMTCheckpointProvider.scala @@ -0,0 +1,90 @@ +/* + * 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.amt + +import org.apache.spark.sql.delta.DeltaLog +import org.apache.spark.sql.delta.actions.{AddFile, Checkpoint, SingleAction} +import org.apache.spark.sql.delta.sources.DeltaSQLConf +import org.apache.hadoop.fs.Path + +import org.apache.spark.paths.SparkPath +import org.apache.spark.sql.{Column, Dataset, Row, SparkSession} +import org.apache.spark.sql.functions.{col, concat, lit, raise_error, udf} + +/** + * An [[AMTCheckpointProvider]] whose state reconstruction builds each `AddFile` field as a column + * over the persisted manifest rows (see [[addFileColumn]]). Enabled by + * [[DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED]]. + * + * @param rootInfo The root's leaf pointers and optional prefetched rows. + */ +final class ColumnarAMTCheckpointProvider( + manifestCommitVersion: Long, + checkpointAction: Checkpoint, + tableRoot: Path, + private val rootInfo: AMTRootInfo) + extends AMTCheckpointProvider( + manifestCommitVersion, checkpointAction, rootInfo.leaves, tableRoot) { + + override protected def rootLiveAddSingleActions( + spark: SparkSession, deltaLog: DeltaLog): Dataset[SingleAction] = { + // Reuse the prefetched root if possible. + val entries = rootInfo.toDF(spark).map { root => + // The shared back-reference expression requires a non-null pos, unused for root entries. + withRootEntryContext(dataEntries(root.withColumn("pos", lit(0)))) + }.getOrElse(rootEntries(deltaLog)) + toAddSingleActions( + withStatuses(entries, Tracking.Status.liveEntryStatuses), + baseRowId = col("tracking.first_row_id")) + } + + override protected def leafLiveAddSingleActions(deltaLog: DeltaLog): Dataset[SingleAction] = + toAddSingleActions( + withStatuses( + leafEntriesWithRowIdPrefix(deltaLog, liveLeavesWithManifestFilters), + Tracking.Status.liveEntryStatuses), + baseRowId = inheritedBaseRowId) + + /** Reuses prefetched root for incremental writes as well as snapshot state reconstruction. */ + override private[amt] def readLiveRootDataEntries( + spark: SparkSession, deltaLog: DeltaLog): Seq[AddFile] = + rootLiveAddSingleActions(spark, deltaLog).collect().toSeq.map(_.add) +} + +object ColumnarAMTCheckpointProvider { + /** RFC-2396 encoding of an AMT `location`, as [[DataEntry.toAddFile]] does. */ + private[amt] val encodePath = + udf((location: String) => SparkPath.fromPathString(location).urlEncoded) + + /** Fails the read of an entry row with `reason`, naming the entry's data file. */ + private[amt] def malformedEntry(reason: Column*): Column = + raise_error(concat( + Seq(lit("Malformed AMT data entry '"), col("location"), lit("': ")) ++ reason: _*)) + + /** An AMT deletion vector struct -> Delta's descriptor, as [[DeletionVector.toDescriptor]]. */ + private[amt] def toDescriptor(tableRoot: Path) = udf { (dv: Row) => + Option(dv).map { dv => + DeletionVector.toDescriptor( + DeletionVector( + location = dv.getAs[String]("location"), + offset = dv.getAs[Long]("offset"), + size_in_bytes = dv.getAs[Long]("size_in_bytes"), + cardinality = dv.getAs[Long]("cardinality")), + tableRoot) + }.orNull + } +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/PerRowAMTCheckpointProvider.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/PerRowAMTCheckpointProvider.scala new file mode 100644 index 00000000000..c2e1b55a212 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/PerRowAMTCheckpointProvider.scala @@ -0,0 +1,53 @@ +/* + * 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.amt + +import org.apache.spark.sql.delta.{DeltaLog, DeltaLogFileIndex} +import org.apache.spark.sql.delta.actions.{AddFile, Checkpoint, SingleAction} +import org.apache.hadoop.fs.Path + +import org.apache.spark.sql.{Dataset, SparkSession} + +/** + * An [[AMTCheckpointProvider]] whose state reconstruction decodes every manifest entry into an + * [[AMTCheckpointProvider.AMTDataEntryExtended]] and converts it to an `AddFile` on the executors. + * The default, kept as the fallback for [[ColumnarAMTCheckpointProvider]]. + */ +final class PerRowAMTCheckpointProvider( + manifestCommitVersion: Long, + checkpointAction: Checkpoint, + leaves: Seq[DataManifestEntry], + tableRoot: Path) + extends AMTCheckpointProvider(manifestCommitVersion, checkpointAction, leaves, tableRoot) { + + override protected def rootLiveAddSingleActions( + spark: SparkSession, deltaLog: DeltaLog): Dataset[SingleAction] = { + val index = DeltaLogFileIndex( + DeltaLogFileIndex.CHECKPOINT_FILE_FORMAT_PARQUET, Array(rootFile)) + val entries = liveDataEntries(deltaLog, index) + toAddSingleActions(entries, dataEntryResolverProvider(parentLeaves = Seq.empty)) + } + + override protected def leafLiveAddSingleActions(deltaLog: DeltaLog): Dataset[SingleAction] = + toAddSingleActions( + loadLeafDataEntriesWithRowIdPrefix(deltaLog, liveLeavesWithManifestFilters), + dataEntryResolverProvider(parentLeaves = liveLeaves)) + + override private[amt] def readLiveRootDataEntries( + spark: SparkSession, deltaLog: DeltaLog): Seq[AddFile] = + AMTCheckpointProvider.readLiveRootDataEntries(deltaLog, checkpointAction) +} diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileFieldCoverageSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileFieldCoverageSuite.scala index a707a3ea133..7ebc35a19ab 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileFieldCoverageSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileFieldCoverageSuite.scala @@ -18,10 +18,11 @@ package org.apache.spark.sql.delta.amt import scala.reflect.runtime.universe._ -import org.apache.spark.sql.delta.actions.{Action, AddFile} +import org.apache.spark.sql.delta.actions.{Action, AddFile, RemoveFile} import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.functions.lit +import org.apache.spark.sql.types.StructType /** * Pins the fields of [[AddFile]] and of the AMT types the DataEntry -> AddFile conversion reads, @@ -30,7 +31,8 @@ import org.apache.spark.sql.functions.lit * * Reflection only sees constructor parameters, so a field added to a case class is caught even * when nothing else in the test refers to it. `addFileColumn` is also called for every - * [[AddFile]] field, so a field it has no mapping for fails here rather than at read time. + * [[AddFile]] field, so a field it has no mapping for fails here rather than at read time. The + * [[RemoveFile]]s of the change files are pinned and checked the same way. */ class AMTAddFileFieldCoverageSuite extends AMTSyntheticTreeTestBase { @@ -39,6 +41,28 @@ class AMTAddFileFieldCoverageSuite extends AMTSyntheticTreeTestBase { "whether each added or removed field needs a transformation in the conversion, then " + "update the expected map in AMTAddFileFieldCoverageSuite." + private val removeFileUpdateInstructions = + "Revisit removeFileColumn in AMTCheckpointProvider and AddFile.removeWithTimestamp, " + + "decide whether each added or removed field needs a transformation in the change files, " + + "then update the expected map in AMTAddFileFieldCoverageSuite." + + private val expectedRemoveFileFields: Map[String, String] = Map( + "path" -> "AddFile.path", + "deletionTimestamp" -> "the commit timestamp", + "dataChange" -> "the commit-level dataChange", + "extendedFileMetadata" -> "always true", + "partitionValues" -> "AddFile.partitionValues", + "size" -> "AddFile.size", + "tags" -> "AddFile.tags", + "deletionVector" -> "AddFile.deletionVector", + "baseRowId" -> "AddFile.baseRowId", + "defaultRowCommitVersion" -> "AddFile.defaultRowCommitVersion", + "stats" -> "AddFile.stats", + "backReference" -> "null, as change files carry no back reference", + "snapshotId" -> "null, stamped by OptimisticTransaction during commit", + "modifiedSnapshotId" -> "AddFile.modifiedSnapshotId" + ) + private val expectedAddFileFields: Map[String, String] = Map( "path" -> "DataEntry.location, URL-encoded (encodePath / toAddFile)", "partitionValues" -> "DataEntry.partition, normalized via the metadata partition schema", @@ -122,6 +146,30 @@ class AMTAddFileFieldCoverageSuite extends AMTSyntheticTreeTestBase { } } + test("removeFileColumn maps every RemoveFile field") { + withSyntheticTree("amt_remove_file_column_fields") { tree => + val provider = tree.provider(Seq.empty) + // `removeFileColumn` has no fallback case, so an unmapped field throws a MatchError. + val removeFileSchema = Action.logSchema("remove").dataType.asInstanceOf[StructType] + val unmapped = removeFileSchema.fields.toSeq.filter { field => + try { + provider.removeFileColumn(field, timestamp = lit(0L), dataChange = lit(true)) + false + } catch { + case _: MatchError => true + } + }.map(_.name) + assert(unmapped.isEmpty, + "removeFileColumn has no mapping for RemoveFile fields " + + unmapped.mkString("[", ", ", "]") + ". " + removeFileUpdateInstructions) + } + } + + test("RemoveFile fields are all reviewed for the AMT change files") { + assertReviewed( + "RemoveFile", typeOf[RemoveFile], expectedRemoveFileFields, removeFileUpdateInstructions) + } + test("AddFile fields are all reviewed for the AMT conversion") { assertReviewed("AddFile", typeOf[AddFile], expectedAddFileFields) } @@ -142,14 +190,18 @@ class AMTAddFileFieldCoverageSuite extends AMTSyntheticTreeTestBase { assertReviewed("AMTPassthrough", typeOf[AMTPassthrough], expectedAMTPassthroughFields) } - private def assertReviewed(typeName: String, tpe: Type, reviewed: Map[String, String]): Unit = { + private def assertReviewed( + typeName: String, + tpe: Type, + reviewed: Map[String, String], + instructions: String = updateInstructions): Unit = { val actual = constructorFields(tpe) val added = actual.filterNot(reviewed.contains).sorted val removed = reviewed.keys.filterNot(actual.contains).toSeq.sorted if (added.nonEmpty || removed.nonEmpty) { fail( typeName + " fields changed. Added: " + added.mkString("[", ", ", "]") + - ". Removed: " + removed.mkString("[", ", ", "]") + ". " + updateInstructions) + ". Removed: " + removed.mkString("[", ", ", "]") + ". " + instructions) } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileReconstructionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileReconstructionSuite.scala index 36a2878f736..42890252e13 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileReconstructionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTAddFileReconstructionSuite.scala @@ -21,6 +21,7 @@ import org.apache.spark.sql.delta.actions.{AddFile, BackReference, Checkpoint, C import org.apache.spark.sql.delta.implicits.singleActionEncoder import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.util.JsonUtils +import org.apache.hadoop.fs.Path import org.apache.spark.paths.SparkPath import org.apache.spark.sql.functions.{col, lit, struct} @@ -466,6 +467,40 @@ class AMTAddFileReconstructionSuite extends AMTSyntheticTreeTestBase { } } + test("a leaf entry read from a manifest that is not one of the leaves is rejected") { + // Both implementations look up a leaf entry's parent by the manifest it was read from. The + // leaf scan reads exactly the leaves the lookup is built from, so a miss is a bug: both fail. + withSyntheticTree("amt_add_file_unknown_leaf") { tree => + val leaf = tree.writeLeaf(Seq(dataEntry("data/a.parquet", recordCount = 10L))) + val checkpoint = tree.checkpoint(Seq(leafPointer(leaf).wrap)) + val provider = AMTCheckpointProvider.fromCheckpoint( + spark, tree.deltaLog, checkpoint, manifestCommitVersion = checkpoint.version) + val unknownLeaf = + SparkPath.fromPath(new Path(tree.deltaLog.dataPath, "unknown.parquet")).urlEncoded + val entries = + spark.createDataFrame(Seq(("data/a.parquet", unknownLeaf))).toDF("location", "leafPath") + val columnarError = intercept[Exception] { + provider.withLeafEntryContext(entries, leaves = Seq.empty).collect() + } + assert(causeMessages(columnarError).contains( + "Malformed AMT data entry 'data/a.parquet': no leaf manifest matches " + unknownLeaf + "."), + causeMessages(columnarError)) + + val perRowResolver = AMTCheckpointProvider.DataEntryResolverProvider( + tableRoot = tree.deltaLog.dataPath, + urlEncodedRootManifestPath = "unused", + parentTrackingByLeafLocation = Map.empty).createResolver() + val perRowError = intercept[NoSuchElementException] { + perRowResolver.resolve(AMTCheckpointProvider.AMTDataEntryExtended( + dataEntry("data/a.parquet", recordCount = 10L).wrap, + leafPath = unknownLeaf, + pos = 0L, + precedingNullFirstRowIdRecords = 0L)) + } + assert(perRowError.getMessage.contains("unknown.parquet"), perRowError.getMessage) + } + } + test("a leaf DATA entry with manifest_info is rejected") { withSyntheticTree("amt_add_file_data_manifest_info") { tree => val leaf = tree.corruptLeaf( diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCommitReconstructionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCommitReconstructionSuite.scala index a11b83be040..169908f2d3b 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCommitReconstructionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCommitReconstructionSuite.scala @@ -17,9 +17,12 @@ package org.apache.spark.sql.delta.amt import org.apache.spark.sql.delta.DeltaLog -import org.apache.spark.sql.delta.actions.{Action, AddFile, FileAction, RemoveFile} +import org.apache.spark.sql.delta.actions.{Action, AddFile, FileAction, RemoveFile, SingleAction} +import org.apache.spark.sql.delta.implicits.singleActionEncoder import org.apache.hadoop.fs.Path +import org.apache.spark.sql.functions.col + /** * Tests for reconstructing an inline manifest commit's file actions from the AMT it wrote. * @@ -61,6 +64,23 @@ class AMTCommitReconstructionSuite extends AMTIncrementalWriteTestBase { (version, provider.reconstructFileActions(deltaLog, dataChange, commitTimestamp)) } + /** `actions` as their sorted log JSON, which compares every field by value. */ + private def asJson(actions: Seq[FileAction]): Seq[String] = actions.map(_.json).sorted + + /** The live AddFiles state reconstruction builds from the tree of manifest commit `version`. */ + private def addFilesAt(deltaLog: DeltaLog, version: Long): Seq[AddFile] = { + val checkpoint = checkpointAt(deltaLog, version) + .getOrElse(fail(s"v$version must be a manifest commit")) + AMTCheckpointProvider.fromCheckpoint(spark, deltaLog, checkpoint, version) + .loadActionsForStateReconstruction(spark, deltaLog) + .getOrElse(fail("AMT provider must contribute reconstructed actions.")) + .where(col("add").isNotNull) + .as[SingleAction] + .collect() + .map(_.add) + .toSeq + } + /** * Commits `actions` as an inline manifest commit and asserts its tree reconstructs the expected * number of AddFiles and RemoveFiles. The commit-time check already compares the reconstructed @@ -183,17 +203,57 @@ class AMTCommitReconstructionSuite extends AMTIncrementalWriteTestBase { test("stamps the given dataChange and commit timestamp on every reconstructed action") { withLeafPackedAmtTable { deltaLog => - // A compaction: the tree records its delete and insert even though neither changes data. + withInline { commitAmt(deltaLog, Seq(fakeAdd(31))) } + // A compaction: the tree records its deletes (from a leaf and, as a tombstone, from the + // root) and its insert even though none of them changes data. val actions = Seq[Action]( removeOf(deltaLog, 1).copy(dataChange = false), + removeOf(deltaLog, 31).copy(dataChange = false), fakeAdd(200, dataChange = false)) val (_, reconstructed) = commitAndReconstruct(deltaLog, actions, dataChange = false, commitTimestamp = 1234L) assert(reconstructed.map(a => (fileName(a), a.isInstanceOf[AddFile])).toSet === - Set((fakeAdd(1).path, false), (fakeAdd(200).path, true))) + Set((fakeAdd(1).path, false), (fakeAdd(31).path, false), (fakeAdd(200).path, true))) assert(reconstructed.forall(!_.dataChange), s"got $reconstructed") assert(reconstructed.collect { case r: RemoveFile => r.deletionTimestamp } === - Seq(Some(1234L))) + Seq(Some(1234L), Some(1234L))) + } + } + + test("reconstructs the row tracking fields of AddFiles spilled into new leaves") { + withLeafPackedAmtTable { deltaLog => + val leavesBefore = leafPointers(deltaLog.update()).size + // The new leaves leave first_row_id to inheritance, so their adds take it from the row-ID + // prefix over the leaf. + val (_, reconstructed) = commitAndReconstruct(deltaLog, (100 to 124).map(fakeAdd)) + assert(leafPointers(deltaLog.update()).size > leavesBefore, + "the insert must spill at least one new leaf for this scenario to be meaningful.") + val adds = reconstructed.collect { case a: AddFile => a } + assert(adds.size == 25 && adds.size == reconstructed.size, s"got $reconstructed") + assert(adds.forall(a => a.baseRowId.isDefined && a.defaultRowCommitVersion.isDefined), + s"every add must carry its row tracking fields, got $adds") + assert(adds.flatMap(_.baseRowId).distinct.size == adds.size, + s"every add must have its own row IDs, got $adds") + } + } + + test("reconstructs RemoveFiles as AddFile.removeWithTimestamp builds them") { + withLeafPackedAmtTable { deltaLog => + withInline { commitAmt(deltaLog, Seq(fakeAdd(31))) } + val previousVersion = deltaLog.update().version + val deleted = Seq(removeOf(deltaLog, 1), removeOf(deltaLog, 31)) + val (_, reconstructed) = + commitAndReconstruct(deltaLog, deleted, dataChange = false, commitTimestamp = 1234L) + val previousAdds = addFilesAt(deltaLog, previousVersion).map(a => a.path -> a).toMap + // Change files carry no back reference. + val expected = deleted.map { remove => + previousAdds(remove.path).removeWithTimestamp(1234L, dataChange = false) + .copy(backReference = None) + } + val removes = reconstructed.collect { case r: RemoveFile => r } + assert(asJson(removes) === asJson(expected)) + assert(removes.forall(r => r.extendedFileMetadata.contains(true) && r.snapshotId.isEmpty), + s"got $removes") } } } From 426d277de689217b94a32610bf822af0b90dd059 Mon Sep 17 00:00:00 2001 From: Hao Sun Date: Mon, 16 Nov 2026 14:44:52 -0800 Subject: [PATCH 04/44] [Spark] Convert SnapshotManagerFactory to Scala (#8055) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other ## Description Convert `SnapshotManagerFactory` from a Java utility class to a Scala object and accept `Option[CatalogTable]`. Scala callers can pass catalog metadata directly, while Java callers use Scala `Option`. Preserve catalog selection, lookup timing, exceptions, and lazy path-based fallback. Keep the factory scoped to the v2 connector. Adapt the existing cache tests to scoped Scala-object spying, add the required test dependency, and open the Java reflection module for those tests on Java 17. Existing test cases and assertions are unchanged. ## How was this patch tested? Validated rebased head `dc2784b985f00d6543dd3be6a563d181e7be1b8e` against master `ef61df0920cec80f49c2142719f823dbf626c6ad` on Java 17 with Spark 4.2: ```sh build/sbt -DsparkVersion=4.2 \ "sparkV2/testOnly org.apache.spark.sql.delta.v2.tablemanager.CachedSnapshotManagerSuite org.apache.spark.sql.delta.v2.snapshot.unitycatalog.UCUtilsSuite" \ "spark/Test/compile" ``` All 42 tests passed: 35 cache tests and 7 UC utility tests. Unified compilation, including both Java changelog callers, and `git diff --check` passed. The rebase preserves the seven-file contribution scope and all existing assertions. ## Does this PR introduce _any_ user-facing changes? No. Signed-off-by: Hao Sun <86338940+HaoSun1993@users.noreply.github.com> --- build.sbt | 3 +- ...eltaV2ChangelogCatalogIntegrationTest.java | 4 +- ...taV2ChangelogDirectBatchExecutionTest.java | 14 ++-- .../v2/snapshot/SnapshotManagerFactory.java | 84 ------------------- .../v2/snapshot/SnapshotManagerFactory.scala | 76 +++++++++++++++++ .../tablemanager/CachedSnapshotManager.scala | 3 +- .../CachedSnapshotManagerSuite.scala | 50 ++++++----- 7 files changed, 115 insertions(+), 119 deletions(-) delete mode 100644 spark/v2/src/main/java/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.java create mode 100644 spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.scala diff --git a/build.sbt b/build.sbt index fdbd7b08d26..698ce412562 100644 --- a/build.sbt +++ b/build.sbt @@ -519,9 +519,10 @@ lazy val sparkV2 = { CrossSparkVersions.sparkDependentSettings(sparkVersion), exportJars := true, // Export as JAR to avoid classpath conflicts - Test / javaOptions ++= Seq("-ea"), + Test / javaOptions ++= Seq("-ea", "--add-opens=java.base/java.lang.reflect=ALL-UNNAMED"), libraryDependencies ++= junit5TestDependencies ++ Seq( "org.mockito" % "mockito-inline" % "4.11.0" % "test", + "org.mockito" %% "mockito-scala" % "1.17.14" % "test", "org.apache.spark" %% "spark-sql" % sparkArtifactVersion.value % "provided", "org.apache.spark" %% "spark-core" % sparkArtifactVersion.value % "provided", "org.apache.spark" %% "spark-catalyst" % sparkArtifactVersion.value % "provided", diff --git a/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogCatalogIntegrationTest.java b/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogCatalogIntegrationTest.java index 47c00752021..58832d5ce08 100644 --- a/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogCatalogIntegrationTest.java +++ b/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogCatalogIntegrationTest.java @@ -24,11 +24,11 @@ import org.apache.spark.sql.delta.v2.snapshot.SnapshotManagerFactory; import java.util.Arrays; import java.util.List; -import java.util.Optional; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.junit.jupiter.api.Test; +import scala.Option; /** * Integration tests for catalog-routed CDC entrypoint (TableCatalog.loadChangelog). @@ -107,7 +107,7 @@ private java.sql.Timestamp commitTimestamp(String tableLocation, long version) { // Reads through the kernel snapshot manager, so it works inside the STRICT block the test body // runs in. tableLocation is resolved by withHistoryTable before STRICT is set. DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tableLocation, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tableLocation, defaultKernelContext, Option.empty()); long millis = snapshotManager.loadSnapshotAt(version).timestamp(); return new java.sql.Timestamp(millis); } diff --git a/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogDirectBatchExecutionTest.java b/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogDirectBatchExecutionTest.java index fda3c0a090d..ec868c1eb54 100644 --- a/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogDirectBatchExecutionTest.java +++ b/spark-unified/src/test/scala-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogDirectBatchExecutionTest.java @@ -29,7 +29,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import org.apache.spark.sql.Row; import org.apache.spark.sql.catalyst.InternalRow; import org.apache.spark.sql.connector.catalog.Identifier; @@ -46,6 +45,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; +import scala.Option; /** * Direct (non-analyzer) batch execution contract test for Delta changelog classes. @@ -77,7 +77,7 @@ public void testDirectBatchExecutionWithExplicitExpectedRows(boolean enableDvs) spark.sql(String.format("DELETE FROM %s WHERE id = 1", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); StructType dataSchema = spark.table(tableName).schema(); long latestVersion = snapshotManager.loadLatestSnapshot().version(); Map commitTimestampsMicros = loadCommitTimestampsMicros(tableName); @@ -149,7 +149,7 @@ public void testRowTrackingMetadataReferences() throws Exception { spark.sql(String.format("INSERT INTO %s VALUES (1)", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); StructType dataSchema = spark.table(tableName).schema(); long latestVersion = snapshotManager.loadLatestSnapshot().version(); @@ -200,7 +200,7 @@ public void testUpdateProducesPairedDeleteAndInsert(boolean enableDvs) throws Ex spark.sql(String.format("UPDATE %s SET name = 'AliceX' WHERE id = 1", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); StructType dataSchema = spark.table(tableName).schema(); long latestVersion = snapshotManager.loadLatestSnapshot().version(); Map commitTimestampsMicros = loadCommitTimestampsMicros(tableName); @@ -273,7 +273,7 @@ public void testRangeSlicingNonZeroStart() throws Exception { spark.sql(String.format("INSERT INTO %s VALUES (3, 'Charlie')", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); StructType dataSchema = spark.table(tableName).schema(); Map commitTimestampsMicros = loadCommitTimestampsMicros(tableName); @@ -342,7 +342,7 @@ public void testChangelogWithReservedCharsInPath() throws Exception { spark.sql(String.format("INSERT INTO %s VALUES (1, 'Alice'), (2, 'Bob')", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); long latestVersion = snapshotManager.loadLatestSnapshot().version(); Map commitTimestampsMicros = loadCommitTimestampsMicros(tableName); @@ -407,7 +407,7 @@ public void testChangelogWithReservedCharsInDataFileNames() throws Exception { spark.sql(String.format("INSERT INTO %s VALUES (1, 'Alice'), (2, 'Bob')", tableName)); DeltaV2SnapshotManager snapshotManager = - SnapshotManagerFactory.create(tablePath, defaultKernelContext, Optional.empty()); + SnapshotManagerFactory.create(tablePath, defaultKernelContext, Option.empty()); long latestVersion = snapshotManager.loadLatestSnapshot().version(); Map commitTimestampsMicros = loadCommitTimestampsMicros(tableName); diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.java deleted file mode 100644 index 4fc4420c070..00000000000 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (2025) 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.v2.snapshot; - -import io.delta.kernel.Meta; -import io.delta.kernel.unitycatalog.UCCatalogManagedClient; -import io.delta.storage.commit.uccommitcoordinator.UCClient; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import org.apache.spark.annotation.Experimental; -import org.apache.spark.sql.SparkSession; -import org.apache.spark.sql.catalyst.catalog.CatalogTable; -import org.apache.spark.sql.delta.coordinatedcommits.UCTokenBasedRestClientFactory$; -import org.apache.spark.sql.delta.v2.interop.DeltaV2SnapshotManager; -import org.apache.spark.sql.delta.v2.kernel.KernelContext; -import org.apache.spark.sql.delta.v2.snapshot.unitycatalog.UCManagedTableSnapshotManager; -import org.apache.spark.sql.delta.v2.snapshot.unitycatalog.UCTableInfo; -import org.apache.spark.sql.delta.v2.snapshot.unitycatalog.UCUtils; -import scala.Option; - -/** - * Factory for creating {@link DeltaV2SnapshotManager} instances. - * - *

This factory determines the appropriate snapshot manager based on the table configuration: - * - *

    - *
  • For Unity Catalog managed tables: creates {@link UCManagedTableSnapshotManager} - *
  • For path-based tables: creates {@link PathBasedSnapshotManager} - *
- */ -@Experimental -public final class SnapshotManagerFactory { - - // Utility class - no instances - private SnapshotManagerFactory() {} - - /** - * Creates a snapshot manager for the given table. - * - * @param tablePath the filesystem path to the Delta table - * @param kernelContext the configured context to use for table operations - * @param catalogTable optional Spark catalog table metadata - * @return a {@link DeltaV2SnapshotManager} appropriate for the table type - */ - public static DeltaV2SnapshotManager create( - String tablePath, KernelContext kernelContext, Optional catalogTable) { - - if (catalogTable.isPresent()) { - Option ucTableInfo = - UCUtils.extractTableInfo(catalogTable.get(), SparkSession.active()); - if (ucTableInfo.isDefined()) { - return createUCManagedSnapshotManager(ucTableInfo.get(), kernelContext); - } - // Catalog table without UC metadata falls back to path-based handling. - } - - // Default: path-based snapshot manager for non-UC tables - return new PathBasedSnapshotManager(tablePath, kernelContext); - } - - private static UCManagedTableSnapshotManager createUCManagedSnapshotManager( - UCTableInfo tableInfo, KernelContext kernelContext) { - Map ucConfig = new HashMap<>(tableInfo.toUcConfig()); - ucConfig.put("appVersions.Kernel", Meta.KERNEL_VERSION); - ucConfig.put("appVersions.Delta V2 connector", "true"); - UCClient ucClient = UCTokenBasedRestClientFactory$.MODULE$.createUCClient(ucConfig); - UCCatalogManagedClient ucCatalogClient = new UCCatalogManagedClient(ucClient); - return new UCManagedTableSnapshotManager(ucCatalogClient, tableInfo, kernelContext); - } -} diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.scala new file mode 100644 index 00000000000..08c5b37acfc --- /dev/null +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/snapshot/SnapshotManagerFactory.scala @@ -0,0 +1,76 @@ +/* + * Copyright (2025) 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.v2.snapshot + +import org.apache.spark.sql.delta.v2.interop.DeltaV2SnapshotManager +import org.apache.spark.sql.delta.v2.kernel.KernelContext +import org.apache.spark.sql.delta.coordinatedcommits.UCTokenBasedRestClientFactory +import org.apache.spark.sql.delta.v2.snapshot.unitycatalog.{UCManagedTableSnapshotManager, UCTableInfo, UCUtils} +import io.delta.kernel.{Meta => KernelMeta} +import io.delta.kernel.unitycatalog.{UCCatalogManagedClient => KernelUCCatalogManagedClient} + +import org.apache.spark.sql.SparkSession + +import org.apache.spark.annotation.Experimental +import org.apache.spark.sql.catalyst.catalog.CatalogTable + +/** + * Factory for creating [[DeltaV2SnapshotManager]] instances. + * + * This factory determines the appropriate snapshot manager based on the table configuration: + * - For Unity Catalog managed tables: creates `UCManagedTableSnapshotManager` + * - For path-based tables: creates [[PathBasedSnapshotManager]] + */ +@Experimental +private[v2] +object SnapshotManagerFactory { + + /** + * Creates a snapshot manager for the given table. + * + * @param tablePath the filesystem path to the Delta table + * @param kernelContext the configured context to use for table operations + * @param catalogTable optional Spark catalog table metadata + * @return a [[DeltaV2SnapshotManager]] appropriate for the table type + */ + def create( + tablePath: String, + kernelContext: KernelContext, + catalogTable: Option[CatalogTable]): DeltaV2SnapshotManager = { + val catalog = catalogTable.orNull + if (catalog != null) { + val ucTableInfo = UCUtils.extractTableInfo(catalog, SparkSession.active) + if (!ucTableInfo.isEmpty) { + return createUCManagedSnapshotManager(ucTableInfo.get, kernelContext) + } + // Catalog table without UC metadata falls back to path-based handling. + } + + // Default: path-based snapshot manager for non-UC tables + new PathBasedSnapshotManager(tablePath, kernelContext) + } + + private def createUCManagedSnapshotManager( + tableInfo: UCTableInfo, + kernelContext: KernelContext): UCManagedTableSnapshotManager = { + val ucConfig = tableInfo.toUcConfig() + ucConfig.put("appVersions.Kernel", KernelMeta.KERNEL_VERSION) + ucConfig.put("appVersions.Delta V2 connector", "true") + val ucClient = UCTokenBasedRestClientFactory.createUCClient(ucConfig) + val kernelUcCatalogClient = new KernelUCCatalogManagedClient(ucClient) + new UCManagedTableSnapshotManager(kernelUcCatalogClient, tableInfo, kernelContext) + } +} diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala index 12a1371d5ee..7f448ee0e25 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala @@ -19,7 +19,6 @@ import java.util.Objects import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.locks.ReentrantLock -import scala.jdk.OptionConverters._ import org.apache.spark.sql.delta.Snapshot import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -265,7 +264,7 @@ private[tablemanager] class CachedSnapshotManager( f(SnapshotManagerFactory.create( tablePath.toString, kernelContext, - catalogTableOpt.toJava)) + catalogTableOpt)) } private def latestSnapshotFreshnessThreshold(): Long = { diff --git a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala index 204d12397db..663f91b3c9c 100644 --- a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala +++ b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala @@ -17,7 +17,7 @@ package org.apache.spark.sql.delta.v2.tablemanager import java.io.File import java.net.URI -import java.util.{Collections, Optional} +import java.util.Collections import java.util.concurrent.{ ConcurrentLinkedQueue, CopyOnWriteArrayList, @@ -42,7 +42,9 @@ import org.apache.spark.sql.delta.v2.interop.{ } import org.apache.spark.sql.delta.v2.kernel.{KernelContext, KernelEngineFactory} import org.apache.spark.sql.delta.v2.snapshot.SnapshotManagerFactory -import org.mockito.Mockito.mockStatic +import org.mockito.ArgumentMatchers.any +import org.mockito.Mockito.doAnswer +import org.mockito.MockitoSugar.withObjectSpied import org.mockito.invocation.InvocationOnMock import org.mockito.stubbing.Answer import io.delta.kernel.exceptions.KernelException @@ -152,22 +154,19 @@ class CachedSnapshotManagerSuite storage = CatalogStorageFormat.empty, schema = new StructType()) val observedCatalogTables = new ConcurrentLinkedQueue[Option[CatalogTable]]() - val factoryMock = mockStatic( - classOf[SnapshotManagerFactory], + withSnapshotManagerFactoryMock( new Answer[DeltaV2SnapshotManager] { override def answer(invocation: InvocationOnMock): DeltaV2SnapshotManager = { - val catalogTable = invocation.getArgument[Optional[CatalogTable]](2) - observedCatalogTables.add( - if (catalogTable.isPresent) Some(catalogTable.get()) else None) + val catalogTable = invocation.getArgument[Option[CatalogTable]](2) + observedCatalogTables.add(catalogTable) throw new IllegalStateException("recorded catalog metadata") } - }) - val tableManager = new DeltaV2TableManagerImpl( - new Path(dir.getCanonicalPath), - Map.empty, - Some(legacyCatalogTable)) - val manager = tableManager.snapshotManager(Some(legacyCatalogTable)) - try { + }) { + val tableManager = new DeltaV2TableManagerImpl( + new Path(dir.getCanonicalPath), + Map.empty, + Some(legacyCatalogTable)) + val manager = tableManager.snapshotManager(Some(legacyCatalogTable)) val queryContext = DeltaV2QueryContext(Some(queryCatalogTable)) val kernelEngine = tableManager.kernelContext.getDefaultEngine() @@ -204,8 +203,6 @@ class CachedSnapshotManagerSuite legacyOperations.foreach(operation => assertRoutesWith(Some(legacyCatalogTable))(operation())) assert(observedCatalogTables.isEmpty) - } finally { - factoryMock.close() } } } @@ -231,16 +228,14 @@ class CachedSnapshotManagerSuite val laterCatalogTable = spark.sessionState.catalog .getTableMetadata(TableIdentifier(laterTableName)) val observedCatalogTables = new ConcurrentLinkedQueue[Option[CatalogTable]]() - val factoryMock = mockStatic( - classOf[SnapshotManagerFactory], + withSnapshotManagerFactoryMock( new Answer[DeltaV2SnapshotManager] { override def answer(invocation: InvocationOnMock): DeltaV2SnapshotManager = { - val catalogTable = invocation.getArgument[Optional[CatalogTable]](2) - observedCatalogTables.add( - if (catalogTable.isPresent) Some(catalogTable.get()) else None) + val catalogTable = invocation.getArgument[Option[CatalogTable]](2) + observedCatalogTables.add(catalogTable) invocation.callRealMethod().asInstanceOf[DeltaV2SnapshotManager] } - }) + }) { DeltaV2TableManagerCache.clearCache() try { val originalTable = new DeltaV2Table( @@ -269,14 +264,23 @@ class CachedSnapshotManagerSuite assert(observations.forall( _.exists(_.identifier == originalCatalogTable.identifier))) } finally { - factoryMock.close() DeltaV2TableManagerCache.clearCache() } + } } } } } + private def withSnapshotManagerFactoryMock( + answer: Answer[DeltaV2SnapshotManager])(f: => Unit): Unit = { + withObjectSpied[SnapshotManagerFactory.type] { + doAnswer(answer).when(SnapshotManagerFactory).create( + any[String](), any[KernelContext](), any[Option[CatalogTable]]()) + f + } + } + private def assertWaitsForSnapshotLock(thread: Thread): Unit = { val deadlineNanos = System.nanoTime() + TimeUnit.SECONDS.toNanos(30L) var stackTrace = thread.getStackTrace.toSeq From 94cdbbcb3961edac2cd04351f6378cd87a0428f4 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Mon, 16 Nov 2026 18:44:59 -0500 Subject: [PATCH 05/44] [Spark][DEDUP] Single helper for V2 CDC output schema (#8116) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Centralize construction of the three CDC output columns in one helper. Preserve nullable fields for the internal Parquet read schema and non-null fields for changelog output, matching the existing contracts. ## How was this patch tested? - `build/sbt "sparkV2/Test/javafmtCheck" "sparkV2/testOnly org.apache.spark.sql.delta.v2.read.cdc.CDCSchemaContextTest"` ## Does this PR introduce _any_ user-facing changes? No. --------- Signed-off-by: tdas Co-authored-by: omnigent --- .../v2/read/changelog/DeltaV2Changelog.java | 13 ++++--- .../read/changelog/DeltaV2ChangelogBatch.java | 7 +--- .../DeltaV2ChangelogScanBuilder.java | 8 +--- .../delta/v2/read/cdc/CDCSchemaContext.java | 37 +++++++++++-------- .../v2/read/cdc/CDCSchemaContextTest.java | 11 ++++++ 5 files changed, 41 insertions(+), 35 deletions(-) diff --git a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2Changelog.java b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2Changelog.java index c827e898ec2..bec66b776c7 100644 --- a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2Changelog.java +++ b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2Changelog.java @@ -2,6 +2,7 @@ import org.apache.spark.sql.delta.Snapshot; import org.apache.spark.sql.delta.v2.catalog.DeltaV2Table; +import org.apache.spark.sql.delta.v2.read.cdc.CDCSchemaContext; import org.apache.spark.sql.delta.v2.shims.CatalogV2UtilShims; import org.apache.spark.sql.delta.v2.utils.SchemaUtils; import org.apache.spark.sql.connector.catalog.Changelog; @@ -64,16 +65,16 @@ public Column[] columns() { // each per-commit Metadata against this same end-version schema. Snapshot endSnapshot = deltaV2Table.getSnapshotManager().loadSnapshotAt(endVersion); StructType endSchema = endSnapshot.schema(); - StructType cdcSchema = - endSchema - .add(METADATA_COLUMN, METADATA_STRUCT, false) - .add("_change_type", DataTypes.StringType, false) - .add("_commit_version", DataTypes.LongType, false) - .add("_commit_timestamp", DataTypes.TimestampType, false); + StructType cdcSchema = changelogSchema(endSchema); return CatalogV2UtilShims.structTypeToV2Columns(cdcSchema); } + static StructType changelogSchema(StructType dataSchema) { + return CDCSchemaContext.appendNonNullableCDCColumns( + dataSchema.add(METADATA_COLUMN, METADATA_STRUCT, false)); + } + // TODO: optimise to false when deletion vectors are guaranteed enabled across the entire // [startVersion, endVersion] range. DVs enabled over range produces no carry-overs. @Override diff --git a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogBatch.java b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogBatch.java index 8eee82ba56e..77c2076f585 100644 --- a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogBatch.java +++ b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogBatch.java @@ -47,7 +47,6 @@ import org.apache.spark.sql.execution.datasources.PartitionedFile; import org.apache.spark.sql.internal.SQLConf; import org.apache.spark.sql.sources.Filter; -import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; import org.apache.spark.unsafe.types.UTF8String; import scala.Tuple2; @@ -333,11 +332,7 @@ public PartitionReaderFactory createReaderFactory() { sqlConf, /* isWriteTimeCDCRead */ false); - StructType outputSchema = - readDataSchema - .add("_change_type", DataTypes.StringType, false) - .add("_commit_version", DataTypes.LongType, false) - .add("_commit_timestamp", DataTypes.TimestampType, false); + StructType outputSchema = CDCSchemaContext.appendNonNullableCDCColumns(readDataSchema); return new CDCPartitionReaderFactory(delegate, outputSchema); } diff --git a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogScanBuilder.java b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogScanBuilder.java index 5cc2f3a8279..e495f84d0a6 100644 --- a/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogScanBuilder.java +++ b/spark/v2/src/main/java-shims/spark-4.2-4.3/org/apache/spark/sql/delta/v2/read/changelog/DeltaV2ChangelogScanBuilder.java @@ -18,7 +18,6 @@ import org.apache.spark.sql.connector.read.Scan; import org.apache.spark.sql.connector.read.ScanBuilder; import org.apache.spark.sql.delta.DeltaErrors; -import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.StructType; import org.apache.spark.sql.util.CaseInsensitiveStringMap; @@ -77,12 +76,7 @@ public Scan build() { DeltaErrors.throwChangelogRowTrackingDisabledInRange(startVersion); } - StructType cdcSchema = - endSchema - .add(DeltaV2Changelog.METADATA_COLUMN, DeltaV2Changelog.METADATA_STRUCT, false) - .add("_change_type", DataTypes.StringType, false) - .add("_commit_version", DataTypes.LongType, false) - .add("_commit_timestamp", DataTypes.TimestampType, false); + StructType cdcSchema = DeltaV2Changelog.changelogSchema(endSchema); return new DeltaV2ChangelogScan( cdcSchema, commitRange, diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContext.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContext.java index 56f782eab28..4824d5a0283 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContext.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContext.java @@ -43,13 +43,7 @@ public class CDCSchemaContext implements Serializable { public static final int COMMIT_VERSION_IDX = 1; public static final int COMMIT_TIMESTAMP_IDX = 2; - private static final StructField[] CDC_FIELDS = - new StructField[] { - DataTypes.createStructField(CDC_TYPE_COLUMN, DataTypes.StringType, /* nullable= */ true), - DataTypes.createStructField(CDC_COMMIT_VERSION, DataTypes.LongType, /* nullable= */ true), - DataTypes.createStructField( - CDC_COMMIT_TIMESTAMP, DataTypes.TimestampType, /* nullable= */ true) - }; + private static final StructField[] CDC_FIELDS = appendCDCColumns(new StructType()).fields(); /** Read data schema augmented with CDC columns (for Parquet reader). */ private final StructType readDataSchemaWithCDC; @@ -105,6 +99,26 @@ public static StructField[] cdcFields() { return CDC_FIELDS.clone(); } + /** + * Appends nullable CDC columns for the Parquet read path, where schema evolution null-fills + * missing columns before {@link CDCReadFunction} fills them, matching V1 {@link + * CDCReader#cdcReadSchema}. + */ + public static StructType appendCDCColumns(StructType schema) { + return schema + .add(CDC_TYPE_COLUMN, DataTypes.StringType, true) + .add(CDC_COMMIT_VERSION, DataTypes.LongType, true) + .add(CDC_COMMIT_TIMESTAMP, DataTypes.TimestampType, true); + } + + /** Appends non-null CDC columns for changelog readers, which set all values for every file. */ + public static StructType appendNonNullableCDCColumns(StructType schema) { + return schema + .add(CDC_TYPE_COLUMN, DataTypes.StringType, false) + .add(CDC_COMMIT_VERSION, DataTypes.LongType, false) + .add(CDC_COMMIT_TIMESTAMP, DataTypes.TimestampType, false); + } + /** Returns true if the given field name is a CDC column. */ public static boolean isCDCColumn(String name) { return CDC_TYPE_COLUMN.equalsIgnoreCase(name) @@ -112,15 +126,6 @@ public static boolean isCDCColumn(String name) { || CDC_COMMIT_TIMESTAMP.equalsIgnoreCase(name); } - /** Appends the three CDC columns to the given schema. */ - public static StructType appendCDCColumns(StructType schema) { - StructType result = schema; - for (StructField field : CDC_FIELDS) { - result = result.add(field); - } - return result; - } - public StructType getReadDataSchemaWithCDC() { return readDataSchemaWithCDC; } diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContextTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContextTest.java index 2dcb70782a6..4fecc45a1e7 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContextTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/cdc/CDCSchemaContextTest.java @@ -164,6 +164,17 @@ void testAppendCDCColumns() { assertEquals(CDCSchemaContext.CDC_COMMIT_TIMESTAMP, augmented.fields()[4].name()); } + @Test + void testAppendNonNullableCDCColumns() { + StructType nonNullable = + DATA_SCHEMA + .add(CDCSchemaContext.CDC_TYPE_COLUMN, DataTypes.StringType, false) + .add(CDCSchemaContext.CDC_COMMIT_VERSION, DataTypes.LongType, false) + .add(CDCSchemaContext.CDC_COMMIT_TIMESTAMP, DataTypes.TimestampType, false); + + assertEquals(nonNullable, CDCSchemaContext.appendNonNullableCDCColumns(DATA_SCHEMA)); + } + private static List toJavaList(Seq seq) { List result = new ArrayList<>(seq.size()); for (int i = 0; i < seq.size(); i++) { From 6a413d1779958f0900b6f958947cddc64af15469 Mon Sep 17 00:00:00 2001 From: You Zhou <98635051+PorridgeSwim@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:14:33 -0800 Subject: [PATCH 06/44] [Spark] Preserve processing failures during iterator cleanup (#8175) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Use `Utils.tryWithSafeFinally` in Delta iterator helpers, streaming source cleanup, and eager log reads. When processing and closing both fail, preserve the processing exception and attach the close exception as suppressed. A close failure still propagates when processing succeeds. Apply the same handling when constructing a wrapped iterator fails, while keeping successfully constructed lazy iterators open until their owner closes them. ## How was this patch tested? Added regression coverage in `LineClosableIteratorSuiteBase` for processing failures with and without close failures, close-only failures, wrapped iterator construction failures, and successful lazy iterator ownership. `git diff --check`, `sparkV2/javafmt`, and `sparkV2/Test/javafmt` passed. Both Java formatter tasks completed without changing any files. The two iterator suites passed against Spark 4.0: 32 tests, zero failures. ```bash build/sbt -DsparkVersion=4.0 \ "spark/testOnly org.apache.spark.sql.delta.storage.InternalLineClosableIteratorSuite org.apache.spark.sql.delta.storage.PublicLineClosableIteratorSuite" ``` ## Does this PR introduce _any_ user-facing changes? Yes. If processing and cleanup both fail, callers now receive the original processing exception with the cleanup exception suppressed, instead of losing the original failure. Successful processing behavior is unchanged. --------- Signed-off-by: You Zhou --- .../spark/sql/delta/sources/DeltaSource.scala | 8 +- .../sql/delta/storage/ClosableIterator.scala | 21 +++-- .../spark/sql/delta/storage/LogStore.scala | 4 +- .../storage/LineClosableIteratorSuite.scala | 89 ++++++++++++++++++- 4 files changed, 110 insertions(+), 12 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala index 107c12f7896..07d9f6fbf6b 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala @@ -270,7 +270,7 @@ trait DeltaSourceBase extends Source isInitialSnapshot, endOffset = Some(endOffset) ) - try { + Utils.tryWithSafeFinally { // Versions before startVersion have already been processed, so we treat // startVersion - 1 as already "seen". var maxVersionSeen = startVersion - 1 @@ -311,7 +311,7 @@ trait DeltaSourceBase extends Source log"endOffset=${MDC(DeltaLogKeys.END_INDEX, endOffset)} took timeMs=" + log"${MDC(DeltaLogKeys.DURATION, duration)} ms") result - } finally { + } { fileActionsIter.close() } } @@ -1514,13 +1514,13 @@ object DeltaSource extends DeltaLogging { * Scan and get the last item of the iterator. */ def iteratorLast[T](iter: ClosableIterator[T]): Option[T] = { - try { + Utils.tryWithSafeFinally { var last: Option[T] = None while (iter.hasNext) { last = Some(iter.next()) } last - } finally { + } { iter.close() } } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/storage/ClosableIterator.scala b/spark/src/main/scala/org/apache/spark/sql/delta/storage/ClosableIterator.scala index c92840d544b..7dba56a5fb1 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/storage/ClosableIterator.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/storage/ClosableIterator.scala @@ -18,17 +18,25 @@ package org.apache.spark.sql.delta.storage import java.io.Closeable +import org.apache.spark.util.Utils + trait SupportsRewinding[T] extends Iterator[T] { // Overrides if class supports rewinding the iterator to the beginning efficiently. def rewind(): Unit } trait ClosableIterator[T] extends Iterator[T] with Closeable { - /** Calls f(this) and always closes the iterator afterwards. */ + /** + * Calls `f` with this iterator and always closes it afterwards. + * + * @return the result of `f` + * @throws Throwable if processing or closing fails. A processing failure takes precedence, + * with any close failure attached as a suppressed exception. + */ def processAndClose[R](f: Iterator[T] => R): R = { - try { + Utils.tryWithSafeFinally { f(this) - } finally { + } { close() } } @@ -46,8 +54,11 @@ object ClosableIterator { f(closableIter) } catch { case e: Throwable => - closableIter.close() - throw e + Utils.tryWithSafeFinally { + throw e + } { + closableIter.close() + } } override def next(): B = iter.next() override def hasNext: Boolean = iter.hasNext diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/storage/LogStore.scala b/spark/src/main/scala/org/apache/spark/sql/delta/storage/LogStore.scala index 3730b4f97a5..8927f0395e0 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/storage/LogStore.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/storage/LogStore.scala @@ -79,9 +79,9 @@ trait LogStore { */ final def read(fileStatus: FileStatus, hadoopConf: Configuration): Seq[String] = { val iter = readAsIterator(fileStatus, hadoopConf) - try { + Utils.tryWithSafeFinally { iter.toIndexedSeq - } finally { + } { iter.close() } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/storage/LineClosableIteratorSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/storage/LineClosableIteratorSuite.scala index 2e7b08309cc..a3233a8912e 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/storage/LineClosableIteratorSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/storage/LineClosableIteratorSuite.scala @@ -18,9 +18,13 @@ package org.apache.spark.sql.delta.storage import java.io.{Reader, StringReader} +import org.apache.spark.sql.delta.sources.DeltaSource +import org.apache.spark.sql.delta.storage.ClosableIterator._ + import org.apache.spark.SparkFunSuite +import org.apache.spark.sql.delta.test.shims.GridTestShim -abstract class LineClosableIteratorSuiteBase extends SparkFunSuite { +abstract class LineClosableIteratorSuiteBase extends SparkFunSuite with GridTestShim { protected def createIter(_reader: Reader): ClosableIterator[String] @@ -123,6 +127,89 @@ abstract class LineClosableIteratorSuiteBase extends SparkFunSuite { assert(closed == 1) } + for (operation <- Seq("processAndClose", "iteratorLast")) { + gridTest(s"$operation preserves processing failures")(Seq(false, true)) { failOnClose => + val processingFailure = new RuntimeException("processing failed") + val closeFailure = new RuntimeException("close failed") + var closeCount = 0 + val reader = new StringReader("foo") { + override def read(buffer: Array[Char], offset: Int, length: Int): Int = { + throw processingFailure + } + override def close(): Unit = { + super.close() + closeCount += 1 + if (failOnClose) throw closeFailure + } + } + val iter = createIter(reader) + val thrown = intercept[RuntimeException] { + if (operation == "processAndClose") { + iter.processAndClose(_.toList) + } else { + DeltaSource.iteratorLast(iter) + } + } + assert(thrown eq processingFailure) + assert(thrown.getSuppressed.toSeq == (if (failOnClose) Seq(closeFailure) else Seq.empty)) + assert(closeCount == 1) + } + } + + test("processAndClose propagates a close failure after successful processing") { + val closeFailure = new RuntimeException("close failed") + var processed = false + val iter = createIter(new StringReader("foo") { + override def close(): Unit = { + super.close() + throw closeFailure + } + }) + val thrown = intercept[RuntimeException] { + iter.processAndClose { actions => + assert(actions.next() == "foo") + processed = true + } + } + assert(processed) + assert(thrown eq closeFailure) + assert(thrown.getSuppressed.isEmpty) + } + + test("withClose preserves a construction failure when closing also fails") { + val processingFailure = new RuntimeException("construction failed") + val closeFailure = new RuntimeException("close failed") + val iter = createIter(new StringReader("foo") { + override def close(): Unit = { + super.close() + throw closeFailure + } + }) + val thrown = intercept[RuntimeException] { + iter.withClose[String](_ => throw processingFailure) + } + assert(thrown eq processingFailure) + assert(thrown.getSuppressed.toSeq == Seq(closeFailure)) + } + + test("withClose keeps a successfully constructed iterator open") { + var closeCount = 0 + val iter = createIter(new StringReader("foo") { + override def close(): Unit = { + super.close() + closeCount += 1 + } + }).withClose(_.map(_ + "!")) + try { + assert(closeCount == 0) + assert(iter.next() == "foo!") + assert(closeCount == 0) + } finally { + iter.close() + } + assert(closeCount == 1) + } + test("flatMapWithClose does not open any iterators on creation") { var opened = 0 var closed = 0 From 65938df79c412430fb6f178b312321b38d06198e Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Mon, 16 Nov 2026 19:26:45 -0500 Subject: [PATCH 07/44] [Spark][DEDUP] Use shared Delta V2 enable mode constants (#8110) [AI-assisted] ## What changes were proposed? Define the Delta V2 enable modes as named constants in `DeltaSQLConf` and reuse those constants in `DeltaV2Mode`. This removes duplicate string literals without changing defaults, validation, case handling, or connector-selection behavior. ## How was this patch tested? - `sparkV2/compile` - `spark/compile` - `DeltaV2CDFSuite` (27 tests) - `DeltaTableRefreshAutoModeSuite` and `DeltaTableRefreshStrictModeSuite` (72 tests) --------- Signed-off-by: tdas --- .../scala/org/apache/spark/sql/delta/DeltaV2Mode.scala | 7 ++++--- .../apache/spark/sql/delta/sources/DeltaSQLConf.scala | 9 +++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaV2Mode.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaV2Mode.scala index 4ce6b1419a4..f765ca892c5 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaV2Mode.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaV2Mode.scala @@ -42,9 +42,10 @@ import org.apache.spark.sql.internal.SQLConf * */ class DeltaV2Mode private (mode: String) { - private final val NONE = "NONE" - private final val STRICT = "STRICT" - private final val AUTO = "AUTO" + import DeltaSQLConf.{ + V2_ENABLE_MODE_AUTO => AUTO, + V2_ENABLE_MODE_NONE => NONE, + V2_ENABLE_MODE_STRICT => STRICT} /** Captures the mode from the supplied SQL configuration. */ def this(sqlConf: SQLConf) = this(sqlConf.getConf(DeltaSQLConf.V2_ENABLE_MODE)) 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 502b89d431a..debcf386b06 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 @@ -4123,6 +4123,11 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(false) + // Named modes used by [[V2_ENABLE_MODE]]. + val V2_ENABLE_MODE_NONE: String = "NONE" + val V2_ENABLE_MODE_AUTO: String = "AUTO" + val V2_ENABLE_MODE_STRICT: String = "STRICT" + /** * Controls which connector implementation to use for Delta table operations. * @@ -4149,8 +4154,8 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { "NONE (use v1 connector for all cases), AUTO (use v2 only for v2 " + "supported operations, default), STRICT (should ONLY be enabled for testing).") .stringConf - .checkValues(Set("AUTO", "NONE", "STRICT")) - .createWithDefault("AUTO") + .checkValues(Set(V2_ENABLE_MODE_AUTO, V2_ENABLE_MODE_NONE, V2_ENABLE_MODE_STRICT)) + .createWithDefault(V2_ENABLE_MODE_AUTO) val V2_TRANSACTIONS_ENABLED = buildConf("v2.transactions.enabled") From f6944f6bbc1dbd5cdd6a5ba1bbc94ce876c414fe Mon Sep 17 00:00:00 2001 From: Abhijit Chakankar <98838463+chakankardb@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:10:55 -0800 Subject: [PATCH 08/44] [Sharing] Prune unsupported sub-expressions from Delta Sharing json predicate hints (#8109) #### Which Delta project/connector is this regarding? - [ ] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [x] Other (Sharing) ## Description When a delta-format Delta Sharing query has one filter that can't be converted to a json predicate (e.g. `RLIKE`/`LIKE`, or a large `IN` list, which the optimizer turns into `InSet`), `OpConverter` throws. The whole partition-filter or data-filter hint is then dropped, so the sharing server can't skip any files and returns the full file list, even though the other filters could have been used for skipping. `DeltaSharingJsonPredicates.convert` now honors `spark.delta.sharing.jsonPredicateHints.partialFilter.enabled`. That conf, and partial conversion in `OpConverter`, shipped in delta-sharing-client 1.4.1 (delta-io/delta-sharing#983), and the parquet-format path (`RemoteDeltaFileIndex`) already uses them. When the conf is on, `OpConverter` emits `UnsupportedOp` placeholders, and `UnsupportedOpPruner` removes them before the hint is serialized: - An AND keeps its supported children. - An OR or NOT that contains an unsupported node is dropped whole. So the hint still matches a superset of the files with matching rows, and `UnsupportedOp` is never sent to the server. The conf applies to both the partition and the data side of the hint. It defaults to `false`, so behavior is unchanged unless it is enabled. ## How was this patch tested? New `DeltaSharingFileIndexSuite` test "jsonPredicate partial filter drops only unsupported sub-expressions". It pins the three hint confs and asserts the exact json hint sent to the server: - With the conf off, an unsupported `RLIKE` or a 21-value `IN` still drops the whole data-filter side, as before. - With the conf on: - an unsupported AND conjunct (`RLIKE`, `InSet`, or a 21-value `IN`) is dropped while the supported partition and data conjuncts are kept; - an OR containing an unsupported branch is dropped entirely; - a predicate with nothing supported sends no hint; - fully supported predicates produce the same hint as before. Each check also asserts that exactly one file-listing call was made, so a missing hint can't come from a cache hit. ## Does this PR introduce _any_ user-facing changes? No. The behavior only changes when `spark.delta.sharing.jsonPredicateHints.partialFilter.enabled` is set to `true` (default `false`). With it on, queries with unsupported filters can get server-side file skipping from their remaining filters. This pull request and its description were written by Isaac. --------- Signed-off-by: Abhijit Chakankar Co-authored-by: Isaac --- .../spark/DeltaSharingJsonPredicates.scala | 32 ++++-- .../spark/DeltaSharingFileIndexSuite.scala | 106 +++++++++++++++++- 2 files changed, 126 insertions(+), 12 deletions(-) diff --git a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingJsonPredicates.scala b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingJsonPredicates.scala index 5c0da363420..839c10c7e22 100644 --- a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingJsonPredicates.scala +++ b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingJsonPredicates.scala @@ -19,7 +19,7 @@ package io.delta.sharing.spark import java.util.Locale import io.delta.sharing.client.util.{ConfUtils, JsonUtils} -import io.delta.sharing.filters.{AndOp, BaseOp, OpConverter} +import io.delta.sharing.filters.{AndOp, BaseOp, OpConverter, UnsupportedOpPruner} import org.apache.spark.internal.Logging import org.apache.spark.sql.{sources => src} @@ -50,11 +50,13 @@ object DeltaSharingJsonPredicates extends Logging { * - data filters are converted only under `jsonPredicateV2Hints.enabled` (default off), so with * defaults only partition filters reach the server. * Partition and data predicates are AND-ed. A conversion error on either side drops just that - * side (logged, not thrown). + * side (logged, not thrown). Under `jsonPredicateHints.partialFilter.enabled` (default off), + * unsupported sub-expressions are instead pruned conservatively: an AND keeps its supported + * children, while an OR or NOT containing one is dropped whole. * * @param partitionFilters filters referencing only partition columns. * @param dataFilters filters referencing at least one non-partition column. - * @param conf session conf supplying the two feature gates. + * @param conf session conf supplying the feature gates. * @return the serialized json predicate, or None when disabled or nothing converted. */ def convert( @@ -64,10 +66,11 @@ object DeltaSharingJsonPredicates extends Logging { if (!ConfUtils.jsonPredicatesEnabled(conf)) { return None } + val partialFilterEnabled = ConfUtils.jsonPredicatePartialFilterEnabled(conf) // Convert the partition filters. val partitionOp = try { - OpConverter.convert(partitionFilters) + OpConverter.convert(partitionFilters, partialFilterEnabled) } catch { case e: Exception => logError("Error while converting partition filters: " + e) @@ -78,7 +81,7 @@ object DeltaSharingJsonPredicates extends Logging { val dataOp = try { if (ConfUtils.jsonPredicatesV2Enabled(conf)) { logInfo("Converting data filters") - OpConverter.convert(dataFilters) + OpConverter.convert(dataFilters, partialFilterEnabled) } else { None } @@ -96,13 +99,22 @@ object DeltaSharingJsonPredicates extends Logging { } else { dataOp } - logInfo("Using combined predicate: " + combinedOp) - if (combinedOp.isDefined) { - Some(JsonUtils.toJson[BaseOp](combinedOp.get)) + // UnsupportedOp is a client-local placeholder and must never reach the server. + val finalOp = if (partialFilterEnabled) { + combinedOp.flatMap { op => + val (pruned, hadUnsupported) = UnsupportedOpPruner.prune(op) + if (hadUnsupported) { + logInfo(s"Pruned unsupported sub-expressions from predicate: $op -> $pruned") + } + pruned + } } else { - None + combinedOp } + logInfo("Using combined predicate: " + finalOp) + + finalOp.map(JsonUtils.toJson[BaseOp](_)) } /** @@ -120,7 +132,7 @@ object DeltaSharingJsonPredicates extends Logging { * @param filters the pushed filters, ANDed together per the DSv2 contract. * @param schema the full table schema, for column type / nullability lookup. * @param partitionColumns the table's partition column names (case-insensitive). - * @param conf session conf supplying the two feature gates. + * @param conf session conf supplying the feature gates. */ def fromPushedFilters( filters: Array[src.Filter], diff --git a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingFileIndexSuite.scala b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingFileIndexSuite.scala index b15a2868848..143fc0e6468 100644 --- a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingFileIndexSuite.scala +++ b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingFileIndexSuite.scala @@ -36,10 +36,15 @@ import org.apache.spark.sql.{QueryTest, SparkSession} import org.apache.spark.sql.catalyst.expressions.{ AttributeReference => SqlAttributeReference, EqualTo => SqlEqualTo, - Literal => SqlLiteral + Expression, + In => SqlIn, + InSet => SqlInSet, + Literal => SqlLiteral, + Or => SqlOr, + RLike => SqlRLike } import org.apache.spark.sql.delta.sharing.DeltaSharingTestSparkUtils -import org.apache.spark.sql.types.{FloatType, IntegerType} +import org.apache.spark.sql.types.{FloatType, IntegerType, StringType} private object TestUtils { val paths = Seq("http://path1", "http://path2") @@ -480,4 +485,101 @@ class DeltaSharingFileIndexSuite } } } + + test("jsonPredicate partial filter drops only unsupported sub-expressions") { + withTempDir { tempDir => + val profileFile = new File(tempDir, "foo.share") + FileUtils.writeStringToFile( + profileFile, + s"""{ + | "shareCredentialsVersion": 1, + | "endpoint": "https://localhost:12345/not-used-endpoint", + | "bearerToken": "mock" + |}""".stripMargin, + "utf-8" + ) + val partialFilterConf = "spark.delta.sharing.jsonPredicateHints.partialFilter.enabled" + withSQLConf( + "spark.delta.sharing.client.class" -> classOf[TestDeltaSharingClientForFileIndex].getName, + "fs.delta-sharing-log.impl" -> classOf[DeltaSharingLogFileSystem].getName, + "spark.delta.sharing.profile.provider.class" -> + "io.delta.sharing.client.DeltaSharingFileProfileProvider", + SparkConfForReturnExpTime -> "true", + SparkConfForUrlExpirationMs -> "3600000", // 1h + "spark.delta.sharing.jsonPredicateHints.enabled" -> "true", + "spark.delta.sharing.jsonPredicateV2Hints.enabled" -> "true", + partialFilterConf -> "false" + ) { + val (_, fileIndex, client) = + prepareDeltaSharingFileIndex(profileFile.getCanonicalPath, metaDataStr) + val testClient = client.asInstanceOf[TestDeltaSharingClientForFileIndex] + val conf = SparkSession.active.sessionState.conf + + val partitionSqlEq = SqlEqualTo( + SqlAttributeReference("id", IntegerType)(), + SqlLiteral(23, IntegerType)) + val dataSqlEq = SqlEqualTo( + SqlAttributeReference("cost", FloatType)(), + SqlLiteral(23.5.toFloat, FloatType)) + // OpConverter has no mapping for RLIKE or InSet (what the optimizer turns large IN lists + // into), nor for IN lists over kMaxSqlInOpSizeLimit (20). + val dataSqlRLike = SqlRLike( + SqlAttributeReference("name", StringType)(), + SqlLiteral("^a.*")) + val dataSqlLargeIn = SqlIn( + SqlAttributeReference("cost", FloatType)(), + (1 to 21).map(i => SqlLiteral(i.toFloat, FloatType))) + val dataSqlInSet = SqlInSet( + SqlAttributeReference("cost", FloatType)(), + (1 to 11).map(_.toFloat).toSet[Any]) + + val partitionJson = + """{"op":"equal","children":[ + | {"op":"column","name":"id","valueType":"int"}, + | {"op":"literal","value":"23","valueType":"int"}]} + |""".stripMargin.replaceAll("\n", "").replaceAll(" ", "") + val dataEqJson = + """{"op":"equal","children":[ + | {"op":"column","name":"cost","valueType":"float"}, + | {"op":"literal","value":"23.5","valueType":"float"}]} + |""".stripMargin.replaceAll("\n", "").replaceAll(" ", "") + val partitionAndDataEqJson = s"""{"op":"and","children":[$partitionJson,$dataEqJson]}""" + + def hintFor(partitionFilters: Seq[Expression], dataFilters: Seq[Expression]) + : Option[String] = { + testClient.clear() + val callsBefore = testClient.numGetFileCalls + fileIndex.listFiles(partitionFilters, dataFilters) + assert(testClient.numGetFileCalls === callsBefore + 1) + assert(testClient.savedJsonPredicateHints.size <= 1) + testClient.savedJsonPredicateHints.headOption + } + + // Flag off: one unsupported conjunct drops the whole data side. + conf.setConfString(partialFilterConf, "false") + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq, dataSqlRLike)) === + Some(partitionJson)) + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq, dataSqlLargeIn)) === + Some(partitionJson)) + + conf.setConfString(partialFilterConf, "true") + // AND: the unsupported conjunct is dropped and its supported siblings are kept. + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq, dataSqlRLike)) === + Some(partitionAndDataEqJson)) + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq, dataSqlLargeIn)) === + Some(partitionAndDataEqJson)) + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq, dataSqlInSet)) === + Some(partitionAndDataEqJson)) + assert(hintFor(Seq.empty, Seq(dataSqlRLike, dataSqlEq)) === Some(dataEqJson)) + // OR: dropping only the unsupported branch would narrow the predicate and skip files + // that match it, so the whole OR is dropped. + assert(hintFor(Seq(partitionSqlEq), Seq(SqlOr(dataSqlEq, dataSqlRLike))) === + Some(partitionJson)) + // Nothing supported left: no hint at all. + assert(hintFor(Seq.empty, Seq(dataSqlRLike)) === None) + // Fully supported predicates are unchanged by the flag. + assert(hintFor(Seq(partitionSqlEq), Seq(dataSqlEq)) === Some(partitionAndDataEqJson)) + } + } + } } From e7261c28d6b78a2d836db2df92c16b590d17b4ce Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Mon, 16 Nov 2026 17:37:16 -0800 Subject: [PATCH 09/44] [Spark] Reconstruct AMT file actions in SingleCommit.getActionsIterator (#8173) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description `SingleCommit.getActionsIterator` returned the actions of a commit's log file as written. For an inline manifest commit of a table with an adaptive metadata tree, the `AddFile` and `RemoveFile` actions are recorded in the tree, so the iterator did not return them. Callers that process a commit's actions one at a time, without loading them all into memory, need the actions that `getActions` returns. - With `DeltaSQLConf.AMT_SINGLE_COMMIT_READ_ENABLED` on, `getActionsIterator` returns the same actions as `getActions`, in the same order: the log file's other actions, then the file actions reconstructed from the tree. With the conf off, it returns the log file as written. - The new `AMTCheckpointProviderImpl.reconstructFileActionsIterator` returns the actions of `reconstructFileActions`, in its order, and pulls them to the driver one partition at a time. The iterator opens the tree only after it has read the log file's actions. `rewind()` reads both again. - `getActions` and `getActionsIterator` share one path. A commit is an inline manifest commit when its first action is a `CommitInfo` whose `lastManifestCommit` is at the commit's own version (`CommitInfo.isAMTInlineManifestCommit`). Its tree is located from its `Checkpoint` action, and the read fails if that action is missing. - The test helper `getJsonOnlyChanges` now reads the log files directly. ## How was this patch tested? New tests in `AMTSingleCommitSuite`: - `getActionsIterator` returns the same actions after `rewind()`. - `getActions` and `getActionsIterator` return a manifest commit's actions in the same order. - `reconstructFileActionsIterator` returns the actions of `reconstructFileActions` in order, with 7 shuffle partitions. - `getActionsIterator` returns a log commit as written, and returns the log file as written when single-commit read is off. The existing `getChanges` test for an inline manifest commit also checks `getActionsIterator`. ## Does this PR introduce _any_ user-facing changes? No. --- .../apache/spark/sql/delta/SingleCommit.scala | 217 ++++++++++++------ .../spark/sql/delta/actions/actions.scala | 29 +++ .../sql/delta/amt/AMTCheckpointProvider.scala | 14 ++ .../sql/delta/amt/AMTCheckpointTestBase.scala | 4 +- .../sql/delta/amt/AMTSingleCommitSuite.scala | 113 +++++++++ 5 files changed, 303 insertions(+), 74 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/SingleCommit.scala b/spark/src/main/scala/org/apache/spark/sql/delta/SingleCommit.scala index 5d5395a1978..51e1fca9747 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/SingleCommit.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/SingleCommit.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.delta import org.apache.spark.sql.delta.actions.{Action, AddFile, Checkpoint, CommitInfo, FileAction, RemoveFile} import org.apache.spark.sql.delta.amt.AMTCheckpointProvider +import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.storage.{ClosableIterator, SupportsRewinding} import org.apache.spark.sql.delta.storage.ClosableIterator._ import org.apache.spark.sql.delta.util.FileNames @@ -43,16 +44,45 @@ class SingleCommit private ( } /** - * Open a fresh iterator over all of this commit's actions. + * Open a fresh iterator over all of this commit's logical actions. For an inline AMT commit, + * inline AddFile and RemoveFile actions are replaced by actions reconstructed from the tree. + * Every other inline action is preserved. The AMT does not record a metadata-only re-add of + * an already-live file (e.g. a stats backfill), so such AddFiles are omitted. * * @param maxInMemoryFileSizeBytes commits whose log file is smaller than this are read into - * memory once and replayed on every `rewind()`; larger commits are re-read on each pass. - * Defaults to 0, i.e. always stream via `readAsIterator` -- callers that want the - * in-memory/rewind fast path opt in by passing a threshold. + * memory once and replayed on every `rewind()`. */ override def getActionsIterator( - maxInMemoryFileSizeBytes: Long = 0): ClosableIterator[Action] with SupportsRewinding[Action] = - SingleCommit.createRewindableActionIterator(deltaLog, fileStatus, maxInMemoryFileSizeBytes) + maxInMemoryFileSizeBytes: Long = 0) + : ClosableIterator[Action] with SupportsRewinding[Action] = { + if (SparkSession.active.sessionState.conf.getConf( + DeltaSQLConf.AMT_SINGLE_COMMIT_READ_ENABLED)) { + getAMTAwareActionsIterator(maxInMemoryFileSizeBytes) + } else { + getJsonActionsIterator(maxInMemoryFileSizeBytes) + } + } + + /** + * Get this commit's logical actions, the same actions in the same order as + * [[getActionsIterator]] with single-commit read on. + * + * @param skipNoDataChangeFileActions whether to omit the AddFile and RemoveFile actions with + * `dataChange = false`. + */ + def getActions(skipNoDataChangeFileActions: Boolean = false): Seq[Action] = { + val commitJsonActions = + getJsonActionsIterator(maxInMemoryFileSizeBytes = 0).processAndClose(_.toList) + def computeTreeFileActions( + commitInfo: CommitInfo, checkpointOpt: Option[Checkpoint]): Iterator[Action] = { + amtProviderFromCheckpointOpt(checkpointOpt) + .reconstructFileActions( + deltaLog, commitInfo.getDataChangeOrThrow, commitInfo.getCommitTimestamp) + .iterator + } + toLogicalActions( + commitJsonActions.iterator, skipNoDataChangeFileActions, computeTreeFileActions).toList + } /** * Like [[getActionsIterator]], but asserts this commit is a log commit. @@ -62,8 +92,7 @@ class SingleCommit private ( private[delta] def getLogCommitActionsIteratorUnsafe( maxInMemoryFileSizeBytes: Long = 0) : ClosableIterator[Action] with SupportsRewinding[Action] = { - val underlying = - SingleCommit.createRewindableActionIterator(deltaLog, fileStatus, maxInMemoryFileSizeBytes) + val underlying = getJsonActionsIterator(maxInMemoryFileSizeBytes) new ClosableIterator[Action] with SupportsRewinding[Action] { override def hasNext: Boolean = underlying.hasNext override def next(): Action = underlying.next() match { @@ -78,80 +107,127 @@ class SingleCommit private ( } /** - * Get this commit's logical actions. For a manifest commit, actions are reconstructed from tree. - * AMT does not record a metadata-only re-add of an already-live file (e.g. a stats backfill), - * so such AddFiles in an inline AMT commit are omitted. + * The modification time of this commit's log file. + */ + private[delta] def fileModificationTimestamp: Long = fileStatus.getModificationTime + + /** + * The size of this commit's log file, in bytes. + */ + private[delta] def commitFileSizeInBytes: Long = fileStatus.getLen + + ////////////////////// + // Helper functions // + ////////////////////// + + /** + * The actions in this commit's log file, as written. * - * @param skipNoDataChangeFileActions whether to omit the AddFile and RemoveFile actions with - * `dataChange = false`. See [[DeltaLog.getChanges]]. + * @param maxInMemoryFileSizeBytes see [[getActionsIterator]]. */ - def getActions(skipNoDataChangeFileActions: Boolean = false): Seq[Action] = { - val actions = getActionsIterator().processAndClose(_.toList) - val commitInfoOpt = actions.collectFirst { case commitInfo: CommitInfo => commitInfo } - // Use AMT reconstruction only when inline AMT checkpoint exists. - val amtCheckpointOpt = actions.collectFirst { - case checkpoint: Checkpoint if checkpoint.contentRoot.version == version => checkpoint - } - amtCheckpointOpt match { - // Always take tree actions when present. - case Some(amtCheckpoint) => - val commitInfo = commitInfoOpt.getOrElse { - throw new IllegalStateException( - s"Commit $version is an inline manifest commit but does not have a CommitInfo.") - } - actions.filter { - case _: AddFile | _: RemoveFile => false - case _ => true - } ++ reconstructAMTFileActions(amtCheckpoint, commitInfo, skipNoDataChangeFileActions) - // Trim no data change actions when skipNoDataChangeFileActions is set. - // AMT tree may be present in this commit, but it is never read. - case None if skipNoDataChangeFileActions => - actions.filter { - case add: AddFile => add.dataChange - case remove: RemoveFile => remove.dataChange - case _ => true - } - // No AMT tree is present. Return all actions. - case None => actions - } - } + private def getJsonActionsIterator( + maxInMemoryFileSizeBytes: Long): ClosableIterator[Action] with SupportsRewinding[Action] = + SingleCommit.createRewindableActionIterator(deltaLog, fileStatus, maxInMemoryFileSizeBytes) /** - * Reconstructs the AddFile and RemoveFile actions of this commit from the AMT that its inline - * `amtCheckpoint` describes, as of this version. + * The actions in this commit's log file, with an inline AMT commit's AddFile and RemoveFile + * actions read from its tree instead (see [[toLogicalActions]]). * - * @param commitInfo the commit's [[CommitInfo]], which records its `dataChange` and timestamp. + * @param maxInMemoryFileSizeBytes see [[getActionsIterator]]. */ - private def reconstructAMTFileActions( - amtCheckpoint: Checkpoint, - commitInfo: CommitInfo, - skipNoDataChangeFileActions: Boolean): Seq[FileAction] = { - val dataChange = commitInfo.dataChange.getOrElse { - throw new IllegalStateException( - s"Commit $version is an inline manifest commit but does not have a dataChange flag.") - } - if (skipNoDataChangeFileActions && !dataChange) { - // A commit that changed no data has no data-changing file actions, so skip its tree. - Seq.empty - } else { - val commitTimestamp = commitInfo.inCommitTimestamp.getOrElse { - throw new IllegalStateException( - s"Commit $version is an inline manifest commit but has no in-commit timestamp.") + private def getAMTAwareActionsIterator( + maxInMemoryFileSizeBytes: Long): ClosableIterator[Action] with SupportsRewinding[Action] = { + val commitJsonIter = getJsonActionsIterator(maxInMemoryFileSizeBytes) + new ClosableIterator[Action] with SupportsRewinding[Action] { + private def computeTreeFileActions( + commitInfo: CommitInfo, checkpointOpt: Option[Checkpoint]): Iterator[Action] = + amtProviderFromCheckpointOpt(checkpointOpt).reconstructFileActionsIterator( + deltaLog, commitInfo.getDataChangeOrThrow, commitInfo.getCommitTimestamp) + private var underlying = + try { + toLogicalActions( + commitJsonIter, skipNoDataChangeFileActions = false, computeTreeFileActions) + } catch { + case e: Throwable => + commitJsonIter.close() + throw e + } + override def hasNext: Boolean = underlying.hasNext + override def next(): Action = underlying.next() + override def close(): Unit = commitJsonIter.close() + override def rewind(): Unit = { + commitJsonIter.rewind() + underlying = toLogicalActions( + commitJsonIter, skipNoDataChangeFileActions = false, computeTreeFileActions) } - AMTCheckpointProvider.fromCheckpoint(SparkSession.active, deltaLog, amtCheckpoint, version) - .reconstructFileActions(deltaLog, dataChange, commitTimestamp) } } /** - * The modification time of this commit's log file. + * Wrap the Json commit iterator with AMT specific handling. This includes: + * 1. Skip all Add and Removes if skipNoDataChangeFileActions is set and dataChange is false. + * 2. Returns iterator immediately for non inline manifest commits. + * 3. Reconstruct file actions from the tree if the commit is an inline manifest commit. + * Reconstruction happens after log commit is exhausted. + * + * @param commitJsonIter the actions in this commit's log file, as written. + * @param skipNoDataChangeFileActions whether to omit the AddFile and RemoveFile actions with + * `dataChange = false`. + * @param computeTreeFileActions reads the tree's file actions, given the commit's CommitInfo + * and Checkpoint action. */ - private[delta] def fileModificationTimestamp: Long = fileStatus.getModificationTime + private def toLogicalActions( + commitJsonIter: Iterator[Action], + skipNoDataChangeFileActions: Boolean, + computeTreeFileActions: (CommitInfo, Option[Checkpoint]) => Iterator[Action]) + : Iterator[Action] = { + val bufferedIter = commitJsonIter.buffered + val amtCommitInfoOpt = bufferedIter.headOption.collect { + case commitInfo: CommitInfo if commitInfo.isAMTInlineManifestCommit(version) => commitInfo + } + amtCommitInfoOpt match { + case None => + // No AMT tree is present. Log commit actions are filtered if skipNoDataChangeFileActions. + if (skipNoDataChangeFileActions) { + bufferedIter.filter { + case add: AddFile => add.dataChange + case remove: RemoveFile => remove.dataChange + case _ => true + } + } else { + bufferedIter + } + case Some(commitInfo) => + // Always take tree actions when present. + var checkpointOpt: Option[Checkpoint] = None + val logFileActionsIter = bufferedIter.filter(!FileAction.isAddOrRemove(_)).map { + case checkpoint: Checkpoint if checkpointOpt.isEmpty => + checkpointOpt = Some(checkpoint) + checkpoint + case action => action + } + // `++` takes the tree's actions by name and opens them only once the log file's actions + // run out, so the Checkpoint has been read by then. + logFileActionsIter ++ { + if (skipNoDataChangeFileActions && !commitInfo.getDataChangeOrThrow) { + // A commit that changed no data has no data-changing file actions, so skip its tree. + Iterator.empty + } else { + computeTreeFileActions(commitInfo, checkpointOpt) + } + } + } + } - /** - * The size of this commit's log file, in bytes. - */ - private[delta] def commitFileSizeInBytes: Long = fileStatus.getLen + /** The tree of this manifest commit, which its Checkpoint action locates. */ + private def amtProviderFromCheckpointOpt( + checkpointOpt: Option[Checkpoint]): AMTCheckpointProvider = { + val checkpoint = checkpointOpt.filter(_.contentRoot.version == version).getOrElse( + throw new IllegalStateException( + s"Commit $version's CommitInfo makes it a manifest commit at its own version, but it " + + s"has no Checkpoint action whose content root is at that version.")) + AMTCheckpointProvider.fromCheckpoint(SparkSession.active, deltaLog, checkpoint, version) + } } object SingleCommit { @@ -170,9 +246,6 @@ object SingleCommit { * constraints. If the commit's log file is smaller than `maxInMemoryFileSizeBytes`, its actions * are read into memory once and replayed on every `rewind()`; otherwise the file is re-read on * each pass. - * - * TODO(AMT): This needs AMT support for manifest commits, whose file actions live in the content - * tree rather than the commit JSON. */ private def createRewindableActionIterator( deltaLog: DeltaLog, diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala b/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala index 89eecef974c..cf72b593f92 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala @@ -1008,6 +1008,15 @@ object FileAction { action.pathAsUri, Option(action.deletionVector).map(_.uniqueId(tableRoot, useObjectIdentity))) } + + /** + * Whether `action` is an [[AddFile]] or a [[RemoveFile]], the file actions an AMT manifest + * commit reads from its tree rather than from its log file. + */ + private[delta] def isAddOrRemove(action: Action): Boolean = action match { + case _: AddFile | _: RemoveFile => true + case _ => false + } } case class ParsedStatsFields( @@ -1769,6 +1778,26 @@ case class CommitInfo( @JsonIgnore override def getVersion: Long = version.get + /** + * Whether this is the CommitInfo of an AMT manifest commit whose tree describes the commit's own + * version. + * + * @param commitVersion the version of the commit this CommitInfo belongs to. + */ + @JsonIgnore + def isAMTInlineManifestCommit(commitVersion: Long): Boolean = + lastManifestCommit.contains( + LastManifestCommit(version = commitVersion, contentRootVersion = commitVersion)) + + /** + * The commit-level `dataChange`, which must be present for AMT tables. + */ + @JsonIgnore + def getDataChangeOrThrow: Boolean = + dataChange.getOrElse(throw new IllegalStateException( + s"Commit ${version.map(_.toString).getOrElse("unknown")} does not have a dataChange flag " + + "in its CommitInfo.")) + } case class JobInfo( diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala index 1f37e2105bc..ff98e5e2748 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.delta.amt import java.util.concurrent.TimeUnit +import scala.collection.JavaConverters._ import scala.collection.mutable import scala.concurrent.duration.Duration @@ -891,6 +892,19 @@ trait AMTCheckpointProviderImpl extends CheckpointProvider { .collect().toSeq .map(_.unwrap.asInstanceOf[FileAction]) + /** + * Like [[reconstructFileActions]], in its order, but pulls the actions to the driver one + * partition of the sort at a time, so a large commit need not fit in driver memory. + */ + private[delta] def reconstructFileActionsIterator( + deltaLog: DeltaLog, + dataChange: Boolean, + commitTimestamp: Long): Iterator[FileAction] = + toChangeActions( + reconstructChangeFiles(deltaLog), dataChange, commitTimestamp, ordered = true) + .toLocalIterator().asScala + .map(_.unwrap.asInstanceOf[FileAction]) + /** * The changed files of the commit this tree describes. */ diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCheckpointTestBase.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCheckpointTestBase.scala index a50e2a0ac4a..ed23255f3c7 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCheckpointTestBase.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTCheckpointTestBase.scala @@ -741,8 +741,8 @@ trait AMTCheckpointTestBase protected def getJsonOnlyChanges( deltaLog: DeltaLog, startVersion: Long): Iterator[(Long, Seq[Action])] = - deltaLog.getSingleCommitIterator(startVersion).map { commit => - (commit.version, commit.getActionsIterator().processAndClose(_.toList)) + deltaLog.getChangeLogFiles(startVersion).map { case (version, logFile) => + (version, deltaLog.store.read(logFile, deltaLog.newDeltaHadoopConf()).map(Action.fromJson)) } /** Returns the actions committed at exactly `version`, as written in its log file. */ diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSingleCommitSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSingleCommitSuite.scala index 8a5ba53a50d..ae9e0d4c875 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSingleCommitSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSingleCommitSuite.scala @@ -580,6 +580,9 @@ class AMTSingleCommitSuite extends AMTIncrementalWriteTestBase with GridTestShim val retainedInlineActions = stripInlineAddAndRemoveActions(amtDeltaLog, version) val actions = amtDeltaLog.getChanges(version).next()._2 + val iteratorActions = commitAt(amtDeltaLog, version) + .getActionsIterator() + .processAndClose(_.toSeq) assert(actions.collect { case action: AddFile => action.path } === Seq(add.path)) assert(actions.collect { case action: RemoveFile => action.path } === Seq(remove.path)) @@ -598,6 +601,7 @@ class AMTSingleCommitSuite extends AMTIncrementalWriteTestBase with GridTestShim } === retainedInlineActions) // Re-reading the commit reconstructs exactly the same actions. assert(amtDeltaLog.getChanges(version).next()._2 === actions) + assert(iteratorActions === actions) // The commit changed data, so skipping file actions that change no data keeps them all, // including the AddCDCFile, whose dataChange is always false. assert(amtDeltaLog.getChanges( @@ -610,6 +614,115 @@ class AMTSingleCommitSuite extends AMTIncrementalWriteTestBase with GridTestShim } } + test("getActionsIterator reconstructs a manifest commit deterministically after rewind") { + withSQLConf(DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "10") { + withAmtTable { amtDeltaLog => + setupAmt(amtDeltaLog, entriesPerLeaf = 10, initialIdRangeInLeaf = 1 to 30) + val leaves = leafToAddFileMap(amtDeltaLog).values.toSeq + assert(leaves.size >= 2, "scenario needs at least two leaves.") + val version = amtDeltaLog.update().version + 1 + val add = fakeAdd(100) + val removes = Seq(leaves(0).head.remove, leaves(1).head.remove) + val changes: Seq[Action] = removes :+ add + withInline { commitAmt(amtDeltaLog, changes) } + stripInlineAddAndRemoveActions(amtDeltaLog, version) + + // Zero disables the raw commit's in-memory replay path, so rewind must reopen both the + // commit JSON and its deterministic AMT action stream. + val actions = commitAt(amtDeltaLog, version) + .getActionsIterator(maxInMemoryFileSizeBytes = 0) + try { + val firstPass = actions.processAndClose(_.toSeq) + actions.rewind() + val secondPass = actions.processAndClose(_.toSeq) + + assert(secondPass === firstPass) + assert(firstPass.collect { case action: AddFile => action.path } === Seq(add.path)) + assert(firstPass.collect { case action: RemoveFile => action.path }.toSet === + removes.map(_.path).toSet) + assert(firstPass.exists(_.isInstanceOf[Checkpoint])) + } finally { + actions.close() + } + } + } + } + + test("getActions and getActionsIterator list a manifest commit's file actions in one order") { + withSQLConf(DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "10") { + withAmtTable { amtDeltaLog => + val (version, changes) = commitAcrossRootAndLeaves(amtDeltaLog) + + // getActions collects the commit in one job; getActionsIterator streams it. + val commit = commitAt(amtDeltaLog, version) + val collected = commit.getActions() + val streamed = commit.getActionsIterator().processAndClose(_.toList) + assert(streamed === collected) + assert(collected.count(_.isInstanceOf[FileAction]) === changes.size) + } + } + } + + test("reconstructFileActionsIterator streams the actions of reconstructFileActions in order") { + withSQLConf(DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "10") { + withAmtTable { amtDeltaLog => + val (version, _) = commitAcrossRootAndLeaves(amtDeltaLog) + val provider = providerAt(amtDeltaLog, version) + val collected = + provider.reconstructFileActions(amtDeltaLog, dataChange = true, commitTimestamp = 0L) + // The iterator pulls the sorted actions one partition at a time, so spread them out. + withSQLConf( + SQLConf.SHUFFLE_PARTITIONS.key -> "7", + SQLConf.ADAPTIVE_EXECUTION_ENABLED.key -> "false") { + assert(provider.reconstructFileActionsIterator( + amtDeltaLog, dataChange = true, commitTimestamp = 0L).toList === collected) + } + } + } + } + + test("getActionsIterator reads a log commit as written") { + withTable("amt_log_commit_iterator") { + val deltaLog = createLogCommitTable("amt_log_commit_iterator", numVersions = 3) + assert(checkpointAt(deltaLog, 2L).isEmpty, "v2 must be a log commit for this test") + assert(commitAt(deltaLog, 2L).getActionsIterator().processAndClose(_.toList) === + actionsAt(deltaLog, 2L)) + } + } + + test("getActionsIterator reads the log file as written with single-commit read off") { + withSQLConf(DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "10") { + withAmtTable { amtDeltaLog => + setupAmt(amtDeltaLog, entriesPerLeaf = 10, initialIdRangeInLeaf = 1 to 30) + val version = amtDeltaLog.update().version + 1 + withInline { commitAmt(amtDeltaLog, Seq(removeOf(amtDeltaLog, 1), fakeAdd(100))) } + // Without its inline file actions, only the tree records the commit's file actions. + val retainedInlineActions = stripInlineAddAndRemoveActions(amtDeltaLog, version) + val commit = commitAt(amtDeltaLog, version) + + withSQLConf(DeltaSQLConf.AMT_SINGLE_COMMIT_READ_ENABLED.key -> "false") { + val actions = commit.getActionsIterator() + try { + assert(actions.toList === retainedInlineActions) + actions.rewind() + assert(actions.toList === retainedInlineActions) + } finally { + actions.close() + } + assert(DeltaFileProviderUtils.parallelReadAndParseDeltaFilesAsSeq(spark, Seq(commit)) === + Seq(retainedInlineActions)) + } + withSQLConf(DeltaSQLConf.AMT_SINGLE_COMMIT_READ_ENABLED.key -> "true") { + val actions = commit.getActionsIterator().processAndClose(_.toList) + assert(actions.exists(_.isInstanceOf[AddFile])) + assert(actions.exists(_.isInstanceOf[RemoveFile])) + assert(DeltaFileProviderUtils.parallelReadAndParseDeltaFilesAsSeq(spark, Seq(commit)) === + Seq(commit.getActions())) + } + } + } + } + /** * Commits leaf deletes, a leaf DV update (an add and a remove of one path), a root delete and * inserts out of path order, so the commit's changes span the root and several leaves. Returns From 54e2ff0eb26bff25bb48e20697eff27c639c5f56 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Mon, 16 Nov 2026 21:08:36 -0500 Subject: [PATCH 10/44] [Infra] Cancel in-progress Delta Spark CI runs on new commits (#8184) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [AI-assisted] ## Description Adds a concurrency group to the Delta Spark workflow with `cancel-in-progress: true`. PR runs are grouped by PR number, so a new commit cancels the previous in-progress run for the same PR. Non-PR runs—pushes to `master` or `branch-*`, and `workflow_dispatch` runs—fall back to `github.run_id`, giving every run a unique concurrency group. They are therefore never cancelled, preserving a full CI result for every master commit and maintaining master regression detection. ## Testing - Parsed `.github/workflows/spark_test.yaml` successfully with PyYAML. - `git diff --check` passed. - Confirmed the final diff against `delta/master` contains only the concurrency comment and block. --------- Co-authored-by: omnigent --- .github/workflows/spark_test.yaml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/spark_test.yaml b/.github/workflows/spark_test.yaml index 7577c22030b..798314f0231 100644 --- a/.github/workflows/spark_test.yaml +++ b/.github/workflows/spark_test.yaml @@ -16,6 +16,14 @@ on: description: Optional suffix to force a distinct Spark Maven cache key required: false type: string + +# Cancel superseded runs on the same PR when new commits are pushed. Non-PR runs (pushes to +# master / branch-*, manual dispatches) fall back to the unique run_id, so they are never +# cancelled and every commit to master gets its own full CI result. +concurrency: + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: true + # Source-build jobs are commented out while all supported Spark versions use releases. # With no snapshot versions, enabled source-build jobs appear as skipped. # The merge bot can report these checks as failures and confuse contributors. From f7443c18bcfce57f1cde8390b877b484e6bfbd43 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Mon, 16 Nov 2026 21:13:46 -0500 Subject: [PATCH 11/44] [Spark][DEDUP] Merge getPartitionRow map overload implementations (#8180) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Merge the Java and Scala map overload implementations of `getPartitionRow` through a shared helper. The overload-specific behavior remains unchanged, including the Java map size assertion, the Scala map missing-key handling, and lazy map access for empty partition schemas. ## How was this patch tested? - `build/sbt "sparkV2/Test/javafmtCheck"` - `build/sbt "sparkV2/testOnly org.apache.spark.sql.delta.v2.utils.PartitionUtilsTest"` (23 test cases) ## Does this PR introduce _any_ user-facing changes? No. --------- Signed-off-by: tdas --- .../spark/sql/delta/v2/utils/PartitionUtils.java | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/PartitionUtils.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/PartitionUtils.java index 1ed3acbbb20..f8d7d7d05c6 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/PartitionUtils.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/PartitionUtils.java @@ -38,6 +38,7 @@ import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; +import java.util.function.Function; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.spark.paths.SparkPath; @@ -233,9 +234,15 @@ public static InternalRow getPartitionRow( partitionValues.size(), numPartCols); + return getPartitionRow(key -> partitionValues.get(key), caster); + } + + private static InternalRow getPartitionRow( + Function partitionValue, PartitionValueCaster caster) { + final int numPartCols = caster.numFields(); final Object[] values = new Object[numPartCols]; for (int index = 0; index < numPartCols; index++) { - values[index] = caster.cast(index, partitionValues.get(caster.physicalName(index))); + values[index] = caster.cast(index, partitionValue.apply(caster.physicalName(index))); } return new GenericInternalRow(values); } @@ -456,13 +463,8 @@ private static scala.collection.immutable.Map emptyScalaMap() { */ public static InternalRow getPartitionRow( scala.collection.immutable.Map partitionValues, PartitionValueCaster caster) { - final int numPartCols = caster.numFields(); - final Object[] values = new Object[numPartCols]; final Map javaPartitionValues = CollectionConverters.asJava(partitionValues); - for (int i = 0; i < numPartCols; i++) { - values[i] = caster.cast(i, javaPartitionValues.get(caster.physicalName(i))); - } - return new GenericInternalRow(values); + return getPartitionRow(key -> javaPartitionValues.get(key), caster); } /** From 64770662b2d0036af189e7f726afe6e4fff8899e Mon Sep 17 00:00:00 2001 From: You Zhou <98635051+PorridgeSwim@users.noreply.github.com> Date: Mon, 16 Nov 2026 19:54:53 -0800 Subject: [PATCH 12/44] [Spark] Re-enable the V2 streaming failOnDataLoss gap test (#8181) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Re-enable `incremental: commit file gap between versions, failOnDataLoss=false succeeds` in `DeltaV2SourceSuite` by moving it from `FailingTests` to `PassingTests`. Remove the obsolete comment that describes this case as unsupported. This restores regression coverage for streaming across a gap between commit versions when `failOnDataLoss=false`. ## How was this patch tested? `git diff --check` passed. Tests were not run locally because this change only re-enables an existing test; execution is left to the Spark CI workflow. ## Does this PR introduce _any_ user-facing changes? No. This change only updates test coverage. Signed-off-by: You Zhou --- .../org/apache/spark/sql/delta/test/DeltaV2SourceSuite.scala | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceSuite.scala index 73912186b5f..cf8cc157d78 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceSuite.scala @@ -100,6 +100,7 @@ object DeltaV2SourceSuite { "incremental: first commit file missing, fails", "incremental: commit file gap between versions, fails", "incremental: first commit file missing, failOnDataLoss=false succeeds", + "incremental: commit file gap between versions, failOnDataLoss=false succeeds", "initial snapshot: commit file missing but checkpoint intact, succeeds", "initial snapshot: checkpoint missing but all commit files intact, succeeds", "initial snapshot: both checkpoint and commit file missing, fails", @@ -183,10 +184,6 @@ object DeltaV2SourceSuite { // nullability change fails instead of adopting the current table schema. "handling nullability schema changes", - // === Data Loss Detection === - // V2 only tolerates missing start versions with failOnDataLoss=false; mid-log gaps still - // throw InvalidTableException because non-contiguous versions are not a log-retention scenario. - "incremental: commit file gap between versions, failOnDataLoss=false succeeds", // These tests directly use DeltaSource, not applicable to the v2 path. "fail on missing trailing commit - trailing commit disappears between latestOffset and" + " getBatch readChangeFeed=true midVersionEndOffset=true", From 8e808544daa1a4684898e50e9887b6cae336b531 Mon Sep 17 00:00:00 2001 From: Zihao Xu Date: Mon, 16 Nov 2026 20:08:47 -0800 Subject: [PATCH 13/44] [Spark] Say catalog-managed in comments (#8151) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description The Delta protocol calls these tables catalog-managed, and the table feature is `catalogManaged`. Comments in the Spark connector still say "catalog-owned", "Catalog Owned" or "CatalogOwned tables". This PR changes that prose to "catalog-managed". ## How was this patch tested? Comment-only change. ## Does this PR introduce _any_ user-facing changes? No. --- .../ConcurrentIdentityColumnSchema.scala | 2 +- .../spark/sql/delta/ConflictChecker.scala | 2 +- .../spark/sql/delta/DeltaAnalysis.scala | 30 +++++++++---------- .../spark/sql/delta/DeltaHistoryManager.scala | 2 +- .../sql/delta/commands/CloneTableBase.scala | 16 +++++----- .../commands/CreateDeltaTableCommand.scala | 2 +- .../commands/alterDeltaTableCommands.scala | 2 +- .../CommitCoordinatorClient.scala | 10 +++++-- .../CoordinatedCommitsUsageLogs.scala | 4 +-- .../CoordinatedCommitsUtils.scala | 28 ++++++++--------- .../sql/delta/util/TransactionHelper.scala | 4 +-- ...DeltaIncrementalSetTransactionsSuite.scala | 4 +-- .../spark/sql/delta/DeltaLogSuite.scala | 4 +-- .../sql/delta/DeltaProtocolVersionSuite.scala | 2 +- .../spark/sql/delta/DeltaRetentionSuite.scala | 10 +++---- .../sql/delta/DescribeDeltaHistorySuite.scala | 4 +-- .../sql/delta/InCommitTimestampSuite.scala | 12 ++++---- .../CatalogOwnedEnablementSuite.scala | 12 ++++---- .../CatalogOwnedPropertySuite.scala | 14 ++++----- .../CoordinatedCommitsSuite.scala | 4 +-- .../CoordinatedCommitsTestUtils.scala | 14 ++++----- .../StagedCommitListingSuite.scala | 4 +-- .../delta/stats/DataSkippingAMTTests.scala | 2 +- 23 files changed, 96 insertions(+), 92 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/ConcurrentIdentityColumnSchema.scala b/spark/src/main/scala/org/apache/spark/sql/delta/ConcurrentIdentityColumnSchema.scala index 73b492bd939..919f14158ca 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/ConcurrentIdentityColumnSchema.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/ConcurrentIdentityColumnSchema.scala @@ -43,7 +43,7 @@ object ConcurrentIdentityColumnSchema { /** * The table id under which this table's sequences live in the sequence service. For a - * catalog-owned (UC coordinated-commits) table this is the UC table id, stamped into the + * catalog-managed (UC coordinated-commits) table this is the UC table id, stamped into the * table configuration at creation ([[UCCommitCoordinatorClient.UC_TABLE_ID_KEY]]). * The `metadata.id` fallback below is test-only, as CIC requires a table to be managed. */ 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 72f973b3810..ce9d9f82079 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 @@ -911,7 +911,7 @@ private[delta] class ConflictChecker( value.toBoolean // only allow enabling, not disabling case DeltaConfigs.IN_COMMIT_TIMESTAMP_ENABLEMENT_VERSION.key => isNew case DeltaConfigs.IN_COMMIT_TIMESTAMP_ENABLEMENT_TIMESTAMP.key => isNew - // Catalog-owned enablement configuration + // Catalog-managed enablement configuration case UCCommitCoordinatorClient.UC_TABLE_ID_KEY if currentTransactionInfo.protocol.isFeatureSupported(CatalogOwnedTableFeature) => isNew diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala index 8eeab88d4f6..9db1cb9f9b3 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala @@ -199,7 +199,7 @@ class DeltaAnalysis(protected val session: SparkSession) } - // Whether we are enabling Catalog-Owned via explicit property overrides. + // Whether we are enabling Catalog-Managed via explicit property overrides. var isEnablingCatalogOwnedViaExplicitPropertyOverrides: Boolean = false val catalogTableTarget = @@ -211,24 +211,24 @@ class DeltaAnalysis(protected val session: SparkSession) // used on the source delta table, then the corresponding fields would be set for the // sourceTable and needs to be removed from the targetTable's configuration. The fields // will then be set in the targetTable's configuration internally after. - // Coordinated commits/Catalog-Owned configurations from the source delta table should + // Coordinated commits/Catalog-Managed configurations from the source delta table should // also be left out, since CREATE LIKE is similar to CLONE, and we do not copy the // commit coordinator from the source table. // If users want a commit coordinator for the target table, they can // specify the configurations in the CREATE LIKE command explicitly. val sourceMetadata = deltaLogSrc.initialSnapshot.metadata - // Catalog-Owned: Specifying the table UUID in the TBLPROPERTIES clause + // Catalog-Managed: Specifying the table UUID in the TBLPROPERTIES clause // should be blocked. CatalogOwnedTableUtils.validateUCTableIdNotPresent(property = ctl.properties) - // Check whether we are trying to enable Catalog-Owned via explicit property overrides. - // The reason to check this is, if the source table is a Catalog-Owned table, and - // we are also trying to enable Catalog-Owned for the target table - We do *NOT* + // Check whether we are trying to enable Catalog-Managed via explicit property overrides. + // The reason to check this is, if the source table is a Catalog-Managed table, and + // we are also trying to enable Catalog-Managed for the target table - We do *NOT* // want to filter out [[CatalogOwnedTableFeature]] from the source table. If we do that, - // the resulting target table's protocol will *NOT* have CatalogOwned table feature + // the resulting target table's protocol will *NOT* have CatalogManaged table feature // present though we have explicitly specified it in the TBLPROPERTIES clause. - // This only applies to cases where source table has Catalog-Owned enabled. + // This only applies to cases where source table has Catalog-Managed enabled. // It works as intended if source table is a normal delta table. if (TableFeatureProtocolUtils.getSupportedFeaturesFromTableConfigs( configs = ctl.properties).contains(CatalogOwnedTableFeature)) { @@ -242,7 +242,7 @@ class DeltaAnalysis(protected val session: SparkSession) .filterKeys(!CoordinatedCommitsUtils.TABLE_PROPERTY_KEYS.contains(_)).toMap // ICT enablement provenance info should not be copied from the source .filterKeys(!InCommitTimestampUtils.ENABLEMENT_INFO_PROPERTY_KEYS.contains(_)).toMap - // Catalog-Owned: Do not copy table UUID from source table + // Catalog-Managed: Do not copy table UUID from source table .filterKeys(_ != UCCommitCoordinatorClient.UC_TABLE_ID_KEY).toMap new CatalogTable( @@ -280,21 +280,21 @@ class DeltaAnalysis(protected val session: SparkSession) } else { None } - // Catalog-Owned: Do not copy over [[CatalogOwnedTableFeature]] from source table + // Catalog-Managed: Do not copy over [[CatalogOwnedTableFeature]] from source table // except the certain case. val protocolAfterFilteringCatalogOwnedFromSource = protocol match { case Some(p) if !isEnablingCatalogOwnedViaExplicitPropertyOverrides => // Only filter out [[CatalogOwnedTableFeature]] when target table is not enabling - // CatalogOwned. + // CatalogManaged. // E.g., // - CREATE TABLE t1 LIKE t2 - // - Filter CatalogOwned table feature out since target table is not enabling - // CatalogOwned explicitly. + // - Filter CatalogManaged table feature out since target table is not enabling + // CatalogManaged explicitly. // - CREATE TABLE t1 LIKE t2 TBLPROPERTIES ( // 'delta.feature.catalogManaged' = 'supported' // ) - // - Do not filter CatalogOwned table feature out if target table is enabling - // CatalogOwned. + // - Do not filter CatalogManaged table feature out if target table is enabling + // CatalogManaged. Some(p.removeFeature(targetFeature = CatalogOwnedTableFeature)) case _ => protocol diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaHistoryManager.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaHistoryManager.scala index 45f2a43183f..d12d5a267ce 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaHistoryManager.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaHistoryManager.scala @@ -502,7 +502,7 @@ class DeltaHistoryManager( } else if (smallestDeltaVersion < Long.MaxValue) { throw DeltaErrors.noRecreatableHistoryFound(deltaLog.logPath) } else { - // For Catalog Owned tables, there are two cases in which a DELTA_NO_COMMITS_FOUND + // For Catalog Managed tables, there are two cases in which a DELTA_NO_COMMITS_FOUND // exception could be thrown: // // 1. If there is no checkpoint or commit 0, and there are only unbackfilled commits diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala index dbc9e4b4cf7..2aa0f6ca6f2 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala @@ -319,7 +319,7 @@ abstract class CloneTableBase( // ICT enablement provenance info refers to the source's log. The commit re-derives it for // the target (see InCommitTimestampUtils.getUpdatedMetadataWithICTEnablementInfo). .filterKeys(!InCommitTimestampUtils.ENABLEMENT_INFO_PROPERTY_KEYS.contains(_)) - // Catalog-Owned enabled table's UC table ID property is never copied over to the + // Catalog-Managed enabled table's UC table ID property is never copied over to the // target table. .filterKeys(_ != UCCommitCoordinatorClient.UC_TABLE_ID_KEY) .toMap @@ -418,9 +418,9 @@ abstract class CloneTableBase( validatedConfigurationsWithoutCoordinatedCommits ++ finalCatalogOwnedMetadata) // An AMT source makes a new target AMT only through the protocol, which the defaults applied - // while creating its metadata (e.g. the catalog-owned QoL features) do not see. Request AMT in - // the configuration too, so that they skip the features AMT is incompatible with. An existing - // target gets none of those defaults. + // while creating its metadata (e.g. the catalog-managed QoL features) do not see. Request AMT + // in the configuration too, so that they skip the features AMT is incompatible with. An + // existing target gets none of those defaults. if (!tableExists(targetSnapshot)) { AdaptiveMetadataTableFeatureBase.supportedBy(sourceTable.protocol).foreach { amtFeature => metadata = metadata.copy(configuration = metadata.configuration + @@ -454,7 +454,7 @@ abstract class CloneTableBase( spark: SparkSession, txn: OptimisticTransaction, opName: String): Protocol = { - // Catalog-Owned: Do not copy over [[CatalogOwnedTableFeature]] from source table. + // Catalog-Managed: Do not copy over [[CatalogOwnedTableFeature]] from source table. val sourceProtocol = sourceTable.protocol.removeFeature(targetFeature = CatalogOwnedTableFeature) // Pre-transaction version of the target table. @@ -465,14 +465,14 @@ abstract class CloneTableBase( // the table property overrides as table features set by it won't be in the transaction // metadata anymore. val validatedConfigurations = DeltaConfigs.validateConfigurations(tablePropertyOverrides) - // For CREATE CLONE, check the default spark configuration for Catalog-Owned. + // For CREATE CLONE, check the default spark configuration for Catalog-Managed. val catalogOwnedEnabledByDefaultConf = if (CatalogOwnedTableUtils.defaultCatalogOwnedEnabled(spark) && !tableExists(txn.snapshot)) { // Append [[CatalogOwnedTableFeature]] to the `configWithOverrides` below if table - // does not exist, to ensure the final target protocol contains CatalogOwned + // does not exist, to ensure the final target protocol contains CatalogManaged // if enabled by default. - // Note: We need this because CatalogOwned is enabled through single protocol + // Note: We need this because CatalogManaged is enabled through single protocol // without auxiliary metadata. Map(s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported") } else { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala index ed0a46ca2c4..ddd8d1b67ae 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala @@ -456,7 +456,7 @@ case class CreateDeltaTableCommand( // from source table. It will override the `newProtocol` being created in the above // `txn.updateMetadataForNewTable`. // In order to enable [[CatalogOwnedTableFeature]] for target table w/ default - // spark configuration of CatalogOwned enabled, we need to manually append + // spark configuration of CatalogManaged enabled, we need to manually append // [[CatalogOwnedTableFeature]] here to the existing source table protocol. val finalizedProtocol = if (CatalogOwnedTableUtils.defaultCatalogOwnedEnabled( spark = sparkSession)) { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala index f4e28d1b2d0..5b2999b87aa 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala @@ -154,7 +154,7 @@ case class AlterTableSetPropertiesDeltaCommand( true }.toMap - // For Catalog Owned table validation + // For Catalog Managed table validation CatalogOwnedTableUtils.validatePropertiesForAlterTableSetPropertiesDeltaCommand( txn.snapshot, propertyOverrides = filteredConfs) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala index 0e6992222ce..cd8d0f4639d 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala @@ -47,9 +47,11 @@ trait CommitCoordinatorBuilder { def build(spark: SparkSession, conf: Map[String, String]): CommitCoordinatorClient } -/** An extended builder interface for [[CommitCoordinatorClient]] with CatalogOwned table feature */ +/** + * An extended builder interface for [[CommitCoordinatorClient]] with CatalogManaged table feature + */ trait CatalogOwnedCommitCoordinatorBuilder extends CommitCoordinatorBuilder { - /** Returns a catalog-owned commit-coordinator client based for the given catalog. */ + /** Returns a catalog-managed commit-coordinator client based for the given catalog. */ def buildForCatalog(spark: SparkSession, catalogName: String): CommitCoordinatorClient } @@ -115,7 +117,9 @@ object CommitCoordinatorProvider { initialCommitCoordinatorBuilders.foreach(registerBuilder) } -/** Factory to get the correct [[CatalogOwnedCommitCoordinatorBuilder]] for a catalog-owned table */ +/** + * Factory to get the correct [[CatalogOwnedCommitCoordinatorBuilder]] for a catalog-managed table + */ object CatalogOwnedCommitCoordinatorProvider { // mapping from catalog names to the corresponding [[CatalogOwnedCommitCoordinatorBuilder]]s. private val catalogNameToBuilderMapping = diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala index 673e087e7fb..cf99c23fb31 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala @@ -16,9 +16,9 @@ package org.apache.spark.sql.delta.coordinatedcommits -/** Class containing usage logs emitted by Catalog Owned. */ +/** Class containing usage logs emitted by Catalog Managed. */ object CatalogOwnedUsageLogs { - /** Common prefix for all catalog-owned usage logs. */ + /** Common prefix for all catalog-managed usage logs. */ val PREFIX = "delta.catalogOwned" /** diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala index aeb5e3fd0f2..aa87db15c42 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala @@ -112,9 +112,9 @@ object CatalogOwnedTableUtils extends DeltaLogging { } .orElse { if (Utils.isTesting) { - // In unit test with a path based access, it is possible to enable CatalogOwned with + // In unit test with a path based access, it is possible to enable CatalogManaged with // in-memory commit coordinator. In this case, we return table commit coordinator - // registered in the provider so that it can still test CatalogOwned table feature + // registered in the provider so that it can still test CatalogManaged table feature // capability. CatalogOwnedCommitCoordinatorProvider.getBuilder(DEFAULT_CATALOG_NAME_FOR_TESTING) .flatMap{ builder => @@ -130,7 +130,7 @@ object CatalogOwnedTableUtils extends DeltaLogging { )) } } - // This table is catalog owned table but catalogTableOpt is not defined. This means + // This table is catalog managed table but catalogTableOpt is not defined. This means // that the caller is accessing this table by path-based or the calling code path is missing // the CatalogTable. // TODO: Better error message with proper error code. @@ -182,7 +182,7 @@ object CatalogOwnedTableUtils extends DeltaLogging { /** * The "Quality of Life" table features that will be enabled automatically - * when creating CatalogOwned tables. + * when creating CatalogManaged tables. * Note that we also include the properties (i.e., DeltaConfig and target value) * used to determine whether the table features and the corresponding * properties/metadata have been enabled or not. @@ -198,7 +198,7 @@ object CatalogOwnedTableUtils extends DeltaLogging { ) /** - * Return true if we should enable CatalogOwned either via default spark + * Return true if we should enable CatalogManaged either via default spark * session configuration during creating a new table, * or via the explicit table property overrides. */ @@ -258,12 +258,12 @@ object CatalogOwnedTableUtils extends DeltaLogging { DeltaConfigs.IN_COMMIT_TIMESTAMP_ENABLEMENT_TIMESTAMP) /** - * The main ICT table properties used as dependencies for Catalog-Owned enabled table. + * The main ICT table properties used as dependencies for Catalog-Managed enabled table. */ val ICT_TABLE_PROPERTY_KEYS: Seq[String] = ICT_TABLE_PROPERTY_CONFS.map(_.key) /** - * Verifies that the property keys do not contain any ICT dependencies for Catalog-Owned. + * Verifies that the property keys do not contain any ICT dependencies for Catalog-Managed. */ private[delta] def verifyNotContainsICTConfigurations(propKeys: Seq[String]): Unit = { ICT_TABLE_PROPERTY_KEYS.foreach { key => @@ -289,17 +289,17 @@ object CatalogOwnedTableUtils extends DeltaLogging { } /** - * Validates the Catalog-Owned configurations in explicit command overrides for + * Validates the Catalog-Managed configurations in explicit command overrides for * `AlterTableSetPropertiesDeltaCommand`. * * If [[CatalogOwnedTableFeature]] presents, we do NOT allow users to - * modify any ICT properties that Catalog-Owned depends on. + * modify any ICT properties that Catalog-Managed depends on. */ def validatePropertiesForAlterTableSetPropertiesDeltaCommand( snapshot: Snapshot, propertyOverrides: Map[String, String]): Unit = { if (snapshot.isCatalogOwned) { - // For Catalog-Owned enabled tables, check the dependent ICT properties. + // For Catalog-Managed enabled tables, check the dependent ICT properties. // Note: Upgrade/Downgrade have been blocked earlier, which do not need to be // checked here. verifyNotContainsICTConfigurations(propKeys = propertyOverrides.keys.toSeq) @@ -310,7 +310,7 @@ object CatalogOwnedTableUtils extends DeltaLogging { * Validates the configurations to unset for `AlterTableUnsetPropertiesDeltaCommand`. * * If the table already has [[CatalogOwnedTableFeature]] present, - * we do not allow users to unset any of the ICT properties that Catalog-Owned depends on. + * we do not allow users to unset any of the ICT properties that Catalog-Managed depends on. */ def validatePropertiesForAlterTableUnsetPropertiesDeltaCommand( snapshot: Snapshot, @@ -399,10 +399,10 @@ object CatalogOwnedTableUtils extends DeltaLogging { } /** - * Whether Catalog-Owned is enabled via default SparkSession configuration. + * Whether Catalog-Managed is enabled via default SparkSession configuration. * * @param spark The SparkSession to check. - * @return True if Catalog-Owned is enabled by default, false otherwise. + * @return True if Catalog-Managed is enabled by default, false otherwise. */ def defaultCatalogOwnedEnabled(spark: SparkSession): Boolean = { spark.conf @@ -794,7 +794,7 @@ object CoordinatedCommitsUtils extends DeltaLogging { */ def backfillWhenCoordinatedCommitsDisabled(snapshot: Snapshot): Unit = { if (snapshot.getTableCommitCoordinatorForWrites.nonEmpty || snapshot.isCatalogOwned) { - // Coordinated commits or Catalog-owned is enabled on the table. Don't backfill + // Coordinated commits or Catalog-managed is enabled on the table. Don't backfill // as backfills are managed by commit-coordinators. return } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala b/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala index 26cc737e732..8c605947647 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala @@ -168,7 +168,7 @@ trait TransactionHelper extends DeltaLogging { private[delta] lazy val readSnapshotTableCommitCoordinatorClientOpt: Option[TableCommitCoordinatorClient] = { if (snapshot.isCatalogOwned) { - // Catalog owned table's commit coordinator is always determined by the catalog. + // Catalog managed table's commit coordinator is always determined by the catalog. CatalogOwnedTableUtils.populateTableCommitCoordinatorFromCatalog( spark, catalogTable, snapshot ) @@ -222,7 +222,7 @@ trait TransactionHelper extends DeltaLogging { } else { metadataToUse.coordinatedCommitsCoordinatorName.getOrElse("NONE") }, - // For Catalog-Owned table, the coordinator conf for UC-CC is [[Map.empty]] + // For Catalog-Managed table, the coordinator conf for UC-CC is [[Map.empty]] // so we don't distinguish between CO/CC here. commitCoordinatorConf = metadataToUse.coordinatedCommitsCoordinatorConf) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaIncrementalSetTransactionsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaIncrementalSetTransactionsSuite.scala index 92920398a5b..399564bee80 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaIncrementalSetTransactionsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaIncrementalSetTransactionsSuite.scala @@ -147,7 +147,7 @@ class DeltaIncrementalSetTransactionsSuite commitSetTxn(deltaLog, "app-1", version = 2, lastUpdated = 2) // 2nd commit // Commit doesn't trigger stateReconstruction and so the incremental CRC won't have // setTransactions present until `setTransactions` API is explicitly invoked before the - // commit. This also holds for CatalogOwned tables with Row Tracking enabled: the + // commit. This also holds for CatalogManaged tables with Row Tracking enabled: the // `domainMetadata` read done by RowId.assignFreshRowIds -> extractHighWatermark is // served from the CRC, so it no longer forces a state reconstruction. assert(deltaLog.update().checksumOpt.get.setTransactions.isEmpty) // crc has no set-txn @@ -234,7 +234,7 @@ class DeltaIncrementalSetTransactionsSuite // 2. If `computeStatePreloaded` is not set, then Snapshot doesn't have computeState // pre-computed. So next commit will not trigger incremental computation of // [[SetTransaction]]. - // Note that commits themselves never pre-compute the state, not even for CatalogOwned + // Note that commits themselves never pre-compute the state, not even for CatalogManaged // tables with Row Tracking enabled: the `domainMetadata` read performed by // RowId.assignFreshRowIds is served from the CRC instead of forcing a state // reconstruction. diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala index 2f65776688d..77dbb0f09ec 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala @@ -518,7 +518,7 @@ class DeltaLogSuite extends QueryTest .filter(!_.getPath.getName.startsWith("_")) .foreach(f => fs.delete(f.getPath, true)) if (catalogOwnedDefaultCreationEnabledInTests) { - // For Catalog Owned table with a commit that is not backfilled, we can't use + // For Catalog Managed table with a commit that is not backfilled, we can't use // 00000000002.json yet. Contact commit coordinator to get uuid file path to malform json // file. val oc = getCatalogOwnedCommitCoordinatorClient( @@ -630,7 +630,7 @@ class DeltaLogSuite extends QueryTest val log = DeltaLog.forTable(spark, path) var commitFilePath = FileNames.unsafeDeltaFile(log.logPath, 1L) if (catalogOwnedDefaultCreationEnabledInTests) { - // For Catalog Owned table with a commit that is not backfilled, we can't use + // For Catalog Managed table with a commit that is not backfilled, we can't use // 00000000001.json yet. Contact commit coordinator to get uuid file path to malform json // file. val oc = getCatalogOwnedCommitCoordinatorClient( diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala index 59bbc7913e5..862b56e73a1 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala @@ -3798,7 +3798,7 @@ trait DeltaProtocolVersionSuiteBase extends QueryTest featureExpectedAtTheEnd: Boolean = false): Unit = { val featureName = VacuumProtocolCheckTableFeature.name withTempTable(createTable = false) { tableName => - // Register a temporary InMemory-CC builder to support CatalogOwned table creation. + // Register a temporary InMemory-CC builder to support CatalogManaged table creation. CatalogOwnedCommitCoordinatorProvider.clearBuilders() CatalogOwnedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaRetentionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaRetentionSuite.scala index d17579eddc8..d15fd781e90 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaRetentionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaRetentionSuite.scala @@ -131,7 +131,7 @@ class DeltaRetentionSuite extends QueryTest log.checkpoint() - // With V2 checkpoints (QoL feature for CatalogOwned tables), checkpoint files have UUIDs + // With V2 checkpoints (QoL feature for CatalogManaged tables), checkpoint files have UUIDs // and may be .json or .parquet (e.g., "04.checkpoint..json" instead of // "04.checkpoint.parquet"). We check for the commit log and CRC, and verify that at least // one checkpoint file exists for version 4. @@ -193,7 +193,7 @@ class DeltaRetentionSuite extends QueryTest assert(maxChkFile === minDeltaFile, "Delta files before the last checkpoint version should have been deleted") - // With V2 checkpoints (QoL feature for CatalogOwned tables), cleanup behavior may retain + // With V2 checkpoints (QoL feature for CatalogManaged tables), cleanup behavior may retain // additional checkpoint files for safety. We check that there are no more than 2 checkpoint // files remaining (classic behavior expects 1, V2 may have up to 2). assert(getCheckpointFiles(logPath).length <= 2, @@ -341,7 +341,7 @@ class DeltaRetentionSuite extends QueryTest intervalStringToMillis("interval 1 day")) // Create new checkpoints so that the previous version can be deleted. - // With V2 checkpoints (QoL feature for CatalogOwned tables), we need to create version 2 + // With V2 checkpoints (QoL feature for CatalogManaged tables), we need to create version 2 // before version 0 can be cleaned up, as V2 checkpoints have stricter retention policies // that require more checkpoint history before allowing cleanup. log.startTransaction().commit(createTestAddFile(encodedPath = "1") :: Nil, testOp) @@ -775,7 +775,7 @@ class DeltaRetentionSuite extends QueryTest .filter(f => FileNames.checkpointVersion(new Path(f.getCanonicalPath)) == version) if (version % 10 == 0) { - // With V2 checkpoints (QoL feature for CatalogOwned), checkpoints may be single-file. + // With V2 checkpoints (QoL feature for CatalogManaged), checkpoints may be single-file. // Classic checkpoints with DELTA_CHECKPOINT_PART_SIZE=1 are multi-part (>= 2 files). assert(chks.length >= 1) // At least one checkpoint file chks.foreach { chk => @@ -791,7 +791,7 @@ class DeltaRetentionSuite extends QueryTest // ensure that the checkpoint at version 10 exists val checkpoint10Files = getCheckpointFiles(logPath) .filter(f => FileNames.checkpointVersion(new Path(f.getCanonicalPath)) == 10) - // With V2 checkpoints (QoL feature for CatalogOwned), checkpoints may be single-file + // With V2 checkpoints (QoL feature for CatalogManaged), checkpoints may be single-file assert(checkpoint10Files.length >= 1) // At least one checkpoint file assert(checkpoint10Files.forall(_.exists)) val deltaFiles = (0 to 15).map { i => diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DescribeDeltaHistorySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DescribeDeltaHistorySuite.scala index 5bde6cf8d62..fe57fc19054 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DescribeDeltaHistorySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DescribeDeltaHistorySuite.scala @@ -192,7 +192,7 @@ trait DescribeDeltaHistorySuiteBase .asInstanceOf[Map[String, String]] } - // Returns necessary delta property json expected for the test. If Catalog-Owned is enabled, + // Returns necessary delta property json expected for the test. If Catalog-Managed is enabled, // a few properties will be automatically populated, and this method will take care of it. protected def getProperties( extraProperty: Option[Map[String, String]] = None): Map[String, String] = { @@ -202,7 +202,7 @@ trait DescribeDeltaHistorySuiteBase => config.key -> value }.toMap ++ // DV is explicitly disabled here b/c the current suite is incompatible - // w/ DV, and we automatically enable it as part of CatalogOwned QoL features. + // w/ DV, and we automatically enable it as part of CatalogManaged QoL features. Map(s"${DeltaConfigs.ENABLE_DELETION_VECTORS_CREATION.key}" -> "false") } else { Map.empty[String, String] diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala index 952340eba57..9fc0aef9728 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala @@ -101,7 +101,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset( "Create a non-inCommitTimestamp table and then enable timestamp") { withSQLConf( @@ -331,7 +331,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset( "Enablement tracking works when ICT is enabled post commit 0") { withSQLConf( @@ -359,7 +359,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset("Conflict resolution of enablement version") { withSQLConf( DeltaConfigs.IN_COMMIT_TIMESTAMPS_ENABLED.defaultTablePropertyKey -> false.toString @@ -913,7 +913,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset( "commitLarge should correctly set the enablement tracking properties") { withTempTable(createTable = false) { tableName => @@ -1201,7 +1201,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset("DeltaHistoryManager.getActiveCommitAtTime: " + "works correctly when the history has both ICT and non-ICT commits") { withSQLConf( @@ -1319,7 +1319,7 @@ class InCommitTimestampSuite } } - // Catalog Owned will also automatically enable ICT. + // Catalog Managed will also automatically enable ICT. testWithDefaultCommitCoordinatorUnset("DeltaHistoryManager.getHistory --- " + "works correctly when the history has both ICT and non-ICT commits") { withSQLConf( diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala index 27833cad037..799ec539eb2 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala @@ -49,12 +49,12 @@ class CatalogOwnedEnablementSuite private val ICT_ENABLED_KEY = DeltaConfigs.IN_COMMIT_TIMESTAMPS_ENABLED.key /** - * Validate that the table has the expected enablement of Catalog-Owned table feature. + * Validate that the table has the expected enablement of Catalog-Managed table feature. * Specifically, [[CatalogOwnedTableFeature]] and its dependent features should be present * in the table protocol. * * @param tableName The name of the table to validate. - * @param expectEnabled Whether the Catalog-Owned table feature should be enabled or not. + * @param expectEnabled Whether the Catalog-Managed table feature should be enabled or not. */ private def validateCatalogOwnedCompleteEnablement( tableName: String, @@ -96,10 +96,10 @@ class CatalogOwnedEnablementSuite /** * Helper function to set up and validate the initial table to be tested - * for Catalog Owned enablement. + * for Catalog Managed enablement. * * @param tableName The name of the table to be created for the test. - * @param createCatalogOwnedTableAtInit Whether to enable Catalog-Owned table feature + * @param createCatalogOwnedTableAtInit Whether to enable Catalog-Managed table feature * at the time of table creation. */ private def testCatalogOwnedEnablementSetup( @@ -294,7 +294,7 @@ class CatalogOwnedEnablementSuite } // QoL features should also be enabled w/ other additional features enablement - // during CatalogOwned creation. + // during CatalogManaged creation. withTable("t1") { // Enable [[ClusteringTableFeature]] and [[ChangeDataFeedTableFeature]] during CO creation. createTable("t1", clusterBy = Seq("id"), properties = Map( @@ -368,7 +368,7 @@ class CatalogOwnedEnablementSuite test("Upgrade should be blocked since it is not supported yet") { withRandomTable( - // Do not enable Catalog-Owned at the beginning when creating table + // Do not enable Catalog-Managed at the beginning when creating table createCatalogOwnedTableAtInit = false ) { tableName => val error = intercept[NotImplementedException] { diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala index 062dfbad9c6..43f9543d62d 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala @@ -34,29 +34,29 @@ class CatalogOwnedPropertySuite extends QueryTest with CatalogOwnedTestBaseSuite { // Register the mock commit coordinator builder for testing, but don't enable - // CatalogOwned by default (tests explicitly enable it when needed). + // CatalogManaged by default (tests explicitly enable it when needed). override def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = Some(3) override def catalogOwnedDefaultCreationEnabledInTests: Boolean = false /** - * Validate if the table is catalog owned or not by checking the following: + * Validate if the table is catalog managed or not by checking the following: * 1) [[Snapshot.isCatalogOwned]] === expected * 2) [[Metadata.configuration]] contains [[UCCommitCoordinatorClient.UC_TABLE_ID_KEY]] * 3) [[Protocol.readerAndWriterFeatureNames]] contains [[CatalogOwnedTableFeature.name]] * and its dependent features. * * @param tableName The name of the table to validate. - * @param expected The expected value of whether the table is catalog owned or not. + * @param expected The expected value of whether the table is catalog managed or not. */ private def validateCatalogOwnedAndUCTableId(tableName: String, expected: Boolean): Unit = { val (_, snapshot) = DeltaLog.forTableWithSnapshot(spark, new TableIdentifier(tableName)) assert(snapshot.isCatalogOwned === expected) assert(snapshot.metadata.configuration.contains(UCCommitCoordinatorClient.UC_TABLE_ID_KEY) === expected) - // CatalogOwned enabled table should have the protocol version of (3, 7), + // CatalogManaged enabled table should have the protocol version of (3, 7), // since the table can't have a [[ReaderWriterTableFeature]] w/o this version. if (expected) { - // Only verify protocol version for expected CatalogOwned table. + // Only verify protocol version for expected CatalogManaged table. validateProtocolMinReaderWriterVersion( tableName, expectedMinReaderVersion = 3, @@ -152,7 +152,7 @@ class CatalogOwnedPropertySuite extends QueryTest createTableAndValidateCatalogOwned(tableName = "t1", withCatalogOwned = true) val ucTableId1 = getUCTableIdFromTable(tableName = "t1") - // Target table should remain a catalog-owned table with same `ucTableId` + // Target table should remain a catalog-managed table with same `ucTableId` sql("REPLACE TABLE t1 (id LONG) USING delta") val ucTableId2 = getUCTableIdFromTable(tableName = "t1") validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) @@ -486,7 +486,7 @@ class CatalogOwnedPropertySuite extends QueryTest } test("[CREATE LIKE] Specifying table UUID should be blocked") { withTable("t1", "t2", "t3") { - // Source catalog-owned table + // Source catalog-managed table createTableAndValidateCatalogOwned(tableName = "t1", withCatalogOwned = true) val error1 = intercept[UnsupportedOperationException] { diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala index 49cd05f6db4..f10d698cea5 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala @@ -325,7 +325,7 @@ class CatalogOwnedSuite with CatalogOwnedTestBaseSuite { override def sparkConf: SparkConf = { - // Make sure all new tables in tests use CatalogOwned table feature by default. + // Make sure all new tables in tests use CatalogManaged table feature by default. super.sparkConf.set(defaultCatalogOwnedFeatureEnabledKey, "supported") } } @@ -737,7 +737,7 @@ abstract class CommitCoordinatorSuiteBase val (_, snapshot) = DeltaLog.forTableWithSnapshot(spark, CatalystTableIdentifier("t1")) if (isCatalogOwnedTest) { assert(snapshot.isCatalogOwned) - // Only [[IN_COMMIT_TIMESTAMPS_ENABLED]] should be set for CatalogOwned + // Only [[IN_COMMIT_TIMESTAMPS_ENABLED]] should be set for CatalogManaged // since we don't support upgrade yet. assert(snapshot.metadata.configuration.contains(IN_COMMIT_TIMESTAMPS_ENABLED.key)) } else { diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala index 6c2744bff0b..e8bad430d74 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala @@ -46,7 +46,7 @@ import org.apache.spark.sql.test.SharedSparkSession case object CatalogManagedMaintenanceIncompatible extends Tag("CatalogManagedMaintenanceIncompatible") -// This trait is built to serve as a base trait for tests built for both CatalogOwned +// This trait is built to serve as a base trait for tests built for both CatalogManaged // and commit-coordinators table feature. trait CommitCoordinatorUtilBase { /** @@ -56,13 +56,13 @@ trait CommitCoordinatorUtilBase { /** * Runs the function `f` with commit coordinator table feature unset. - * Any table created in function `f` have CatalogOwned/CoordinatedCommits disabled by default. + * Any table created in function `f` have CatalogManaged/CoordinatedCommits disabled by default. */ def withoutDefaultCCTableFeature(f: => Unit): Unit /** * Runs the function `f` with commit coordinator table feature set. - * Any table created in function `f` have CatalogOwned/CoordinatedCommits enabled by default.` + * Any table created in function `f` have CatalogManaged/CoordinatedCommits enabled by default.` */ def withDefaultCCTableFeature(f: => Unit): Unit @@ -79,7 +79,7 @@ trait CommitCoordinatorUtilBase { def propertiesString: String /** - * Returns true if this test is about CatalogOwned table feature. + * Returns true if this test is about CatalogManaged table feature. * Returns false if this test is about CoordinatedCommits tabel feature. */ def isCatalogOwnedTest: Boolean @@ -97,7 +97,7 @@ trait CatalogOwnedTestBaseSuite val defaultCatalogOwnedFeatureEnabledKey: String = TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) - // If this config is not overridden, newly created table is not CatalogOwned by default. + // If this config is not overridden, newly created table is not CatalogManaged by default. def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = None def catalogOwnedDefaultCreationEnabledInTests: Boolean = @@ -281,7 +281,7 @@ trait CatalogOwnedTestBaseSuite } /** - * Constructs the specific table properties for Catalog Owned tables. + * Constructs the specific table properties for Catalog Managed tables. * * @param spark The Spark session. * @param metadata The metadata of the CC table. @@ -318,7 +318,7 @@ trait CatalogOwnedTestBaseSuite /** * Returns the properties that are expected to show up in the table properties of a Delta table - * when catalog owned is enabled in tests. + * when catalog managed is enabled in tests. */ def extractCatalogOwnedSpecificPropertiesIfEnabled( metadata: Metadata): Iterable[(String, String)] = { diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/StagedCommitListingSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/StagedCommitListingSuite.scala index c45ab281f96..a7af3ecae2d 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/StagedCommitListingSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/StagedCommitListingSuite.scala @@ -33,7 +33,7 @@ import org.apache.spark.SparkConf import org.apache.spark.sql.QueryTest /** - * On a Catalog Owned table the fs listing must not promote a staged-commit file + * On a Catalog Managed table the fs listing must not promote a staged-commit file * (`_staged_commits/N..json`) to a commit. [[RecursiveListingLocalLogStore]] reproduces a * recursive-listing LogStore hermetically (no real object store). */ @@ -45,7 +45,7 @@ class StagedCommitListingSuite extends QueryTest override protected def sparkConf: SparkConf = super.sparkConf.set(logStoreClassConfKey, classOf[RecursiveListingLocalLogStore].getName) - /** Runs `f` with Catalog Owned (CCv2) and staged-commit filtering enabled. */ + /** Runs `f` with Catalog Managed (CCv2) and staged-commit filtering enabled. */ private def withCatalogOwnedCommits(f: => Unit): Unit = withDefaultCCTableFeature { withSQLConf( DeltaSQLConf.DELTA_SNAPSHOT_FILESYSTEM_LISTING_FILTER_STAGED_COMMITS_ENABLED.key -> diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/stats/DataSkippingAMTTests.scala b/spark/src/test/scala/org/apache/spark/sql/delta/stats/DataSkippingAMTTests.scala index 20f6d7323a2..813a0b1c969 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/stats/DataSkippingAMTTests.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/stats/DataSkippingAMTTests.scala @@ -35,7 +35,7 @@ trait DataSkippingAMTBase extends DataSkippingDeltaTestsBase import testImplicits._ // AMT requires the catalogManaged feature. `catalogOwnedCoordinatorBackfillBatchSize = Some(1)` - // registers the in-memory commit coordinator (and enables catalog-owned-by-default) so + // registers the in-memory commit coordinator (and enables catalog-managed-by-default) so // catalog-managed AMT tables can be created locally, backfilling every commit immediately. override def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = Some(1) From 090e69821d6da9b51b391d699240bd69a292d2d2 Mon Sep 17 00:00:00 2001 From: Zihao Xu Date: Mon, 16 Nov 2026 20:20:23 -0800 Subject: [PATCH 14/44] [Spark] Rename the CatalogOwnedTableFeature and CatalogOwnedTableUtils definitions (#8158) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Stacked on #8151; review the last commit. Renames the `CatalogOwnedTableFeature` and `CatalogOwnedTableUtils` objects to `CatalogManagedTableFeature` and `CatalogManagedTableUtils`. The feature name in the protocol stays `catalogManaged`. The old names stay as aliases, in the `delta` package object and in a new `coordinatedcommits` package object, so the callers keep compiling until the PRs stacked on this one move them to the new names. `UCDeltaCatalogClientImpl.scala` moves to the new name here. ## How was this patch tested? Rename only, no new tests. Apart from the aliases and the line wrapping, every changed token is an old name changed to the new one. ## Does this PR introduce _any_ user-facing changes? No. --- .../apache/spark/sql/delta/TableFeature.scala | 6 ++--- .../catalog/UCDeltaCatalogClientImpl.scala | 6 ++--- .../CoordinatedCommitsUtils.scala | 6 ++--- .../delta/coordinatedcommits/package.scala | 23 +++++++++++++++++++ .../org/apache/spark/sql/delta/package.scala | 3 +++ .../CatalogOwnedEnablementSuite.scala | 2 +- 6 files changed, 36 insertions(+), 10 deletions(-) create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala b/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala index 8c05b14d80e..b83a71883af 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala @@ -400,7 +400,7 @@ object TableFeature { VariantShreddingPreviewTableFeature, VariantShreddingTableFeature, FileTypePreviewTableFeature, - CatalogOwnedTableFeature, + CatalogManagedTableFeature, CoordinatedCommitsTableFeature, CheckpointProtectionTableFeature) if (isTesting && testingFeaturesEnabled) { @@ -967,7 +967,7 @@ sealed abstract class AdaptiveMetadataTableFeatureBase(name: String) // must be present. Note that presence alone is not enough; `id` mode is enforced separately // in [[OptimisticTransaction.scala]]. override def requiredFeatures: Set[TableFeature] = Set( - CatalogOwnedTableFeature, + CatalogManagedTableFeature, RowTrackingFeature, DomainMetadataTableFeature, DeletionVectorsTableFeature, @@ -1356,7 +1356,7 @@ object CoordinatedCommitsTableFeature } /** Table feature to represent tables that commits are managed by catalog */ -object CatalogOwnedTableFeature +object CatalogManagedTableFeature extends ReaderWriterFeature(name = "catalogManaged") with RemovableFeature { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/catalog/UCDeltaCatalogClientImpl.scala b/spark/src/main/scala/org/apache/spark/sql/delta/catalog/UCDeltaCatalogClientImpl.scala index 478d2f0e274..592e1f8148b 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/catalog/UCDeltaCatalogClientImpl.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/catalog/UCDeltaCatalogClientImpl.scala @@ -47,7 +47,7 @@ import org.apache.spark.sql.catalyst.catalog.{ CatalogTableType } import org.apache.spark.sql.connector.catalog.{CatalogV2Util, Identifier, Table, TableCatalog, V1Table} -import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, ClusteringTableFeature, DeltaConfigs, DeltaErrors, MaterializedRowCommitVersion, MaterializedRowId, TableFeature} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, ClusteringTableFeature, DeltaConfigs, DeltaErrors, MaterializedRowCommitVersion, MaterializedRowId, TableFeature} import org.apache.spark.sql.delta.actions.{Action, AddFile, CommitInfo, DomainMetadata, Metadata, Protocol, RemoveFile, TableFeatureProtocolUtils} import org.apache.spark.sql.delta.actions.TableFeatureProtocolUtils.FEATURE_PROP_SUPPORTED import org.apache.spark.sql.delta.CatalogManagedTableMaintenanceOperation.ALLOWED_OPERATIONS_PROPERTY @@ -436,7 +436,7 @@ private[catalog] class UCDeltaCatalogClientImpl( /** Reject `delta.feature.catalogManaged` override to anything other than `supported`. */ private def rejectCatalogManagedOverride( properties: util.Map[String, String], qualifiedName: String): Unit = { - val key = TableFeatureProtocolUtils.propertyKey(CatalogOwnedTableFeature) + val key = TableFeatureProtocolUtils.propertyKey(CatalogManagedTableFeature) val value = properties.get(key) if (value != null && value != FEATURE_PROP_SUPPORTED) { throw new IllegalArgumentException( @@ -459,7 +459,7 @@ private[catalog] class UCDeltaCatalogClientImpl( if (!provider.contains("delta")) { throw DeltaErrors.notADeltaTableException("REPLACE TABLE", qualified) } - val catalogManagedKey = TableFeatureProtocolUtils.propertyKey(CatalogOwnedTableFeature) + val catalogManagedKey = TableFeatureProtocolUtils.propertyKey(CatalogManagedTableFeature) val isCatalogManaged = Option(info.getMetadata.getConfiguration) .map(_.asScala.toMap) .exists(_.get(catalogManagedKey).contains(FEATURE_PROP_SUPPORTED)) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala index aa87db15c42..6539820f8c3 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala @@ -46,7 +46,7 @@ import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan import org.apache.spark.sql.connector.catalog.CatalogPlugin import org.apache.spark.util.Utils -object CatalogOwnedTableUtils extends DeltaLogging { +object CatalogManagedTableUtils extends DeltaLogging { /** The default catalog name only used for testing. */ val DEFAULT_CATALOG_NAME_FOR_TESTING: String = "spark_catalog" @@ -212,7 +212,7 @@ object CatalogOwnedTableUtils extends DeltaLogging { // Check default spark session configuration only when creating a new table. val isEnablingCOByDefault = - isCreatingNew && CatalogOwnedTableUtils.defaultCatalogOwnedEnabled(spark) + isCreatingNew && CatalogManagedTableUtils.defaultCatalogOwnedEnabled(spark) isExplicitlyEnablingCO || isEnablingCOByDefault } @@ -874,7 +874,7 @@ object CoordinatedCommitsUtils extends DeltaLogging { * while rebuilding the configuration map. */ def getExplicitQoLConfigurations(properties: Map[String, String]): Map[String, String] = { - val qolKeys = CatalogOwnedTableUtils.QOL_TABLE_FEATURES_AND_PROPERTIES.map(_._2.key).toSet + val qolKeys = CatalogManagedTableUtils.QOL_TABLE_FEATURES_AND_PROPERTIES.map(_._2.key).toSet properties.filter { case (k, _) => qolKeys.contains(k) } } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala new file mode 100644 index 00000000000..95b986d4fd2 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala @@ -0,0 +1,23 @@ +/* + * Copyright (2026) 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 + +package object coordinatedcommits { + // The old names, kept until their callers use the new ones. + val CatalogOwnedTableUtils: CatalogManagedTableUtils.type = CatalogManagedTableUtils +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/package.scala b/spark/src/main/scala/org/apache/spark/sql/delta/package.scala index 56b1e9e9e40..590369eddc5 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/package.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/package.scala @@ -36,4 +36,7 @@ package object delta { * concrete [[Snapshot]] implementation to `SnapshotV1`. */ type SnapshotV1 = Snapshot + + // The old name, kept until its callers use the new one. + val CatalogOwnedTableFeature: CatalogManagedTableFeature.type = CatalogManagedTableFeature } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala index 799ec539eb2..a6c9e1bf1a2 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala @@ -238,7 +238,7 @@ class CatalogOwnedEnablementSuite "path" -> log.logPath.toString, "version" -> expectedVersion, "stackTrace" -> - ("org.apache.spark.sql.delta.coordinatedcommits.CatalogOwnedTableUtils$" + + ("org.apache.spark.sql.delta.coordinatedcommits.CatalogManagedTableUtils$" + ".recordCommitCoordinatorPopulationUsageLog"), "latestCheckpointVersion" -> -1, // Only check for certain fields of `checksumOpt` since the entire map From df10b5472bdb8ae0da9c5763c17485da8e545c3d Mon Sep 17 00:00:00 2001 From: openinx Date: Mon, 16 Nov 2026 20:25:54 -0800 Subject: [PATCH 15/44] [Spark] Attribute Delta V2 snapshot and cache operations (#8067) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Record substantive Delta V2 snapshot loads, history requests, file-state construction, and table-manager cache lifecycle operations through the existing operation hooks. Normalize operation names under `delta.v2.` and attribute events to the table path without requiring a DeltaLog-backed provider. Cache timing uses a shared elapsed-time helper. Keep `KernelContext` focused on filesystem options and its LogStore. Remove the unused table-path constructor/factory argument and update the production and test callers; engine creation does not use that argument. Keep configuration materialization scoped to the active session with table options overlaid. Path and payload construction for table-scoped events is guarded so non-fatal telemetry failures preserve the caller's control flow and original exception. Ordinary cache hits, snapshot freshness decisions, cleanup behavior, and exceptions retain their existing behavior. This is the root of the operations stack: #8067, #8068. It is based directly on master and can be reviewed independently of the diagnostics stack (#8062, #8066). Design agreement is tracked in #8065 and remains pending. ## How was this patch tested? Both `sparkV2/Test/compile` and `spark/Test/compile` passed. Six affected suites passed all 92 tests with zero failures or skips: KernelContextSuite (7), CachedSnapshotManagerSuite (35), UCManagedTableSnapshotManagerSuite (10), DeltaV2SnapshotSuite (23), KernelSnapshotUtilsSuite (5), and ApplyV2ReadOptionsSuite (12). Style checks passed for all changed Scala files. Whitespace checks pass. CI must rerun on the updated head. ## Does this PR introduce _any_ user-facing changes? Yes. Delta V2 operation hooks gain consistent names and table attribution. Query results and the transaction-log format are unchanged. --------- Signed-off-by: Zheng Hu --- .../delta/v2/ApplyV2ReadOptionsSuite.scala | 4 +- .../v2/interop/DeltaV2SnapshotSuite.scala | 3 +- .../v2/interop/KernelSnapshotUtilsSuite.scala | 3 +- .../spark/sql/delta/v2/DeltaV2Logging.scala | 64 +++++++- .../v2/interop/DeltaV2SnapshotManager.scala | 17 +- .../v2/interop/KernelSnapshotUtils.scala | 11 +- .../sql/delta/v2/kernel/KernelContext.scala | 9 +- .../delta/v2/kernel/KernelEngineFactory.scala | 7 +- .../tablemanager/CachedSnapshotManager.scala | 149 ++++++++++++------ .../DeltaV2TableManagerCache.scala | 23 ++- .../DeltaV2TableManagerImpl.scala | 3 +- .../UCManagedTableSnapshotManagerSuite.scala | 3 +- .../CachedSnapshotManagerSuite.scala | 12 +- 13 files changed, 243 insertions(+), 65 deletions(-) diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/ApplyV2ReadOptionsSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/ApplyV2ReadOptionsSuite.scala index f3bd3c10934..79871c7a2b4 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/ApplyV2ReadOptionsSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/ApplyV2ReadOptionsSuite.scala @@ -271,7 +271,9 @@ class ApplyV2ReadOptionsSuite extends DeltaSQLCommandTest { private def seedSchemaLogWithExtraColumn(tablePath: String, schemaLogPath: String): Unit = { val deltaLog = DeltaLog.forTable(spark, tablePath) val snapshotManager = - new PathBasedSnapshotManager(tablePath, new KernelContext(deltaLog.options, deltaLog.store)) + new PathBasedSnapshotManager( + tablePath, + new KernelContext(deltaLog.options, deltaLog.store)) val tableId = snapshotManager.loadLatestSnapshot.metadata.getId val trackingLog = DeltaSourceMetadataTrackingLog.create( spark, schemaLogPath, tableId, tablePath, parameters = Map.empty[String, String]) diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotSuite.scala index 60b1d904d53..2afdd68ed54 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotSuite.scala @@ -48,7 +48,8 @@ import org.apache.spark.sql.catalyst.catalog.{CatalogStorageFormat, CatalogTable */ class DeltaV2SnapshotSuite extends DeltaSQLCommandTest { - private lazy val kernelContext = new KernelContext(Map.empty, LogStore(spark)) + private lazy val kernelContext = + new KernelContext(Map.empty, LogStore(spark)) private def engine: Engine = kernelContext.getDefaultEngine() diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtilsSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtilsSuite.scala index 98d7041d336..f3f3cdb1301 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtilsSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtilsSuite.scala @@ -32,7 +32,8 @@ import io.delta.kernel.internal.SnapshotImpl class KernelSnapshotUtilsSuite extends DeltaSQLCommandTest { - private lazy val kernelContext = new KernelContext(Map.empty, LogStore(spark)) + private lazy val kernelContext = + new KernelContext(Map.empty, LogStore(spark)) private def engine: Engine = kernelContext.getDefaultEngine() diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/DeltaV2Logging.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/DeltaV2Logging.scala index 161848cb30b..41268f94b84 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/DeltaV2Logging.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/DeltaV2Logging.scala @@ -15,15 +15,77 @@ */ package org.apache.spark.sql.delta.v2 +import java.util.concurrent.TimeUnit import java.util.function.Supplier -import org.apache.spark.sql.delta.metering.DeltaLogging +import scala.util.control.NonFatal + +import com.databricks.spark.util.TagDefinition +import org.apache.spark.sql.delta.metering.{DeltaLogging, DeltaLoggingProvider} +import org.apache.hadoop.fs.Path /** * Delta V2 specialization of [[DeltaLogging]]. Frame-name suffixes passed here must be fixed * system-code literals; this trait supplies the shared `Delta` group and `v2.` prefix. */ private[v2] trait DeltaV2Logging extends DeltaLogging { + protected final def elapsedTimeMs(startedAtNs: Long): Long = + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAtNs) + + private val deltaV2OpTypePrefix = "delta.v2." + + private def deltaV2OpType(opType: String): String = { + if (opType.startsWith(deltaV2OpTypePrefix)) opType else deltaV2OpTypePrefix + opType + } + + protected final override def recordDeltaEvent( + provider: DeltaLoggingProvider, + opType: String, + tags: Map[TagDefinition, String], + data: AnyRef, + path: Option[Path]): Unit = { + super.recordDeltaEvent(provider, deltaV2OpType(opType), tags, data, path) + } + + /** + * Records a table-scoped event without requiring a DeltaLog-backed provider. Delta V2 must not + * depend on DeltaLog, so the path supplies the table identity through DeltaLogging's supported + * path-attribution fallback. + */ + protected final def recordDeltaEventForTablePath( + tablePath: => Path, + opType: String, + tags: Map[TagDefinition, String] = Map.empty, + data: => AnyRef = null): Unit = { + try { + recordDeltaEvent( + provider = null, + opType = opType, + tags = tags, + data = data, + path = Some(tablePath)) + } catch { + case NonFatal(loggingFailure) => + logWarning("Failed to record table-scoped Delta V2 event", loggingFailure) + } + } + + protected final override def recordDeltaOperationForTablePath[A]( + tablePath: String, + opType: String, + tags: Map[TagDefinition, String])( + thunk: => A): A = { + super.recordDeltaOperationForTablePath(tablePath, deltaV2OpType(opType), tags)(thunk) + } + + protected final override def recordDeltaOperation[A]( + provider: DeltaLoggingProvider, + opType: String, + tags: Map[TagDefinition, String])( + thunk: => A): A = { + super.recordDeltaOperation(provider, deltaV2OpType(opType), tags)(thunk) + } + private def deltaV2FrameName(nameSuffix: String): String = "v2." + nameSuffix protected final def recordFrameProfile[T]( diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotManager.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotManager.scala index b99b7ecc704..bf95092b410 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotManager.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2SnapshotManager.scala @@ -18,6 +18,8 @@ package org.apache.spark.sql.delta.v2.interop import java.util.Objects +import scala.util.control.NonFatal + import io.delta.kernel.CommitRange import io.delta.kernel.engine.Engine import io.delta.kernel.internal.DeltaHistoryManager @@ -27,6 +29,8 @@ import org.apache.spark.sql.delta.v2.interop.DeltaV2SnapshotManager.GetTableChan import org.apache.spark.sql.delta.v2.kernel.KernelContext import org.apache.spark.sql.delta.Snapshot +import org.apache.spark.sql.delta.v2.DeltaV2Logging +import org.apache.hadoop.fs.Path import org.apache.spark.annotation.Experimental @@ -148,7 +152,7 @@ trait DeltaV2SnapshotManager { } } -object DeltaV2SnapshotManager { +object DeltaV2SnapshotManager extends DeltaV2Logging { /** * Inputs for loading an inclusive range of table changes. @@ -187,6 +191,15 @@ object DeltaV2SnapshotManager { Objects.requireNonNull(kernelSnapshot, "kernelSnapshot is null") Objects.requireNonNull(kernelContext, "kernelContext is null") Objects.requireNonNull(tablePath, "tablePath is null") - new DeltaV2Snapshot(kernelSnapshot, kernelContext) + try { + new DeltaV2Snapshot(kernelSnapshot, kernelContext) + } catch { + case NonFatal(e) => + recordDeltaEventForTablePath( + tablePath = new Path(tablePath), + opType = "snapshot.wrap.failure", + data = Map("version" -> kernelSnapshot.getVersion)) + throw e + } } } diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtils.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtils.scala index 15dca61f711..e00633b9502 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtils.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/interop/KernelSnapshotUtils.scala @@ -26,6 +26,7 @@ import io.delta.kernel.internal.actions.{AddFile => KernelAddFile, DeletionVecto import org.apache.spark.sql.delta.actions.{AddFile, DeletionVectorDescriptor => V1DeletionVectorDescriptor} import org.apache.spark.sql.delta.implicits._ +import org.apache.spark.sql.delta.v2.DeltaV2Logging import org.apache.spark.sql.{Dataset, SparkSession} @@ -36,7 +37,7 @@ import org.apache.spark.sql.{Dataset, SparkSession} * This object does not create a SparkSession or Kernel Engine. The caller passes them in so the * caller controls which Spark context and Hadoop configuration are used. */ -private[delta] object KernelSnapshotUtils { +private[delta] object KernelSnapshotUtils extends DeltaV2Logging { /** * Reads the active files in the Kernel snapshot and returns them as V1 [[AddFile]] rows. @@ -49,7 +50,13 @@ private[delta] object KernelSnapshotUtils { kernelSnapshot: SnapshotImpl, spark: SparkSession, engine: Engine): Dataset[AddFile] = { - spark.createDataset(collectV1AddFiles(kernelSnapshot, engine)) + recordDeltaOperationForTablePath( + kernelSnapshot.getDataPath.toString, "scan.buildAllFiles") { + def buildTableState(): Dataset[AddFile] = { + spark.createDataset(collectV1AddFiles(kernelSnapshot, engine)) + } + buildTableState() + } } /** diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelContext.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelContext.scala index 691e65752d9..0725d59127a 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelContext.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelContext.scala @@ -31,12 +31,16 @@ import org.apache.spark.sql.SparkSession */ final class KernelContext( private[v2] val sessionInvariantFsOptions: Map[String, String], - private[v2] val logStore: LogStore) { + private[v2] val logStore: LogStore) +{ require(sessionInvariantFsOptions != null, "sessionInvariantFsOptions must not be null") require(logStore != null, "logStore must not be null") + // No DeltaLog is available; overlay table options on the active session configuration. + // scalastyle:off deltahadoopconfiguration private[v2] def materializeHadoopConf() = SparkSession.active.sessionState.newHadoopConfWithOptions(sessionInvariantFsOptions) + // scalastyle:on deltahadoopconfiguration private def createDefaultEngine(): KernelEngine = { val hadoopConf = materializeHadoopConf() @@ -51,7 +55,8 @@ final class KernelContext( } private[v2] object KernelContext { - def empty(logStore: LogStore): KernelContext = new KernelContext(Map.empty, logStore) + def empty(logStore: LogStore): KernelContext = + new KernelContext(Map.empty[String, String], logStore) def apply(sessionInvariantFsOptions: Map[String, String], logStore: LogStore): KernelContext = new KernelContext(sessionInvariantFsOptions, logStore) diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelEngineFactory.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelEngineFactory.scala index f9249d923cf..d5ebf930a39 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelEngineFactory.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/kernel/KernelEngineFactory.scala @@ -16,15 +16,18 @@ package org.apache.spark.sql.delta.v2.kernel +import org.apache.spark.sql.delta.v2.DeltaV2Logging import org.apache.hadoop.conf.Configuration import io.delta.kernel.defaults.engine.{DefaultEngine => KernelDefaultEngine} import io.delta.kernel.engine.{Engine => KernelEngine} /** Factory for creating the default Kernel [[KernelEngine]] used by the DSv2 connector. */ -object KernelEngineFactory { +object KernelEngineFactory extends DeltaV2Logging { /** Builds the backend-appropriate default engine. */ def createDefaultEngine(hadoopConf: Configuration): KernelEngine = { - KernelDefaultEngine.create(hadoopConf) + recordFrameProfile("kernelEngineFactory.createDefaultEngine") { + KernelDefaultEngine.create(hadoopConf) + } } } diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala index 7f448ee0e25..b625c5a36f8 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManager.scala @@ -95,13 +95,14 @@ private[tablemanager] class CachedSnapshotManager( timestampMillis: Long, canReturnLastCommit: Boolean, mustBeRecreatable: Boolean, - canReturnEarliestCommit: Boolean): KernelDeltaHistoryManager.Commit = - withUncachedSnapshotManager(Option(latestCatalogTable.get()))( - _.getActiveCommitAtTime( - timestampMillis, - canReturnLastCommit, - mustBeRecreatable, - canReturnEarliestCommit)) + canReturnEarliestCommit: Boolean): KernelDeltaHistoryManager.Commit = { + getActiveCommitAtTimeInternal( + timestampMillis, + canReturnLastCommit, + mustBeRecreatable, + canReturnEarliestCommit, + Option(latestCatalogTable.get())) + } override def getActiveCommitAtTime( timestampMillis: Long, @@ -110,20 +111,40 @@ private[tablemanager] class CachedSnapshotManager( canReturnEarliestCommit: Boolean, queryContext: DeltaV2QueryContext): KernelDeltaHistoryManager.Commit = { Objects.requireNonNull(queryContext, "queryContext is null") - withUncachedSnapshotManager(queryContext.catalogTableOpt)( - _.getActiveCommitAtTime( - timestampMillis, - canReturnLastCommit, - mustBeRecreatable, - canReturnEarliestCommit)) + getActiveCommitAtTimeInternal( + timestampMillis, + canReturnLastCommit, + mustBeRecreatable, + canReturnEarliestCommit, + queryContext.catalogTableOpt) + } + + private def getActiveCommitAtTimeInternal( + timestampMillis: Long, + canReturnLastCommit: Boolean, + mustBeRecreatable: Boolean, + canReturnEarliestCommit: Boolean, + catalogTableOpt: Option[CatalogTable]): KernelDeltaHistoryManager.Commit = { + recordDeltaOperationForTablePath(tablePath.toString, "snapshot.timeTravel") { + withUncachedSnapshotManager(catalogTableOpt)( + _.getActiveCommitAtTime( + timestampMillis, + canReturnLastCommit, + mustBeRecreatable, + canReturnEarliestCommit)) + } } override def checkVersionExists( version: Long, mustBeRecreatable: Boolean, - allowOutOfRange: Boolean): Unit = - withUncachedSnapshotManager(Option(latestCatalogTable.get()))( - _.checkVersionExists(version, mustBeRecreatable, allowOutOfRange)) + allowOutOfRange: Boolean): Unit = { + checkVersionExistsInternal( + version, + mustBeRecreatable, + allowOutOfRange, + Option(latestCatalogTable.get())) + } override def checkVersionExists( version: Long, @@ -131,23 +152,47 @@ private[tablemanager] class CachedSnapshotManager( allowOutOfRange: Boolean, queryContext: DeltaV2QueryContext): Unit = { Objects.requireNonNull(queryContext, "queryContext is null") - withUncachedSnapshotManager(queryContext.catalogTableOpt)( - _.checkVersionExists(version, mustBeRecreatable, allowOutOfRange)) + checkVersionExistsInternal( + version, + mustBeRecreatable, + allowOutOfRange, + queryContext.catalogTableOpt) + } + + private def checkVersionExistsInternal( + version: Long, + mustBeRecreatable: Boolean, + allowOutOfRange: Boolean, + catalogTableOpt: Option[CatalogTable]): Unit = { + recordFrameProfile("DeltaHistoryManager.checkVersionExists") { + recordDeltaOperationForTablePath(tablePath.toString, "snapshot.checkVersion") { + withUncachedSnapshotManager(catalogTableOpt)( + _.checkVersionExists(version, mustBeRecreatable, allowOutOfRange)) + } + } } override def getTableChanges( kernelEngine: KernelEngine, - params: GetTableChangesParam): KernelCommitRange = - withUncachedSnapshotManager(Option(latestCatalogTable.get()))( - _.getTableChanges(kernelEngine, params)) + params: GetTableChangesParam): KernelCommitRange = { + getTableChangesInternal(kernelEngine, params, Option(latestCatalogTable.get())) + } override def getTableChanges( kernelEngine: KernelEngine, params: GetTableChangesParam, queryContext: DeltaV2QueryContext): KernelCommitRange = { Objects.requireNonNull(queryContext, "queryContext is null") - withUncachedSnapshotManager(queryContext.catalogTableOpt)( - _.getTableChanges(kernelEngine, params)) + getTableChangesInternal(kernelEngine, params, queryContext.catalogTableOpt) + } + + private def getTableChangesInternal( + kernelEngine: KernelEngine, + params: GetTableChangesParam, + catalogTableOpt: Option[CatalogTable]): KernelCommitRange = { + recordDeltaOperationForTablePath(tablePath.toString, "snapshot.tableChanges") { + withUncachedSnapshotManager(catalogTableOpt)(_.getTableChanges(kernelEngine, params)) + } } // === Snapshot lifecycle =================================================== @@ -171,7 +216,9 @@ private[tablemanager] class CachedSnapshotManager( if (isFresh(current, requiredFreshAfter)) { current.snapshot } else { - rebuildAndInstallInternal(catalogTableOpt) + withSnapshotLoadOperation("snapshot.loadLatest") { + rebuildAndInstallInternal(catalogTableOpt) + } } } } @@ -225,35 +272,42 @@ private[tablemanager] class CachedSnapshotManager( if (current != null && version == current.snapshot.version) { return current.snapshot } - val refreshed = - if (isFresh(current, latestSnapshotFreshnessThreshold(), Some(version))) current.snapshot - else rebuildAndInstallInternal(catalogTableOpt) - // If latest still trails the requested version, attempt the exact load before rejecting it. - if (version > refreshed.version) { - val loaded = CachedSnapshot( - withUncachedSnapshotManager(catalogTableOpt)(_.loadSnapshotAt(version)), - validatedAtMs = -1L) - val previous = currentSnapshot - if (previous != null && previous.snapshot.metadata.id != loaded.snapshot.metadata.id) { - logWarning( - s"Table identity changed while loading snapshot at version $version: " + - s"previous=${previous.snapshot.metadata.id}, current=${loaded.snapshot.metadata.id}") - } - // An exact-version load proves this snapshot exists, but not that it is the latest. - currentSnapshot = loaded - retireSnapshotInternal(previous) - loaded.snapshot + if (isFresh(current, latestSnapshotFreshnessThreshold(), Some(version))) { + current.snapshot } else { - refreshed + withSnapshotLoadOperation("snapshot.loadVersion") { + val refreshed = + rebuildAndInstallInternal(catalogTableOpt) + // If latest still trails the requested version, attempt the exact load before + // rejecting it. + if (version > refreshed.version) { + val loaded = CachedSnapshot( + withUncachedSnapshotManager(catalogTableOpt)(_.loadSnapshotAt(version)), + validatedAtMs = -1L) + val previous = currentSnapshot + if (previous != null && previous.snapshot.metadata.id != loaded.snapshot.metadata.id) { + logWarning( + s"Table identity changed while loading snapshot at version $version: " + + s"previous=${previous.snapshot.metadata.id}, " + + s"current=${loaded.snapshot.metadata.id}") + } + // An exact-version load proves this snapshot exists, not that it is the latest. + currentSnapshot = loaded + retireSnapshotInternal(previous) + loaded.snapshot + } else { + refreshed + } + } } } if (version == upperBound.version) { return upperBound } // Historical snapshots are returned to the caller but never replace the cached latest snapshot. - val historicalSnapshot = withUncachedSnapshotManager(catalogTableOpt)( - _.loadSnapshotAt(version)) - historicalSnapshot + withSnapshotLoadOperation("snapshot.loadVersion") { + withUncachedSnapshotManager(catalogTableOpt)(_.loadSnapshotAt(version)) + } } // === Uncached loading ===================================================== @@ -267,6 +321,9 @@ private[tablemanager] class CachedSnapshotManager( catalogTableOpt)) } + private def withSnapshotLoadOperation[T](opType: String)(body: => T): T = + recordDeltaOperationForTablePath(tablePath.toString, opType)(body) + private def latestSnapshotFreshnessThreshold(): Long = { val now = System.currentTimeMillis() val stalenessLimit = SparkSession.active.sessionState.conf diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerCache.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerCache.scala index 330f15cbcbf..06b682a4350 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerCache.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerCache.scala @@ -54,7 +54,17 @@ private[tablemanager] class DeltaV2TableManagerCache( private val cache: Cache[CacheKey, DeltaV2TableManager] = { val listener: RemovalListener[CacheKey, DeltaV2TableManager] = notification => { val manager = notification.getValue - if (manager != null) manager.retire() + val key = notification.getKey + if (manager != null) { + val startedAtNs = System.nanoTime() + manager.retire() + recordDeltaEventForTablePath( + tablePath = key.path.getParent, + opType = "cache.evict", + data = Map( + "cause" -> notification.getCause.toString, + "elapsedMs" -> elapsedTimeMs(startedAtNs))) + } } CacheBuilder.newBuilder() .maximumSize(maxSize) @@ -74,7 +84,13 @@ private[tablemanager] class DeltaV2TableManagerCache( try { cache.get(key, () => { recordFrameProfile("tableManagerCache.createManager") { - managerFactory(key, initialCatalogTableOpt) + val createStartedAtNs = System.nanoTime() + val created = managerFactory(key, initialCatalogTableOpt) + recordDeltaEventForTablePath( + tablePath = key.path.getParent, + opType = "cache.create", + data = Map("elapsedMs" -> elapsedTimeMs(createStartedAtNs))) + created } }) } catch { @@ -82,6 +98,9 @@ private[tablemanager] class DeltaV2TableManagerCache( _: ExecutionError | _: ExecutionException) => val cause = Option(e.getCause).getOrElse(e) logWarning(log"Cache loader failed; rethrowing original cause", cause) + recordDeltaEventForTablePath( + tablePath = key.path.getParent, + opType = "cache.load.failure") throw cause } } diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImpl.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImpl.scala index 775213c375f..47eeb49e65a 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImpl.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImpl.scala @@ -66,7 +66,8 @@ private[tablemanager] class DeltaV2TableManagerImpl( /** Used to read and write physical log files and checkpoints. */ override private[v2] val logStore = createLogStore(SparkSession.active) - override private[v2] val kernelContext = KernelContext(sessionInvariantFsOptions, logStore) + override private[v2] val kernelContext = + KernelContext(sessionInvariantFsOptions, logStore) private val latestCatalogTable = new AtomicReference[CatalogTable](initialCatalogTableOpt.orNull) diff --git a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/snapshot/unitycatalog/UCManagedTableSnapshotManagerSuite.scala b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/snapshot/unitycatalog/UCManagedTableSnapshotManagerSuite.scala index e604c49a97f..e9d3b4913c4 100644 --- a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/snapshot/unitycatalog/UCManagedTableSnapshotManagerSuite.scala +++ b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/snapshot/unitycatalog/UCManagedTableSnapshotManagerSuite.scala @@ -42,7 +42,8 @@ class UCManagedTableSnapshotManagerSuite private val testUcToken = "test-token" private val testUcAuthConfig = Map("token" -> testUcToken).asJava - private def kernelContext = new KernelContext(Map.empty, LogStore(spark)) + private def kernelContext = + new KernelContext(Map.empty, LogStore(spark)) private def createManager( ucClient: InMemoryUCClient, diff --git a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala index 663f91b3c9c..d229aca7bd8 100644 --- a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala +++ b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/CachedSnapshotManagerSuite.scala @@ -95,10 +95,14 @@ class CachedSnapshotManagerSuite spark.range(numRows).write.format("delta").mode("append").save(dir.getCanonicalPath) } + private def createManager(dir: File): CachedSnapshotManager = + createManager( + dir, + KernelContext(Map.empty, LogStore.createLogStore(spark))) + private def createManager( dir: File, - kernelContext: KernelContext = KernelContext(Map.empty, LogStore.createLogStore(spark)) - ): CachedSnapshotManager = { + kernelContext: KernelContext): CachedSnapshotManager = { new CachedSnapshotManager( new Path(dir.getCanonicalPath), kernelContext, @@ -387,7 +391,9 @@ class CachedSnapshotManagerSuite SparkSession.setActiveSession(constructionSession) setRecordingMarkers(constructionSession, "construction") val kernelContext = - KernelContext(invariantOptions, LogStore.createLogStore(constructionSession)) + KernelContext( + invariantOptions, + LogStore.createLogStore(constructionSession)) manager = createManager(dir, kernelContext) SparkSession.setActiveSession(firstOperationSession) From 01c3d5a34c41534c13cd3b22f04154696aee1c01 Mon Sep 17 00:00:00 2001 From: hari <39596845+hariuserx@users.noreply.github.com> Date: Mon, 16 Nov 2026 21:31:37 -0800 Subject: [PATCH 16/44] [Spark] Use one helper to get the DeltaV2Scan in the V2 scan Java tests (#8182) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description The V2 scan Java tests cast the built scan to DeltaV2Scan in about 90 places. A failed cast gives a ClassCastException that does not say which scan the builder built. Add DeltaV2TestBase.asDeltaV2Scan, which checks the type and fails with the class name of the scan, and use it in DeltaV2ScanTest, DeltaV2ScanBuilderTest, and DeltaV2BatchTest. The test assertions do not change. ## How was this patch tested? Existing tests ## Does this PR introduce _any_ user-facing changes? No Signed-off-by: Hari Kishore Chaparala Co-authored-by: Isaac --- .../spark/sql/delta/v2/DeltaV2TestBase.java | 16 ++ .../sql/delta/v2/read/DeltaV2BatchTest.java | 8 +- .../delta/v2/read/DeltaV2ScanBuilderTest.java | 14 +- .../sql/delta/v2/read/DeltaV2ScanTest.java | 164 +++++++++--------- 4 files changed, 109 insertions(+), 93 deletions(-) diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/DeltaV2TestBase.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/DeltaV2TestBase.java index 7db0c2d7791..dac43fa9d2e 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/DeltaV2TestBase.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/DeltaV2TestBase.java @@ -26,8 +26,10 @@ import org.apache.spark.sql.catalyst.expressions.AttributeReference; import org.apache.spark.sql.catalyst.expressions.Expression; import org.apache.spark.sql.catalyst.expressions.Literal; +import org.apache.spark.sql.connector.read.Scan; import org.apache.spark.sql.delta.storage.LogStore; import org.apache.spark.sql.delta.v2.kernel.KernelContext; +import org.apache.spark.sql.delta.v2.read.DeltaV2Scan; import org.apache.spark.sql.delta.v2.read.DeltaV2ScanBuilder; import org.apache.spark.sql.delta.v2.utils.ScalaUtils; import org.apache.spark.sql.sources.And; @@ -215,6 +217,20 @@ protected static void pushFilters(DeltaV2ScanBuilder builder, Filter... filters) builder.pushFilters(expressionSeq); } + /** + * Returns the Delta V2 scan that a scan builder built. Example: {@code + * asDeltaV2Scan(builder.build()).getPushedLimit()}. + * + * @param scan the scan that a Delta V2 scan builder built + * @return the {@link DeltaV2Scan} that selects the files of the read + */ + protected static DeltaV2Scan asDeltaV2Scan(Scan scan) { + if (!(scan instanceof DeltaV2Scan)) { + throw new AssertionError("expected a DeltaV2Scan, got " + scan.getClass().getName()); + } + return (DeltaV2Scan) scan; + } + protected static Expression toCatalystFilter(DeltaV2ScanBuilder builder, Filter filter) { // Concatenate data + partition fields via add() rather than StructType.merge: of the two merge // overloads, one is not available in every build and the other is private[sql], so neither is diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2BatchTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2BatchTest.java index f01756cb76d..d6ccce66131 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2BatchTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2BatchTest.java @@ -83,13 +83,13 @@ public void testEqualsAndHashCode(String description, Filter[] filters1, Filter[ if (filters1.length > 0) { pushFilters(builder1, filters1); } - Batch batch1 = ((DeltaV2Scan) builder1.build()).toBatch(); + Batch batch1 = asDeltaV2Scan(builder1.build()).toBatch(); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); if (filters2.length > 0) { pushFilters(builder2, filters2); } - Batch batch2 = ((DeltaV2Scan) builder2.build()).toBatch(); + Batch batch2 = asDeltaV2Scan(builder2.build()).toBatch(); assertEquals(batch1, batch2); assertEquals(batch1.hashCode(), batch2.hashCode()); @@ -98,11 +98,11 @@ public void testEqualsAndHashCode(String description, Filter[] filters1, Filter[ @Test public void testEqualsWithDifferentPushedFilters() { DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - Batch batch1 = ((DeltaV2Scan) builder1.build()).toBatch(); + Batch batch1 = asDeltaV2Scan(builder1.build()).toBatch(); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder2, new EqualTo("city", "hz")); - Batch batch2 = ((DeltaV2Scan) builder2.build()).toBatch(); + Batch batch2 = asDeltaV2Scan(builder2.build()).toBatch(); assertNotEquals(batch1, batch2); assertNotEquals(batch1.hashCode(), batch2.hashCode()); diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java index 9b0f84a6875..2de0114f051 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java @@ -97,7 +97,7 @@ public void testBuild_returnsScanWithExpectedSchema(@TempDir File tempDir) { builder.pruneColumns(expectedSparkSchema); Scan scan = builder.build(); - assertTrue(scan instanceof DeltaV2Scan); + assertNotNull(asDeltaV2Scan(scan)); assertEquals(expectedSparkSchema, scan.readSchema()); } @@ -589,14 +589,14 @@ public void testPushLimit_isPartiallyPushedIsTrue(@TempDir File tempDir) { public void testPushLimit_propagatedToScan(@TempDir File tempDir) { DeltaV2ScanBuilder builder = newFilterScanBuilder(tempDir); builder.pushLimit(42); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals(Option.apply(42), scan.getPushedLimit()); } @Test public void testPushLimit_absentByDefault(@TempDir File tempDir) { DeltaV2ScanBuilder builder = newFilterScanBuilder(tempDir); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals(Option.empty(), scan.getPushedLimit()); } @@ -606,7 +606,7 @@ public void testPushLimit_lastValueWins(@TempDir File tempDir) { builder.pushLimit(10); builder.pushLimit(20); assertEquals(OptionalInt.of(20), builder.getPushedLimit()); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals(Option.apply(20), scan.getPushedLimit()); } @@ -625,7 +625,7 @@ public void testPushLimit_clearedWhenDataFiltersPresent(@TempDir File tempDir) { // A data filter (on a non-partition column) becomes a post-scan residual. pushFilters(builder, new GreaterThan("id", 10)); builder.pushLimit(10); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Option.empty(), scan.getPushedLimit(), @@ -642,7 +642,7 @@ public void testPushLimit_remainsClearedAfterLaterEmptyPushFilters(@TempDir File builder.pushFilters( scala.jdk.javaapi.CollectionConverters.asScala(java.util.List.of()).toList()); assertTrue(builder.pushLimit(10)); - assertEquals(Option.empty(), ((DeltaV2Scan) builder.build()).getPushedLimit()); + assertEquals(Option.empty(), asDeltaV2Scan(builder.build()).getPushedLimit()); } @Test @@ -654,7 +654,7 @@ public void testPushLimit_keptWhenPartitionFilterLeavesNoResidual(@TempDir File pushFilters(builder, new EqualTo("dep_id", 1)); builder.pushLimit(10); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Option.apply(10), scan.getPushedLimit(), diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanTest.java index adb85e325c3..a06df98f193 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanTest.java @@ -133,7 +133,7 @@ public static void setupPartitionedTable(@TempDir File tempDir) { public void testColumnarSupportModeReturnsSupported() { // Table schema uses simple types (INT, STRING) which are batch-read-compatible DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Scan.ColumnarSupportMode.SUPPORTED, @@ -146,7 +146,7 @@ public void testColumnarSupportModeDoesNotTriggerPlanning() throws Exception { // Calling columnarSupportMode() must NOT trigger file planning (the whole point of the // override is to avoid the early planInputPartitions() call that PARTITION_DEFINED causes). DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // Call columnarSupportMode before any planning scan.columnarSupportMode(); @@ -184,7 +184,7 @@ public void testColumnarSupportModeWithUnsupportedSchema(@TempDir File tempDir) path, options); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) mapTable.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Scan.ColumnarSupportMode.UNSUPPORTED, @@ -204,7 +204,7 @@ public void testColumnarSupportModeWithVectorizedReaderDisabled() throws Excepti "false", () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Scan.ColumnarSupportMode.UNSUPPORTED, @@ -225,7 +225,7 @@ public void testColumnarSupportModeWithMetadataColumnPruned() { .add("part", DataTypes.IntegerType); builder.pruneColumns(prunedSchema); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( Scan.ColumnarSupportMode.UNSUPPORTED, @@ -258,7 +258,7 @@ public void testColumnarSupportModeWithDeletionVectors(@TempDir File tempDir) th dvPath, options); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) dvTable.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // DV-enabled table with simple types should still return SUPPORTED because the // DV column (ByteType) is batch-compatible @@ -277,7 +277,7 @@ public void testColumnarSupportModeWithDeletionVectors(@TempDir File tempDir) th @Test public void testGetDataSchemaPartitionSchemaReadDataSchemaOptionsConfiguration() { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // Table schema: (part INT, date STRING, city STRING, name STRING, cnt INT) // Partition columns: (date STRING, city STRING, part INT) @@ -328,7 +328,7 @@ public void testGetDataSchemaPartitionSchemaReadDataSchemaOptionsConfiguration() @Test public void testGetTablePathReturnsTablePath() { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); String retrievedPath = scan.getTablePath(); assertNotNull(retrievedPath, "getTablePath should not return null"); @@ -350,7 +350,7 @@ public void testGetConfigurationWithHadoopOptions() { CaseInsensitiveStringMap optionsWithHadoopMap = new CaseInsensitiveStringMap(optionsWithHadoop); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(optionsWithHadoopMap); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); Configuration configuration = scan.getConfiguration(); assertEquals( @@ -375,7 +375,7 @@ public void testGetReadDataSchemaWithColumnPruning() { .add("part", DataTypes.IntegerType); builder.pruneColumns(prunedSchema); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); StructType dataSchema = scan.getDataSchema(); StructType readDataSchema = scan.getReadDataSchema(); @@ -517,7 +517,7 @@ protected static void checkSupportsRuntimeFilters( ScanBuilder newBuilder = table.newScanBuilder(scanOptions); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) newBuilder; Scan scan = builder.build(); - DeltaV2Scan deltaV2Scan = (DeltaV2Scan) scan; + DeltaV2Scan deltaV2Scan = asDeltaV2Scan(scan); List beforeDppFiles = getPartitionedFiles(deltaV2Scan); // make a copy for comparison after DPP @@ -571,7 +571,7 @@ private static List partitionedFilePaths(List files) { @Test public void testSelectedFilesTracksPlannedAndRuntimeFilteredFiles() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); List plannedFiles = getPartitionedFiles(scan); List selectedFiles = @@ -600,7 +600,7 @@ public void testSelectedFilesTracksPlannedAndRuntimeFilteredFiles() throws Excep @Test public void testPlannedSnapshotTriggersPlanningAndReturnsSameSnapshot() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse(getPlanned(scan), "build() should leave file planning lazy"); Snapshot plannedSnapshot = scan.preparedScan().scannedSnapshot(); @@ -675,7 +675,7 @@ public void testNumRowsEmptyWhenStatsDisabled() throws Exception { "false", () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse( isRowCountKnown(scan), @@ -695,7 +695,7 @@ public void testPathStatisticsDoNotReportPerFileNumRows() throws Exception { "true", () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse( isRowCountKnown(scan), @@ -715,7 +715,7 @@ public void testNumRowsAfterRuntimeFiltering() throws Exception { "true", () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); scan.toBatch(); assertEquals(5L, getTotalRows(scan), "5 rows before filtering"); @@ -741,7 +741,7 @@ public void testNumRowsZeroAfterFilteringOutAllFiles() throws Exception { "true", () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); scan.filter(new Predicate[] {negativeCityPredicate}); // city=zz doesn't exist @@ -787,7 +787,7 @@ public void testNumRowsUnknownWhenSomeFilesLackStats(@TempDir File testDir) thro () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) mixedStatsTable.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse( isRowCountKnown(scan), "rowCountKnown should be false when some files lack stats"); @@ -810,7 +810,7 @@ public void testReadSchema_cdcRead_returnsTableSchemaWithCDCColumns() { CaseInsensitiveStringMap cdcOptionsMap = new CaseInsensitiveStringMap(cdcOptions); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(cdcOptionsMap); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); StructType schema = scan.readSchema(); @@ -836,7 +836,7 @@ public void testReadSchema_cdcRead_returnsTableSchemaWithCDCColumns() { public void testReadSchema_nonCdcRead_returnsDataAndPartitionSchema() { // Without readChangeFeed, readSchema() returns readDataSchema + partitionSchema. DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); StructType schema = scan.readSchema(); @@ -870,7 +870,7 @@ public void testPruneColumns_cdcRead_filtersCDCColumns() { .add("date", DataTypes.StringType); builder.pruneColumns(requiredSchema); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // readDataSchema reflects pruning: only "name" remains (cnt dropped, partition + CDC filtered) StructType readDataSchema = scan.getReadDataSchema(); @@ -895,7 +895,7 @@ public void testCdcRead_toBatchRejectsCDCOptions() { CaseInsensitiveStringMap cdcOptionsMap = new CaseInsensitiveStringMap(cdcOptions); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(cdcOptionsMap); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // Sanity: scan still advertises the CDC schema (this is needed for the streaming path). StructType advertised = scan.readSchema(); @@ -916,7 +916,7 @@ public void testCdcRead_toBatchRejectsLegacyCDCOption() { CaseInsensitiveStringMap cdcOptionsMap = new CaseInsensitiveStringMap(cdcOptions); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(cdcOptionsMap); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals(8, scan.readSchema().fields().length); UnsupportedOperationException e = @@ -942,7 +942,7 @@ public void testCdcRead_falseDoesNotAdvertiseCDCColumns() { CaseInsensitiveStringMap nonCdcOptionsMap = new CaseInsensitiveStringMap(nonCdcOptions); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(nonCdcOptionsMap); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); StructType schema = scan.readSchema(); assertThrows(IllegalArgumentException.class, () -> schema.fieldIndex("_change_type")); @@ -957,10 +957,10 @@ public void testCdcRead_falseDoesNotAdvertiseCDCColumns() { public void testEqualsAndHashCode() { // Create two scans from the same table with same options DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // Same table, same options should be equal assertEquals(scan1, scan2); @@ -970,13 +970,13 @@ public void testEqualsAndHashCode() { @Test public void testEqualsWithDifferentOptions() { DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); Map differentOptions = new HashMap<>(); differentOptions.put("customOption", "value"); CaseInsensitiveStringMap optionsMap = new CaseInsensitiveStringMap(differentOptions); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(optionsMap); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // Different options should not be equal and hashCodes should differ assertNotEquals(scan1, scan2); @@ -985,8 +985,8 @@ public void testEqualsWithDifferentOptions() { @Test public void testEqualsWithDifferentOriginalQueryContext() throws Exception { - DeltaV2Scan scan1 = (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); - DeltaV2Scan scan2 = (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + DeltaV2Scan scan1 = asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); + DeltaV2Scan scan2 = asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); assertEquals(scan1, scan2); CatalogTable catalogTable = @@ -1007,7 +1007,7 @@ public void testToMicroBatchStreamPassesOriginalQueryContext() throws Exception // A path-backed scan carries a present query context with no catalog metadata. DeltaV2Scan pathScan = - (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(streamingOptions)).build(); + asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(streamingOptions)).build()); assertStreamUsesOriginalQueryContext(pathScan, tablePath + "/path-checkpoint", false); // A catalog-backed scan must retain its original query context through the same execution seam. @@ -1019,8 +1019,8 @@ public void testToMicroBatchStreamPassesOriginalQueryContext() throws Exception catalogTable, Collections.emptyMap()); DeltaV2Scan catalogScan = - (DeltaV2Scan) - ((DeltaV2ScanBuilder) catalogBackedTable.newScanBuilder(streamingOptions)).build(); + asDeltaV2Scan( + ((DeltaV2ScanBuilder) catalogBackedTable.newScanBuilder(streamingOptions)).build()); assertStreamUsesOriginalQueryContext(catalogScan, tablePath + "/catalog-checkpoint", true); } @@ -1066,11 +1066,11 @@ public void testEqualsWithSameFilters() { // Both scans with equivalent filters created separately (not same instance) DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder1, new org.apache.spark.sql.sources.EqualTo("city", "hz")); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder2, new org.apache.spark.sql.sources.EqualTo("city", "hz")); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // Same options and equivalent filters should be equal assertEquals(scan1, scan2); @@ -1081,12 +1081,12 @@ public void testEqualsWithSameFilters() { public void testEqualsWithDifferentFilters() { // Scan without filters DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); // Scan with filters pushed DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder2, new org.apache.spark.sql.sources.EqualTo("city", "hz")); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // Same options but different filters should not be equal and hashCodes should differ assertNotEquals(scan1, scan2); @@ -1102,11 +1102,11 @@ public void testEqualsWithPushedFiltersInDifferentOrder() { DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder1, new org.apache.spark.sql.sources.Filter[] {cityEq, dateEq}); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder2, new org.apache.spark.sql.sources.Filter[] {dateEq, cityEq}); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); assertEquals(scan1, scan2); assertEquals(scan1.hashCode(), scan2.hashCode()); @@ -1125,11 +1125,11 @@ public void testEqualsWithDataFiltersInDifferentOrder() throws Exception { DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder1, new org.apache.spark.sql.sources.Filter[] {nameEq, cntGt}); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder2, new org.apache.spark.sql.sources.Filter[] {cntGt, nameEq}); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // Sanity check that dataFilters is actually populated, otherwise this test would trivially // pass without exercising the dataFiltersSet path it's intended to cover. @@ -1147,7 +1147,7 @@ public void testEqualsWithDataFiltersInDifferentOrder() throws Exception { @Test public void testEstimatedSizeMatchesStatistics() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); long estimatedSizeFromStats = scan.estimateStatistics().sizeInBytes().getAsLong(); long estimatedSizeFromSizeOnlyApi = scan.estimateSizeInBytes().getAsLong(); @@ -1158,7 +1158,7 @@ public void testEstimatedSizeMatchesStatistics() throws Exception { @Test public void testUnfilteredOrdinaryStatisticsDoNotTriggerFilePlanning() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); int[] supplierCalls = instrumentDeltaScanSupplier(scan); OptionalLong sizeOnly = scan.estimateSizeInBytes(); @@ -1183,7 +1183,7 @@ public void testUnfilteredOrdinaryStatisticsDoNotTriggerFilePlanning() throws Ex public void testFilteredOrdinaryStatisticsPlanFilesOnce() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); pushFilters(builder, new org.apache.spark.sql.sources.EqualTo("city", "hz")); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); int[] supplierCalls = instrumentDeltaScanSupplier(scan); OptionalLong sizeOnly = scan.estimateSizeInBytes(); @@ -1217,7 +1217,7 @@ public void testMissingChecksumFallsBackToFilePlanning(@TempDir File tempDir) th DeltaV2Table tableWithoutChecksum = new DeltaV2Table(id, path); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) tableWithoutChecksum.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); int[] supplierCalls = instrumentDeltaScanSupplier(scan); OptionalLong sizeOnly = scan.estimateSizeInBytes(); @@ -1273,7 +1273,7 @@ public void testEstimateSizeInBytesUsesCheapFileSizePath() throws Exception { () -> { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); builder.pruneColumns(new StructType().add("name", DataTypes.StringType)); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); long sizeInBytes = scan.estimateSizeInBytes().getAsLong(); assertFalse(getPlanned(scan), "size estimation must not plan Delta files"); @@ -1287,7 +1287,7 @@ public void testEstimateSizeInBytesUsesCheapFileSizePath() throws Exception { @Test public void testStatisticsRequireSparkPostPushdownFilterAdjustment() { - DeltaV2Scan scan = (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + DeltaV2Scan scan = asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); assertFalse(scan.reflectsFullyPushedDownFilters()); } @@ -1295,7 +1295,7 @@ public void testStatisticsRequireSparkPostPushdownFilterAdjustment() { public void testEstimatedSizeZeroAfterFilteringOutAllFiles() throws Exception { // Test that filtering out all files results in zero for both sizes DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // Apply filter that matches nothing scan.filter(new Predicate[] {negativeCityPredicate}); // city=zz doesn't exist @@ -1320,9 +1320,9 @@ public void testEstimatedSizeZeroAfterFilteringOutAllFiles() throws Exception { public void testEqualsAndHashCodeWithSameRuntimeFilter() { // Same filter applied to both scans (same instance) DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate}); scan2.filter(new Predicate[] {cityPredicate}); @@ -1335,9 +1335,9 @@ public void testEqualsAndHashCodeWithSameRuntimeFilter() { public void testEqualsAndHashCodeWithEquivalentRuntimeFilters() { // Equivalent filters (different instances) DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate}); @@ -1357,9 +1357,9 @@ public void testEqualsAndHashCodeWithEquivalentRuntimeFilters() { public void testEqualsAndHashCodeWithMultipleRuntimeFiltersInSameOrder() { // Multiple filters in same order DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate, datePredicate}); scan2.filter(new Predicate[] {cityPredicate, datePredicate}); @@ -1372,9 +1372,9 @@ public void testEqualsAndHashCodeWithMultipleRuntimeFiltersInSameOrder() { public void testEqualsAndHashCodeWithIdempotentRuntimeFilters() { // Filter idempotency - applying same filter once vs twice DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate}); scan2.filter(new Predicate[] {cityPredicate}); @@ -1388,9 +1388,9 @@ public void testEqualsAndHashCodeWithIdempotentRuntimeFilters() { public void testEqualsAndHashCodeWithSeparateRuntimeFilterCalls() { // Multiple separate filter() calls vs single call with multiple filters DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate}); scan1.filter(new Predicate[] {datePredicate}); @@ -1404,9 +1404,9 @@ public void testEqualsAndHashCodeWithSeparateRuntimeFilterCalls() { public void testEqualsAndHashCodeWithRuntimeFiltersInDifferentOrder() { // Same filters in different order (order-independent) DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate, datePredicate}); scan2.filter(new Predicate[] {datePredicate, cityPredicate}); @@ -1420,9 +1420,9 @@ public void testEqualsAndHashCodeWithNonPartitionColumnRuntimeFilters() { // Non-partition column predicates should not affect equality // Only partition column predicates should be tracked DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); // cityPredicate is on partition column, dataPredicate is on non-partition column (cnt) scan1.filter(new Predicate[] {cityPredicate}); @@ -1437,9 +1437,9 @@ public void testEqualsAndHashCodeWithNonPartitionColumnRuntimeFilters() { public void testNotEqualsWithDifferentRuntimeFilters() { // Different filters DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan1.filter(new Predicate[] {cityPredicate}); scan2.filter(new Predicate[] {datePredicate}); @@ -1452,9 +1452,9 @@ public void testNotEqualsWithDifferentRuntimeFilters() { public void testNotEqualsWithAndWithoutRuntimeFilter() { // One with filter, one without DeltaV2ScanBuilder builder1 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan1 = (DeltaV2Scan) builder1.build(); + DeltaV2Scan scan1 = asDeltaV2Scan(builder1.build()); DeltaV2ScanBuilder builder2 = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan2 = (DeltaV2Scan) builder2.build(); + DeltaV2Scan scan2 = asDeltaV2Scan(builder2.build()); scan2.filter(new Predicate[] {cityPredicate}); @@ -1513,7 +1513,7 @@ public void testEstimateStatisticsWithCatalogStats(@TempDir File tempDir) throws DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); Statistics stats = scan.estimateStatistics(); // Catalog rows and columns are returned without an explicit size so Spark can derive a @@ -1558,7 +1558,7 @@ public void testCatalogNumRowsPreferredForFullStatistics(@TempDir File tempDir) DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); Statistics stats = scan.estimateStatistics(); assertTrue(stats.numRows().isPresent(), "numRows should be present"); @@ -1583,7 +1583,7 @@ public void testEstimateStatisticsWithoutCatalogStats(@TempDir File tempDir) thr DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); Statistics stats = scan.estimateStatistics(); assertFalse( @@ -1644,7 +1644,7 @@ public void testEstimateStatisticsWithPartitionedTableAndCatalogStats(@TempDir F DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); Statistics stats = scan.estimateStatistics(); assertTrue(stats.numRows().isPresent(), "numRows should be present"); @@ -1704,7 +1704,7 @@ public void testSizeOnlyEstimateDoesNotUseCatalogColumnStats(@TempDir File tempD StructType prunedSchema = new StructType().add("name", DataTypes.StringType); builder.pruneColumns(prunedSchema); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse(getPlanned(scan)); assertEquals(OptionalLong.of(1024L), scan.estimateSizeInBytes()); assertFalse(getPlanned(scan), "catalog size lookup should not plan Delta files"); @@ -1746,7 +1746,7 @@ public void testEstimateStatisticsWithCatalogStats_noNumRows(@TempDir File tempD DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse(getPlanned(scan)); assertEquals( @@ -1787,7 +1787,7 @@ private static scala.collection.immutable.Map buildCo public void testLimitPushdown_descriptionIncludesLimit() { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); builder.pushLimit(10); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertTrue( scan.description().contains("PushedLimit: 10"), "description should include the pushed limit"); @@ -1796,7 +1796,7 @@ public void testLimitPushdown_descriptionIncludesLimit() { @Test public void testLimitPushdown_descriptionOmitsLimitWhenAbsent() { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse( scan.description().contains("PushedLimit"), "description should not mention PushedLimit when no limit is pushed"); @@ -1821,7 +1821,7 @@ public void testLimitPushdown_notEqualWithDifferentLimit() { @Test public void testLimitPushdown_notEqualWithAndWithoutLimit() { DeltaV2Scan withoutLimit = - (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); DeltaV2Scan withLimit = buildScanWithLimit(10); assertNotEquals(withoutLimit, withLimit); assertNotEquals(withoutLimit.hashCode(), withLimit.hashCode()); @@ -1830,7 +1830,7 @@ public void testLimitPushdown_notEqualWithAndWithoutLimit() { @Test public void testLimitPushdown_noLimitPlansAllFiles() throws Exception { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); // The shared partitioned test table has 5 single-row files. assertEquals( 5, getPartitionedFiles(scan).size(), "all files should be planned without a limit"); @@ -1852,7 +1852,7 @@ public void testLimitPushdown_prunesFilesForSmallLimit() throws Exception { assertEquals(1, files.size(), "LIMIT 1 over single-row files should plan exactly one file"); DeltaV2Scan unlimited = - (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); assertTrue( getTotalBytes(scan) <= getTotalBytes(unlimited), "planned bytes with a limit should not exceed the full-scan bytes"); @@ -1862,7 +1862,7 @@ public void testLimitPushdown_prunesFilesForSmallLimit() throws Exception { public void testLimitPushdown_getterReflectsBuilder() { assertEquals(Option.apply(7), buildScanWithLimit(7).getPushedLimit()); DeltaV2Scan noLimit = - (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); assertEquals(Option.empty(), noLimit.getPushedLimit()); } @@ -1896,7 +1896,7 @@ public void testLimitPushdown_limit0ReportsZeroNumRowsNotStaleCatalog(@TempDir F (DeltaV2ScanBuilder) sparkTable.newScanBuilder(new CaseInsensitiveStringMap(new HashMap<>())); builder.pushLimit(0); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertFalse(getPlanned(scan), "LIMIT 0 statistics should not plan Delta files"); Statistics stats = scan.estimateStatistics(); @@ -1924,7 +1924,7 @@ public void testLimitPushdown_numRowsRemainsInternalUnderPlanStats() throws Exce () -> { // Without a limit, retaining numRecords does not populate an aggregate row count. DeltaV2Scan noLimit = - (DeltaV2Scan) ((DeltaV2ScanBuilder) table.newScanBuilder(options)).build(); + asDeltaV2Scan(((DeltaV2ScanBuilder) table.newScanBuilder(options)).build()); assertFalse(isRowCountKnown(noLimit), "missing aggregate row count should stay unknown"); assertFalse(noLimit.estimateStatistics().numRows().isPresent()); @@ -2007,7 +2007,7 @@ public void testLimitPushdown_missingNumRecordsPlansAllFiles(@TempDir File tempD Identifier.of(new String[] {"spark_catalog", "default"}, tblName), path, options); DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) tableWithoutStats.newScanBuilder(options); assertTrue(builder.pushLimit(1)); - DeltaV2Scan scan = (DeltaV2Scan) builder.build(); + DeltaV2Scan scan = asDeltaV2Scan(builder.build()); assertEquals( 2, @@ -2021,6 +2021,6 @@ public void testLimitPushdown_missingNumRecordsPlansAllFiles(@TempDir File tempD private DeltaV2Scan buildScanWithLimit(int limit) { DeltaV2ScanBuilder builder = (DeltaV2ScanBuilder) table.newScanBuilder(options); builder.pushLimit(limit); - return (DeltaV2Scan) builder.build(); + return asDeltaV2Scan(builder.build()); } } From 638f6dba4994fc01e025a5e3a8fec6cbf90ce911 Mon Sep 17 00:00:00 2001 From: Zikang Han Date: Mon, 16 Nov 2026 21:52:30 -0800 Subject: [PATCH 17/44] [Spark] Share checkNonAdditiveSchemaChanges between DeltaSource and DeltaV2MicroBatchStream (#8187) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description This PR starts to share the offset logic of the DSv1 streaming source `DeltaSource` with the DSv2 streaming source `DeltaV2MicroBatchStream`. Each PR moves one `DeltaSource` method, unchanged, into a shared trait, and deletes the `DeltaV2MicroBatchStream` copy. This PR adds the trait `DeltaSourceOffsetLogic`, which both sources mix in, and moves `checkNonAdditiveSchemaChanges` into it. `DeltaV2MicroBatchStream` now also runs the `assert(!trackingMetadataChange)` check that `DeltaSource` has. Every `DeltaV2MicroBatchStream` caller already skips the check while it tracks metadata. ## How was this patch tested? Existing tests. No test file changes. ## Does this PR introduce _any_ user-facing changes? No. --- .../spark/sql/delta/sources/DeltaSource.scala | 56 +---------- .../DeltaSourceMetadataEvolutionSupport.scala | 3 +- .../sources/DeltaSourceOffsetLogic.scala | 95 +++++++++++++++++++ .../v2/read/DeltaV2MicroBatchStream.scala | 49 +++------- 4 files changed, 114 insertions(+), 89 deletions(-) create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceOffsetLogic.scala diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala index 07d9f6fbf6b..a4e08e77ad7 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSource.scala @@ -112,13 +112,14 @@ private[delta] case class IndexedFile( trait DeltaSourceBase extends Source with SupportsAdmissionControl with SupportsTriggerAvailableNow - with DeltaLogging { self: DeltaSource => + with DeltaLogging + with DeltaSourceOffsetLogic { self: DeltaSource => /** * Configuration options for handling schema changes behavior. Controls unsafe operations like * column mapping changes, partition column changes, nullability changes, and type widening. */ - protected lazy val schemaReadOptions: DeltaStreamUtils.SchemaReadOptions = { + override protected lazy val schemaReadOptions: DeltaStreamUtils.SchemaReadOptions = { val schemaReadOptions = DeltaStreamUtils.SchemaReadOptions.fromSparkSession( spark = spark, isStreamingFromColumnMappingTable = @@ -656,55 +657,6 @@ trait DeltaSourceBase extends Source } } } - - /** - * Checks for non-additive schema changes (column renames, drops, type widening) and blocks - * the stream by throwing an exception if detected. - * - * Blocks when type widening tracking is enabled and widening changes exist, or when column - * mapping changes (rename/drop) are detected, unless `allowUnsafeStreamingReadOnColumnMapping - * SchemaChanges` is enabled. Upon blocking, the error requests the user to provide a schema - * tracking location to enable schema tracking. On restart, users must acknowledge changes via - * reader options or SQL confs. - * See [[DeltaSourceMetadataEvolutionSupport.validateIfSchemaChangeCanBeUnblocked]]. - * - * Note: Should not be called when schema tracking is active (trackingMetadataChange = true). - * - * @param oldMetadata Previous metadata (typically from stream initialization) - * @param newMetadata New metadata with potential schema changes - * @param validatedDuringStreamStart Whether validating during stream start vs. execution, - * which affects the error message. - * @throws DeltaAnalysisException if non-additive schema changes require blocking - */ - private def checkNonAdditiveSchemaChanges( - oldMetadata: Metadata, - newMetadata: Metadata, - validatedDuringStreamStart: Boolean): Unit = { - val shouldTrackSchema: Boolean = - if (schemaReadOptions.typeWideningEnabled && - schemaReadOptions.enableSchemaTrackingForTypeWidening && - TypeWidening.containsWideningTypeChanges(oldMetadata.schema, newMetadata.schema)) { - // If schema tracking is enabled for type widening, we will detect widening type changes and - // block the stream until the user sets `allowSourceColumnTypeChange` - similar to handling - // DROP/RENAME for column mapping. - true - } else if (schemaReadOptions.allowUnsafeStreamingReadOnColumnMappingSchemaChanges) { - false - } else { - // Column mapping schema changes - assert(!trackingMetadataChange, "should not check schema change while tracking it") - !DeltaColumnMapping.hasNoColumnMappingSchemaChanges(newMetadata, oldMetadata, - schemaReadOptions.allowUnsafeStreamingReadOnPartitionColumnChanges) - } - - if (shouldTrackSchema) { - throw DeltaErrors.blockStreamingReadsWithIncompatibleNonAdditiveSchemaChanges( - spark, - oldMetadata.schema, - newMetadata.schema, - detectedDuringStreaming = !validatedDuringStreamStart) - } - } } /** @@ -718,7 +670,7 @@ trait DeltaSourceBase extends Source * the same answer as a batch query that had processed the entire dataset at any given point. */ case class DeltaSource( - spark: SparkSession, + override val spark: SparkSession, deltaLog: DeltaLog, catalogTableOpt: Option[CatalogTable], options: DeltaOptions, diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceMetadataEvolutionSupport.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceMetadataEvolutionSupport.scala index d1a1a1f039b..015b2217ff3 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceMetadataEvolutionSupport.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceMetadataEvolutionSupport.scala @@ -92,7 +92,7 @@ import org.apache.spark.sql.types.StructType */ trait DeltaSourceMetadataEvolutionSupport extends DeltaSourceBase { base: DeltaSource => - protected def trackingMetadataChange: Boolean = + override protected def trackingMetadataChange: Boolean = DeltaSourceMetadataEvolutionSupport.shouldTrackMetadataChange( schemaReadOptions, metadataTrackingLog) @@ -717,6 +717,7 @@ object DeltaSourceMetadataEvolutionSupport extends Logging { } } + /** * Check the table metadata or protocol changed since the initial read snapshot. We make sure: * 1. The schema is the same, except for internal metadata, AND diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceOffsetLogic.scala b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceOffsetLogic.scala new file mode 100644 index 00000000000..01e21808419 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/sources/DeltaSourceOffsetLogic.scala @@ -0,0 +1,95 @@ +/* + * Copyright (2026) 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.sources + +import org.apache.spark.sql.delta.{DeltaColumnMapping, DeltaErrors, TypeWidening} +import org.apache.spark.sql.delta.actions.Metadata + +import org.apache.spark.sql.SparkSession + +/** + * Offset logic shared by the Delta streaming sources: [[DeltaSource]] (V1) and + * `DeltaV2MicroBatchStream` (V2). Both sources mix in this trait and run the same code. + */ +trait DeltaSourceOffsetLogic { + + // --------------------------------------------------------------------------------------------- + // Required from the source + // --------------------------------------------------------------------------------------------- + + protected def spark: SparkSession + + /** Options that control how the source handles schema changes. */ + protected def schemaReadOptions: DeltaStreamUtils.SchemaReadOptions + + /** Whether the source reads with a schema from the metadata tracking log. */ + protected def trackingMetadataChange: Boolean + + + // --------------------------------------------------------------------------------------------- + // Schema checks + // --------------------------------------------------------------------------------------------- + + /** + * Checks for non-additive schema changes (column renames, drops, type widening) and blocks + * the stream by throwing an exception if detected. + * + * Blocks when type widening tracking is enabled and widening changes exist, or when column + * mapping changes (rename/drop) are detected, unless `allowUnsafeStreamingReadOnColumnMapping + * SchemaChanges` is enabled. Upon blocking, the error requests the user to provide a schema + * tracking location to enable schema tracking. On restart, users must acknowledge changes via + * reader options or SQL confs. + * See [[DeltaSourceMetadataEvolutionSupport.validateIfSchemaChangeCanBeUnblocked]]. + * + * Note: Should not be called when schema tracking is active (trackingMetadataChange = true). + * + * @param oldMetadata Previous metadata (typically from stream initialization) + * @param newMetadata New metadata with potential schema changes + * @param validatedDuringStreamStart Whether validating during stream start vs. execution, + * which affects the error message. + * @throws DeltaAnalysisException if non-additive schema changes require blocking + */ + protected def checkNonAdditiveSchemaChanges( + oldMetadata: Metadata, + newMetadata: Metadata, + validatedDuringStreamStart: Boolean): Unit = { + val shouldTrackSchema: Boolean = + if (schemaReadOptions.typeWideningEnabled && + schemaReadOptions.enableSchemaTrackingForTypeWidening && + TypeWidening.containsWideningTypeChanges(oldMetadata.schema, newMetadata.schema)) { + // If schema tracking is enabled for type widening, we will detect widening type changes and + // block the stream until the user sets `allowSourceColumnTypeChange` - similar to handling + // DROP/RENAME for column mapping. + true + } else if (schemaReadOptions.allowUnsafeStreamingReadOnColumnMappingSchemaChanges) { + false + } else { + // Column mapping schema changes + assert(!trackingMetadataChange, "should not check schema change while tracking it") + !DeltaColumnMapping.hasNoColumnMappingSchemaChanges(newMetadata, oldMetadata, + schemaReadOptions.allowUnsafeStreamingReadOnPartitionColumnChanges) + } + + if (shouldTrackSchema) { + throw DeltaErrors.blockStreamingReadsWithIncompatibleNonAdditiveSchemaChanges( + spark, + oldMetadata.schema, + newMetadata.schema, + detectedDuringStreaming = !validatedDuringStreamStart) + } + } +} diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala index 83867b6708c..a26915200b5 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala @@ -27,7 +27,6 @@ import scala.jdk.javaapi.CollectionConverters import scala.util.Using import scala.util.matching.Regex -import org.apache.spark.sql.delta.DeltaColumnMapping import org.apache.spark.sql.delta.DeltaErrors import org.apache.spark.sql.delta.DeltaOptions import org.apache.spark.sql.delta.DeltaSingleCommit @@ -47,6 +46,7 @@ import org.apache.spark.sql.delta.files.DeltaSourceSnapshot import org.apache.spark.sql.delta.sources.DeltaSource import org.apache.spark.sql.delta.sources.DeltaSourceMetadataTrackingLog import org.apache.spark.sql.delta.sources.DeltaSourceOffset +import org.apache.spark.sql.delta.sources.DeltaSourceOffsetLogic import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.sources.DeltaStreamingBackend import org.apache.spark.sql.delta.sources.DeltaStreamUtils @@ -99,7 +99,7 @@ private[read] class DeltaV2MicroBatchStream( tableManager: DeltaV2TableManager, snapshotAtSourceInit: Snapshot, hadoopConf: Configuration, - spark: SparkSession, + override protected val spark: SparkSession, options: DeltaOptions, inputTablePath: String, dataSchema: StructType, @@ -113,7 +113,8 @@ private[read] class DeltaV2MicroBatchStream( originalStreamingQueryContext: DeltaV2QueryContext) extends MicroBatchStream with SupportsAdmissionControl - with SupportsTriggerAvailableNow { + with SupportsTriggerAvailableNow + with DeltaSourceOffsetLogic { private val logger: Logger = LoggerFactory.getLogger(classOf[DeltaV2MicroBatchStream]) @@ -243,7 +244,7 @@ private[read] class DeltaV2MicroBatchStream( * Configuration options for handling schema changes behavior. Controls unsafe operations like * column mapping changes, partition column changes, nullability changes, and type widening. */ - private val schemaReadOptions: DeltaStreamUtils.SchemaReadOptions = { + override protected val schemaReadOptions: DeltaStreamUtils.SchemaReadOptions = { val isStreamingFromColumnMappingTable: Boolean = this.snapshotAtSourceInit.metadata.columnMappingMode != NoMapping val isTypeWideningSupportedInProtocol: Boolean = @@ -267,6 +268,10 @@ private[read] class DeltaV2MicroBatchStream( readSnapshotDescriptor.metadata, readSnapshotDescriptor.protocol, metadataPath) + + override protected def trackingMetadataChange: Boolean = + metadataEvolutionHandler.shouldTrackMetadataChange() + locally { val shouldValidateSchemaOnRestart: Boolean = spark @@ -1338,7 +1343,10 @@ private[read] class DeltaV2MicroBatchStream( oldPartitionColumns = oldMetadata.partitionColumns.toList } - checkNonAdditiveSchemaChanges(oldMetadata, newMetadata, validatedDuringStreamStart) + checkNonAdditiveSchemaChanges( + oldMetadata, + newMetadata, + validatedDuringStreamStart) // Other standard read compatibility changes if (!validatedDuringStreamStart @@ -1375,37 +1383,6 @@ private[read] class DeltaV2MicroBatchStream( } } - // Non-additive schema changes include rename column, drop column and change column type. - // When schema tracking is enabled, this method is NOT called - the MetadataEvolutionHandler - // manages these changes through the barrier protocol instead. - private def checkNonAdditiveSchemaChanges( - oldMetadata: Metadata, newMetadata: Metadata, validatedDuringStreamStart: Boolean): Unit = { - var shouldTrackSchema: Boolean = false - if (schemaReadOptions.typeWideningEnabled - && schemaReadOptions.enableSchemaTrackingForTypeWidening - && TypeWidening.containsWideningTypeChanges(oldMetadata.schema, newMetadata.schema)) { - // If schema tracking is enabled for type widening, we will detect widening type changes and - // block the stream until the user sets `allowSourceColumnTypeChange` - similar to handling - // DROP/RENAME for column mapping. - shouldTrackSchema = true - } else if (schemaReadOptions.allowUnsafeStreamingReadOnColumnMappingSchemaChanges) { - shouldTrackSchema = false - } else { - // Delegate to the shared utility which handles all column mapping mode transitions - // (both enabled, upgrade from none, downgrade to none). - shouldTrackSchema = - !DeltaColumnMapping.hasNoColumnMappingSchemaChanges( - newMetadata, - oldMetadata, - schemaReadOptions.allowUnsafeStreamingReadOnPartitionColumnChanges) - } - - if (shouldTrackSchema) { - throw DeltaErrors.blockStreamingReadsWithIncompatibleNonAdditiveSchemaChanges( - spark, oldMetadata.schema, newMetadata.schema, !validatedDuringStreamStart) - } - } - /** * Validate and lazily initialize the metadata tracking log for planned batches during stream * (re)start. Mirrors v1's {@code validateAndInitMetadataLogForPlannedBatchesDuringStreamStart}. From 760382473dc474f7c0c601b4cab8b381d882a5aa Mon Sep 17 00:00:00 2001 From: Eric Tseng Date: Tue, 17 Nov 2026 03:45:41 -0800 Subject: [PATCH 18/44] [Spark] Fix snapshot listing test catalog selection (#8188) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other ## Description `SnapshotManagementParallelListingSuite` registers its test coordinator for `spark_catalog`. If another catalog is current, its unqualified table name creates the table elsewhere and bypasses that coordinator. Qualify the test table name and use an explicit catalog-qualified identifier when opening the Delta log so the listing reconciliation assertions exercise the intended coordinator. ## How was this patch tested? - `git diff --check` passed. - The local `spark/testOnly org.apache.spark.sql.delta.SnapshotManagementParallelListingSuite` run could not start because the sbt launcher download was unavailable. The suite will run in CI. ## Does this PR introduce _any_ user-facing changes? No. Signed-off-by: Eric Tseng <52102337+EricTsengTy@users.noreply.github.com> --- .../sql/delta/SnapshotManagementSuite.scala | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/SnapshotManagementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/SnapshotManagementSuite.scala index b30297e8c3d..546f0cd10fd 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/SnapshotManagementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/SnapshotManagementSuite.scala @@ -848,6 +848,12 @@ class SnapshotManagementParallelListingSuite extends QueryTest with SharedSparkSession with DeltaSQLCommandTest { + private val testTableIdentifier = TableIdentifier( + "snapshot_listing_catalog_managed", + Some("default"), + Some(CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING)) + private val qualifiedTableName = testTableIdentifier.unquotedString + override protected def sparkConf: SparkConf = super.sparkConf.set(logStoreClassConfKey, classOf[CountDownLatchLogStore].getName) @@ -870,10 +876,10 @@ class SnapshotManagementParallelListingSuite extends QueryTest _ => spark.range(10).write.format("delta").mode("append").saveAsTable(tableName)) } - private def captureUsageRecordsAndGetSnapshot(tableName: String): (Snapshot, Seq[UsageRecord]) = { + private def captureUsageRecordsAndGetSnapshot(): (Snapshot, Seq[UsageRecord]) = { var snapshot: Snapshot = null val records = Log4jUsageLogger.track { - snapshot = DeltaLog.forTable(spark, TableIdentifier(tableName)).update() + snapshot = DeltaLog.forTable(spark, testTableIdentifier).update() } (snapshot, records) } @@ -912,17 +918,16 @@ class SnapshotManagementParallelListingSuite extends QueryTest val endVersion = if (tryIncludeGapAtTheEnd) { batchSize } else { batchSize + 3 } withSQLConf( DeltaSQLConf.DELTALOG_MINOR_COMPACTION_USE_FOR_READS.key -> "false") { - val tableName = "snapshot_listing_catalog_managed" - withTable(tableName) { - writeDeltaData(tableName, endVersion) - val deltaLog = DeltaLog.forTable(spark, TableIdentifier(tableName)) + withTable(qualifiedTableName) { + writeDeltaData(qualifiedTableName, endVersion) + val deltaLog = DeltaLog.forTable(spark, testTableIdentifier) assert(deltaLog.update().isCatalogOwned) // Invalidate cache to ensure re-listing. DeltaLog.invalidateCache(spark, deltaLog.dataPath) ConcurrentBackfillCommitCoordinatorClient.beginConcurrentBackfills = true - val (snapshot, records) = captureUsageRecordsAndGetSnapshot(tableName) + val (snapshot, records) = captureUsageRecordsAndGetSnapshot() val expectedNeedAdditionalFsListingCount = if (concurrentBackfills) { 1 } else { 0 } verifyUsageRecords(records, expectedNeedAdditionalFsListingCount) verifySnapshotBackfills(snapshot, backfillUntilInclusive = batchSize) @@ -937,10 +942,9 @@ class SnapshotManagementParallelListingSuite extends QueryTest val endVersion = batchSize + 3 withSQLConf( DeltaSQLConf.DELTALOG_MINOR_COMPACTION_USE_FOR_READS.key -> "false") { - val tableName = "snapshot_listing_catalog_managed" - withTable(tableName) { - writeDeltaData(tableName, endVersion) - val deltaLog = DeltaLog.forTable(spark, TableIdentifier(tableName)) + withTable(qualifiedTableName) { + writeDeltaData(qualifiedTableName, endVersion) + val deltaLog = DeltaLog.forTable(spark, testTableIdentifier) assert(deltaLog.update().isCatalogOwned) // Delete 5.json to create a permanent gap between file-system i.e. [0, 4] and @@ -951,7 +955,7 @@ class SnapshotManagementParallelListingSuite extends QueryTest // Invalidate cache to ensure re-listing. DeltaLog.invalidateCache(spark, deltaLog.dataPath) val e = intercept[IllegalStateException] { - DeltaLog.forTable(spark, TableIdentifier(tableName)).update() + DeltaLog.forTable(spark, testTableIdentifier).update() } assert(e.getMessage.contains("unexpectedly still requires additional file-system listing")) } From 83c33403ee0ded0635f7b93de40df78547513ed4 Mon Sep 17 00:00:00 2001 From: Omar Elhadidy Date: Tue, 17 Nov 2026 16:45:33 +0100 Subject: [PATCH 19/44] [SPARK] Support verionless CDF in delta sharing delta format responses (#8170) --> - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Support querying versionless CDF for delta sharing clients with delta format. ## How was this patch tested? UTs ## Does this PR introduce _any_ user-facing changes? No --------- Co-authored-by: Omar Elhadidy --- .../sharing/spark/DeltaSharingCDFUtils.scala | 36 +++- .../spark/DeltaSharingCDFUtilsSuite.scala | 200 ++++++++++++++++++ 2 files changed, 226 insertions(+), 10 deletions(-) diff --git a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingCDFUtils.scala b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingCDFUtils.scala index 55bcbe609be..daf87271b18 100644 --- a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingCDFUtils.scala +++ b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingCDFUtils.scala @@ -18,6 +18,7 @@ package io.delta.sharing.spark import java.lang.ref.WeakReference import java.nio.charset.StandardCharsets.UTF_8 +import java.util.UUID import org.apache.spark.sql.delta.catalog.DeltaTableV2 import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -41,6 +42,7 @@ object DeltaSharingCDFUtils extends Logging { * Prepares the BaseRelation for cdf queries on a delta sharing table. Since there's no limit * pushdown or filter pushdown involved, it wiill firatly fetch all the files from the delta * sharing server, prepare the local delta log, and leverage DeltaTableV2 to produce the relation. + * Versionless CDF is already materialized as data, so it only needs a snapshot read. */ private[sharing] def prepareCDFRelation( sqlContext: SQLContext, @@ -74,15 +76,28 @@ object DeltaSharingCDFUtils extends Logging { val path = options.options.getOrElse("path", throw DeltaSharingErrors.pathNotSpecifiedException) // 2. Prepare local delta log val queryCustomTablePath = client.getProfileProvider.getCustomTablePath(path) - val queryParamsHashId = DeltaSharingUtils.getQueryParamsHashId(options.cdfOptions) + val queryParamsHashId = if (deltaTableFiles.isVersionlessCDF) { + // Each materialization has its own version-zero log, including reads with identical bounds. + s"${DeltaSharingUtils.getQueryParamsHashId(options.cdfOptions)}_${UUID.randomUUID()}" + } else { + DeltaSharingUtils.getQueryParamsHashId(options.cdfOptions) + } val tablePathWithHashIdSuffix = DeltaSharingUtils.getTablePathWithIdSuffix(queryCustomTablePath, queryParamsHashId) - val deltaLogMetadata = DeltaSharingLogFileSystem.constructLocalDeltaLogAcrossVersions( - lines = deltaTableFiles.lines, - customTablePath = tablePathWithHashIdSuffix, - startingVersionOpt = None, - endingVersionOpt = None - ) + val deltaLogMetadata = if (deltaTableFiles.isVersionlessCDF) { + // Materialized rows already contain the source CDF columns. Read them as a snapshot. + DeltaSharingLogFileSystem.constructLocalDeltaLogAtVersionZero( + lines = deltaTableFiles.lines, + customTablePath = tablePathWithHashIdSuffix + ) + } else { + DeltaSharingLogFileSystem.constructLocalDeltaLogAcrossVersions( + lines = deltaTableFiles.lines, + customTablePath = tablePathWithHashIdSuffix, + startingVersionOpt = None, + endingVersionOpt = None + ) + } // 3. Register parquet file id to url mapping CachedTableManager.INSTANCE.register( @@ -116,10 +131,11 @@ object DeltaSharingCDFUtils extends Logging { DeltaSharingOptions.CDF_END_VERSION -> deltaLogMetadata.maxVersion.toString, DeltaSharingOptions.CDF_READ_OPTION -> "true" ) - DeltaTableV2( + val deltaTable = DeltaTableV2( spark = sqlContext.sparkSession, path = DeltaSharingLogFileSystem.encode(tablePathWithHashIdSuffix), - options = localDeltaCdfOptions - ).toBaseRelation + options = if (deltaTableFiles.isVersionlessCDF) Map.empty else localDeltaCdfOptions + ) + deltaTable.toBaseRelation } } diff --git a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingCDFUtilsSuite.scala b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingCDFUtilsSuite.scala index 140f2658e69..4c72442339a 100644 --- a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingCDFUtilsSuite.scala +++ b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingCDFUtilsSuite.scala @@ -177,6 +177,26 @@ class DeltaSharingCDFUtilsSuite with DeltaSharingTestSparkUtils { import CDFTesTUtils._ + import java.util.concurrent.ConcurrentLinkedQueue + import java.util.concurrent.atomic.AtomicBoolean + + import scala.concurrent.duration._ + import scala.jdk.CollectionConverters._ + + import org.apache.spark.sql.delta.DeltaLog + import org.apache.spark.sql.delta.util.DeltaFileOperations + import io.delta.sharing.spark.model.{ + DeltaSharingFileAction, + DeltaSharingMetadata, + DeltaSharingProtocol + } + + import org.apache.spark.delta.sharing.CachedTableManager + import org.apache.spark.sql.Row + import org.apache.spark.sql.catalyst.TableIdentifier + import org.apache.spark.sql.execution.datasources.HadoopFsRelation + import org.apache.spark.sql.types.TimestampType + private val shareName = "share" private val schemaName = "default" @@ -190,6 +210,186 @@ class DeltaSharingCDFUtilsSuite .set("spark.delta.sharing.driver.accessThresholdToExpireMs", "60000") } + for (empty <- Seq(false, true); cache <- Seq(false, true)) test( + "versionless CDF reads a native Delta snapshot with column mapping " + + s"(empty=$empty, cache=$cache)") { + withTempDir { tempDir => + val materializedTable = "versionless_cdf_rows" + withTable(materializedTable) { + sql(s"""CREATE TABLE $materializedTable + |(value STRING, _change_type STRING, _commit_timestamp TIMESTAMP) + |USING DELTA PARTITIONED BY (value) + |TBLPROPERTIES ('delta.columnMapping.mode' = 'name', + |'delta.enableChangeDataFeed' = 'false', 'delta.enableDeletionVectors' = 'false') + |""".stripMargin) + val expected = if (empty) { + Seq.empty[Row] + } else { + sql(s"""INSERT INTO $materializedTable VALUES + |('first', 'insert', TIMESTAMP '2026-01-01 00:00:01'), + |('second', 'delete', TIMESTAMP '2026-01-01 00:00:02') + |""".stripMargin) + Seq( + Row("first", "insert", sqlTimestamp("2026-01-01 00:00:01")), + Row("second", "delete", sqlTimestamp("2026-01-01 00:00:02"))) + } + val deltaLog = DeltaLog.forTable(spark, TableIdentifier(materializedTable)) + def snapshotResponse(): DeltaTableFiles = { + val snapshot = deltaLog.update() + val fileLines = snapshot.allFiles.collect().toSeq.map { add => + val file = new File( + DeltaFileOperations.absolutePath(deltaLog.dataPath.toString, add.path).toUri) + val fileId = file.getName + // Serve the real Delta files through the existing sharing test filesystem. + DeltaSharingUtils.overrideIteratorBlock[Byte]( + TestDeltaSharingFileSystem.getBlockId(sharedTableName, fileId), + FileUtils.readFileToByteArray(file).toIterator) + DeltaSharingFileAction( + id = fileId, + expirationTimestamp = System.currentTimeMillis() + 60000, + deltaSingleAction = add.copy( + path = TestDeltaSharingFileSystem.encode(sharedTableName, fileId)).wrap).json + } + DeltaTableFiles( + version = 0L, + lines = Seq( + DeltaSharingProtocol(snapshot.protocol).json, + DeltaSharingMetadata(deltaMetadata = snapshot.metadata).json) ++ fileLines, + respondedFormat = DeltaSharingRestClient.RESPONSE_FORMAT_DELTA, + isVersionlessCDF = true) + } + var response = snapshotResponse() + val profilePath = prepareProfileFile(tempDir).getCanonicalPath + val tablePath = s"$profilePath#$shareName.$schemaName.$sharedTableName" + withSQLConf( + "spark.delta.sharing.client.sparkParquetIOCache.enabled" -> cache.toString, + "fs.delta-sharing.impl" -> classOf[TestDeltaSharingFileSystem].getName, + "fs.delta-sharing-log.impl" -> classOf[DeltaSharingLogFileSystem].getName, + "spark.delta.sharing.profile.provider.class" -> + "io.delta.sharing.client.DeltaSharingFileProfileProvider" + ) { + PreSignedUrlCache.registerIfNeeded(SparkEnv.get) + val provider = DeltaSharingRestClient(profilePath, Map.empty, false, "delta") + .getProfileProvider + // Snapshot and metadata RPCs are unsupported by this client, so extra requests fail. + val client = new TestDeltaSharingClientForCDFUtils(provider) { + override def getCDFFiles( + table: Table, + cdfOptions: Map[String, String], + includeHistoricalMetadata: Boolean, + fileIdHash: Option[String], + includeHistoricalProtocol: Boolean = false): DeltaTableFiles = { + numGetFileCalls += 1 + response + } + } + client.numGetFileCalls = 0 + val options = new DeltaSharingOptions(Map( + "path" -> tablePath, + "readChangeFeed" -> "true", + "startingTimestamp" -> "2026-01-01T00:00:00Z", + "endingTimestamp" -> "2026-01-01T00:00:03Z")) + val relation = DeltaSharingCDFUtils.prepareCDFRelation( + spark.sqlContext, + options, + Table(share = shareName, schema = schemaName, name = sharedTableName), + client) + assert(relation.schema.fieldNames.toSeq == + Seq("value", "_change_type", "_commit_timestamp")) + assert(relation.schema("_commit_timestamp").dataType == TimestampType) + val firstRead = spark.sqlContext.baseRelationToDataFrame(relation) + checkAnswer(firstRead, expected) + assert(client.numGetFileCalls == 1) + if (!empty) { + sql(s"""INSERT OVERWRITE $materializedTable VALUES + |('third', 'update_postimage', TIMESTAMP '2026-01-01 00:00:03') + |""".stripMargin) + response = snapshotResponse() + val nextRelation = DeltaSharingCDFUtils.prepareCDFRelation( + spark.sqlContext, + options, + Table(share = shareName, schema = schemaName, name = sharedTableName), + client) + checkAnswer(spark.sqlContext.baseRelationToDataFrame(nextRelation), + Seq(Row("third", "update_postimage", sqlTimestamp("2026-01-01 00:00:03")))) + checkAnswer(firstRead, expected) + assert(client.numGetFileCalls == 2) + } + } + } + } + } + + test("versionless CDF refresh preserves timestamp bounds and isolates queries") { + withTempDir { tempDir => + val profilePath = prepareProfileFile(tempDir).getCanonicalPath + val tablePath = s"$profilePath#$shareName.$schemaName.$sharedTableName" + val calls = new ConcurrentLinkedQueue[Map[String, String]]() + val refresh = new AtomicBoolean(false) + withSQLConf( + "fs.delta-sharing-log.impl" -> classOf[DeltaSharingLogFileSystem].getName, + "spark.delta.sharing.profile.provider.class" -> + "io.delta.sharing.client.DeltaSharingFileProfileProvider" + ) { + val provider = DeltaSharingRestClient(profilePath, Map.empty, false, "delta") + .getProfileProvider + val client = new TestDeltaSharingClientForCDFUtils(provider) { + override def getCDFFiles( + table: Table, + cdfOptions: Map[String, String], + includeHistoricalMetadata: Boolean, + fileIdHash: Option[String], + includeHistoricalProtocol: Boolean = false): DeltaTableFiles = { + assert(includeHistoricalMetadata) + calls.add(cdfOptions) + val prefix = if (refresh.get()) "refreshed" else "original" + val path = s"http://$prefix/${cdfOptions("startingTimestamp")}" + DeltaTableFiles( + version = 0L, + lines = Seq( + """{"protocol":{"deltaProtocol":{"minReaderVersion":1,"minWriterVersion":1}}}""", + metaDataStr, + getAddFileStr1(path, returnExpTime = true)), + respondedFormat = DeltaSharingRestClient.RESPONSE_FORMAT_DELTA, + isVersionlessCDF = true) + } + } + val table = Table(share = shareName, schema = schemaName, name = sharedTableName) + val options = Seq("2026-01-01T00:00:00Z", "2026-01-02T00:00:00Z").map { start => + new DeltaSharingOptions(Map( + "path" -> tablePath, + "readChangeFeed" -> "true", + "startingTimestamp" -> start, + "endingTimestamp" -> "2026-01-03T00:00:00Z")) + } + val relations = options.map { queryOptions => + DeltaSharingCDFUtils.prepareCDFRelation(spark.sqlContext, queryOptions, table, client) + } + val keys = relations.map { relation => + DeltaSharingLogFileSystem.decode( + relation.asInstanceOf[HadoopFsRelation].location.rootPaths.head) + } + assert(keys.distinct.size == 2) + keys.zip(options).foreach { case (key, queryOptions) => + val expectedUrl = s"http://original/${queryOptions.cdfOptions("startingTimestamp")}" + assert(CachedTableManager.INSTANCE.getPreSignedUrl(key, fileStr1Id)._1 == expectedUrl) + } + refresh.set(true) + eventually(timeout(20.seconds), interval(100.millis)) { + keys.zip(options).foreach { case (key, queryOptions) => + val expectedUrl = s"http://refreshed/${queryOptions.cdfOptions("startingTimestamp")}" + assert(CachedTableManager.INSTANCE.getPreSignedUrl(key, fileStr1Id)._1 == expectedUrl) + } + } + val recordedOptions = calls.asScala.toSeq + assert(recordedOptions.forall(call => options.exists(_.cdfOptions == call))) + options.foreach { queryOptions => + assert(recordedOptions.count(_ == queryOptions.cdfOptions) >= 2) + } + } + } + } + test("refresh works") { PreSignedUrlCache.registerIfNeeded(SparkEnv.get) From 99823f83d20f1951c9ab4bde5fa07e13a3a93580 Mon Sep 17 00:00:00 2001 From: Zihao Xu Date: Tue, 17 Nov 2026 07:46:18 -0800 Subject: [PATCH 20/44] [Spark] Rename CatalogOwnedUsageLogs to CatalogManagedUsageLogs (#8157) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Stacked on #8158; review the last commit. Renames the `CatalogOwnedUsageLogs` object, which holds the op types of catalog-managed tables, to `CatalogManagedUsageLogs`. The `coordinatedcommits` package object keeps the old name as an alias. The op type values, such as `delta.catalogOwned.commitToUcEtagRetry`, stay the same. ## How was this patch tested? Rename only, no new tests. Apart from the aliases and the line wrapping, every changed token is an old name changed to the new one. ## Does this PR introduce _any_ user-facing changes? No. --- .../delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala | 2 +- .../sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala | 2 +- .../org/apache/spark/sql/delta/coordinatedcommits/package.scala | 1 + .../delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala index cf99c23fb31..713e180f351 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUsageLogs.scala @@ -17,7 +17,7 @@ package org.apache.spark.sql.delta.coordinatedcommits /** Class containing usage logs emitted by Catalog Managed. */ -object CatalogOwnedUsageLogs { +object CatalogManagedUsageLogs { /** Common prefix for all catalog-managed usage logs. */ val PREFIX = "delta.catalogOwned" diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala index 6539820f8c3..1586d01fea7 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala @@ -418,7 +418,7 @@ object CatalogManagedTableUtils extends DeltaLogging { private def logAndThrowPathBasedAccessNotAllowed(snapshot: Snapshot): Nothing = { recordCommitCoordinatorPopulationUsageLog( snapshot.deltaLog, - opType = CatalogOwnedUsageLogs.COMMIT_COORDINATOR_POPULATION_INVALID_PATH_BASED_ACCESS, + opType = CatalogManagedUsageLogs.COMMIT_COORDINATOR_POPULATION_INVALID_PATH_BASED_ACCESS, snapshot, catalogTableOpt = None, commitCoordinatorOpt = None, diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala index 95b986d4fd2..9e037cf7fc6 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala @@ -20,4 +20,5 @@ package org.apache.spark.sql.delta package object coordinatedcommits { // The old names, kept until their callers use the new ones. val CatalogOwnedTableUtils: CatalogManagedTableUtils.type = CatalogManagedTableUtils + val CatalogOwnedUsageLogs: CatalogManagedUsageLogs.type = CatalogManagedUsageLogs } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala index a6c9e1bf1a2..6711ca265b5 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala @@ -209,7 +209,7 @@ class CatalogOwnedEnablementSuite }.filter { log => log.metric == "tahoeEvent" && log.tags.getOrElse("opType", null) == - CatalogOwnedUsageLogs.COMMIT_COORDINATOR_POPULATION_INVALID_PATH_BASED_ACCESS + CatalogManagedUsageLogs.COMMIT_COORDINATOR_POPULATION_INVALID_PATH_BASED_ACCESS } assert(usageLog.nonEmpty, "Should have usage log for INVALID_PATH_BASED_ACCESS scenario") From a75a415b90f8b57bd5926d4bcb009c96ac498e86 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Tue, 17 Nov 2026 13:01:02 -0500 Subject: [PATCH 21/44] [Spark][DEDUP] Share row-tracking metadata lookup in V2 value setter builders (#8113) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Extracts the shared row-tracking file metadata lookup, missing-value validation, and long conversion used by the V2 row ID and row commit version value setter builders. Exception types and messages remain unchanged. ## How was this patch tested? - `build/sbt "sparkV2/Compile/javafmtCheckAll"` - `build/sbt "sparkV2/testOnly org.apache.spark.sql.delta.v2.read.metadata.MetadataStructReadFunctionTest org.apache.spark.sql.delta.v2.read.metadata.MetadataStructSchemaContextTest org.apache.spark.sql.delta.v2.read.metadata.MetadataValueSetterTest org.apache.spark.sql.delta.v2.V2RowTrackingReadTest"` ## Does this PR introduce _any_ user-facing changes? No. --------- Signed-off-by: tdas --- .../RowCommitVersionValueSetterBuilder.java | 21 +++------ .../metadata/RowIdValueSetterBuilder.java | 21 ++------- .../RowTrackingMetadataValueUtils.java | 45 +++++++++++++++++++ .../metadata/MetadataValueSetterTest.java | 31 +++++++++++++ 4 files changed, 84 insertions(+), 34 deletions(-) create mode 100644 spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowTrackingMetadataValueUtils.java diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowCommitVersionValueSetterBuilder.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowCommitVersionValueSetterBuilder.java index a2e12ddfab4..f297dd0d499 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowCommitVersionValueSetterBuilder.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowCommitVersionValueSetterBuilder.java @@ -36,22 +36,11 @@ public RowCommitVersionValueSetterBuilder(int materializedRowCommitVersionIdx) { @Override public BoundMetadataValueSetter buildWithFile(PartitionedFile file) { - // default_row_commit_version is required whenever row tracking is enabled on the file; fail - // fast with an actionable error rather than NPE if it's missing. - Object rawDefault = - file.otherConstantMetadataColumnValues() - .get(DefaultRowCommitVersion$.MODULE$.METADATA_STRUCT_FIELD_NAME()) - .getOrElse(() -> null); - if (rawDefault == null) { - throw new IllegalStateException( - "Missing '" - + DefaultRowCommitVersion$.MODULE$.METADATA_STRUCT_FIELD_NAME() - + "' on PartitionedFile '" - + file.filePath() - + "' for row tracking - every Delta " - + "file with row tracking enabled must carry a default_row_commit_version constant."); - } - long defaultCommitVersion = ((Number) rawDefault).longValue(); + long defaultCommitVersion = + RowTrackingMetadataValueUtils.requireRowTrackingLong( + file, + DefaultRowCommitVersion$.MODULE$.METADATA_STRUCT_FIELD_NAME(), + "default_row_commit_version constant"); return new Bound(defaultCommitVersion, materializedRowCommitVersionIdx); } diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowIdValueSetterBuilder.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowIdValueSetterBuilder.java index 6d88c1eee8d..4094c3fbf63 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowIdValueSetterBuilder.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowIdValueSetterBuilder.java @@ -38,24 +38,9 @@ public RowIdValueSetterBuilder(int materializedRowIdIdx, int rowIndexIdx) { @Override public BoundMetadataValueSetter buildWithFile(PartitionedFile file) { - // base_row_id is required whenever row tracking is enabled on the file; if it's not present - // (would yield null via Scala's `apply` throwing NoSuchElementException, or returning null - // from a Java-shaped map), fail fast with an actionable error rather than NPE on the - // subsequent .longValue() call. - Object rawBaseRowId = - file.otherConstantMetadataColumnValues() - .get(RowId$.MODULE$.BASE_ROW_ID()) - .getOrElse(() -> null); - if (rawBaseRowId == null) { - throw new IllegalStateException( - "Missing '" - + RowId$.MODULE$.BASE_ROW_ID() - + "' on PartitionedFile '" - + file.filePath() - + "' for row tracking - every Delta file with row tracking " - + "enabled must carry a base_row_id constant."); - } - long baseRowId = ((Number) rawBaseRowId).longValue(); + long baseRowId = + RowTrackingMetadataValueUtils.requireRowTrackingLong( + file, RowId$.MODULE$.BASE_ROW_ID(), "base_row_id constant"); return new Bound(baseRowId, materializedRowIdIdx, rowIndexIdx); } diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowTrackingMetadataValueUtils.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowTrackingMetadataValueUtils.java new file mode 100644 index 00000000000..42403b4a858 --- /dev/null +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/metadata/RowTrackingMetadataValueUtils.java @@ -0,0 +1,45 @@ +/* + * Copyright (2026) 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.v2.read.metadata; + +import org.apache.spark.sql.execution.datasources.PartitionedFile; + +final class RowTrackingMetadataValueUtils { + + private RowTrackingMetadataValueUtils() {} + + /** + * Returns the required row-tracking long constant from {@code file}. Fails fast with a clear + * {@link IllegalStateException} instead of an NPE on {@code longValue()} when the constant is + * missing. {@code requiredConstantDescription} is spliced into the exception message; callers + * pass descriptions of the form {@code " constant"}. + */ + static long requireRowTrackingLong( + PartitionedFile file, String key, String requiredConstantDescription) { + Object rawValue = file.otherConstantMetadataColumnValues().get(key).getOrElse(() -> null); + if (rawValue == null) { + throw new IllegalStateException( + "Missing '" + + key + + "' on PartitionedFile '" + + file.filePath() + + "' for row tracking - every Delta file with row tracking enabled must carry a " + + requiredConstantDescription + + "."); + } + return ((Number) rawValue).longValue(); + } +} diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/metadata/MetadataValueSetterTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/metadata/MetadataValueSetterTest.java index 165bb204c12..b63695d35f1 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/metadata/MetadataValueSetterTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/metadata/MetadataValueSetterTest.java @@ -17,6 +17,7 @@ import static org.apache.spark.sql.delta.v2.InternalRowTestUtils.row; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.spark.paths.SparkPath; import org.apache.spark.sql.catalyst.InternalRow; @@ -112,6 +113,21 @@ public void testRowIdSetterFallsBackToBaseRowIdPlusRowIndex() { assertEquals(52L, metadataRow.getLong(0), "row_id should fall back to baseRowId + rowIndex"); } + @Test + public void testRowIdSetterRejectsMissingBaseRowId() { + RowIdValueSetterBuilder setter = new RowIdValueSetterBuilder(1, 2); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, () -> setter.buildWithFile(simplePartitionedFile())); + + assertEquals( + "Missing 'base_row_id' on PartitionedFile 'file:///tmp/setter-test.parquet' for row " + + "tracking - every Delta file with row tracking enabled must carry a base_row_id " + + "constant.", + error.getMessage()); + } + // --------------------------------------------------------------------------- // RowCommitVersionValueSetterBuilder // --------------------------------------------------------------------------- @@ -148,6 +164,21 @@ public void testRowCommitVersionSetterFallsBackToDefault() { assertEquals(9L, metadataRow.getLong(0)); } + @Test + public void testRowCommitVersionSetterRejectsMissingDefaultCommitVersion() { + RowCommitVersionValueSetterBuilder setter = new RowCommitVersionValueSetterBuilder(1); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, () -> setter.buildWithFile(simplePartitionedFile())); + + assertEquals( + "Missing 'default_row_commit_version' on PartitionedFile " + + "'file:///tmp/setter-test.parquet' for row tracking - every Delta file with row " + + "tracking enabled must carry a default_row_commit_version constant.", + error.getMessage()); + } + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- From 79ca8516d84f3e6352d79ce4c3f60f908909d7d4 Mon Sep 17 00:00:00 2001 From: Sumeet Varma Date: Tue, 17 Nov 2026 10:04:48 -0800 Subject: [PATCH 22/44] [Spark] Fix DROP FEATURE deletionVectors succeeding while files still have deletion vectors (#8190) #### Which Delta project/connector is this regarding? - [x] Spark ## Description `DeletionVectorsTableFeature.validateDropInvariants` treated an unknown DV count as zero. `numDeletionVectorsOpt` is unknown when DVs are no longer writable and the snapshot has no checksum with the count, for example after a RESTORE commit. In that case DROP FEATURE deletionVectors succeeded while files still had deletion vectors. This change checks the files themselves (`DeletionVectorUtils.isTableDVFree`) when the count is unknown. ## How was this patch tested? Tested with a scenario that drops the feature after a RESTORE leaves the DV count unknown while files still have DVs. Without this change DROP FEATURE succeeds; with it, DROP FEATURE fails with `DELTA_FEATURE_DROP_CONFLICT_REVALIDATION_FAIL`. ## Does this PR introduce _any_ user-facing changes? No. Co-authored-by: Isaac --- .../main/scala/org/apache/spark/sql/delta/TableFeature.scala | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala b/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala index b83a71883af..878da0ce685 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/TableFeature.scala @@ -924,7 +924,10 @@ object DeletionVectorsTableFeature */ override def validateDropInvariants(table: DeltaTableV2, snapshot: Snapshot): Boolean = { val dvsWritable = DeletionVectorUtils.deletionVectorsWritable(snapshot) - val dvsExist = snapshot.numDeletionVectorsOpt.getOrElse(0L) > 0 + // Log replay counts DVs only while DVs are writable. After DROP FEATURE turns DVs off, the DV + // count is known only from a checksum, and a RESTORE commit can have none. + val dvsExist = snapshot.numDeletionVectorsOpt.map(_ > 0) + .getOrElse(!DeletionVectorUtils.isTableDVFree(snapshot)) !(dvsWritable || dvsExist) } From ba79b1b4782d074efcc9ec3d0e26d4ff1da36dec Mon Sep 17 00:00:00 2001 From: Sumeet Varma Date: Tue, 17 Nov 2026 10:48:03 -0800 Subject: [PATCH 23/44] [Spark] Reject DROP COLUMNS of a struct that holds a clustering column (#8194) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description A clustered table can be clustered by a field inside a struct, for example `a.b`. DROP COLUMNS rejects a drop of a clustering column, but it compares only whole names. `DROP COLUMNS (a)` drops the struct `a`, and `a.b` with it. The check misses that, because `"a"` is not `"a.b"`. The table is then clustered by a column that is gone, and later writes, DESCRIBE DETAIL and OPTIMIZE fail with `DELTA_CANNOT_RESOLVE_CLUSTERING_COLUMN`. The check now also rejects a drop of a struct that holds a clustering column: it matches when the name parts of a dropped column are a prefix of the name parts of a clustering column. ## How was this patch tested? New test in `ClusteredTableDDLSuite`: on a table clustered by `a.b`, `DROP COLUMNS (a)`, `(A)` and `(a.b)` fail with `DELTA_UNSUPPORTED_DROP_CLUSTERING_COLUMN`, and `DROP COLUMNS (a.c)` succeeds and keeps `a.b` as the clustering column. ## Does this PR introduce _any_ user-facing changes? Yes. `DROP COLUMNS` of a struct that holds a clustering column now fails with `DELTA_UNSUPPORTED_DROP_CLUSTERING_COLUMN`. Before, it succeeded and left the table clustered by a missing column. --- .../commands/alterDeltaTableCommands.scala | 6 ++++- .../clustering/ClusteredTableDDLSuite.scala | 22 +++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala index 5b2999b87aa..7d5ca29d9be 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/alterDeltaTableCommands.scala @@ -728,7 +728,11 @@ case class AlterTableDropColumnsDeltaCommand( } // Disallow dropping clustering columns. val clusteringCols = ClusteringColumnInfo.extractLogicalNames(txn.snapshot) - val droppingClusteringCols = clusteringCols.filter(droppedColumnSet.contains(_)) + // Dropping a struct drops the clustering columns nested in it. + val droppingClusteringCols = clusteringCols.filter { clusteringCol => + val clusteringColParts = UnresolvedAttribute.parseAttributeName(clusteringCol) + columnsToDrop.exists(clusteringColParts.startsWith(_)) + } if (droppingClusteringCols.nonEmpty) { throw DeltaErrors.dropClusteringColumnNotSupported(droppingClusteringCols) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala index f636375af5c..b6cdf8082d1 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala @@ -567,6 +567,7 @@ trait ClusteredTableDDLWithColumnMapping "validate dropping clustering column is not allowed: multiple clustering columns", "validate dropping clustering column is not allowed: clustering column + " + "non-clustering column", + "validate dropping clustering column is not allowed: struct of a nested clustering column", "validate RESTORE on clustered table" ) @@ -614,6 +615,27 @@ trait ClusteredTableDDLWithColumnMapping ) } } + + test("validate dropping clustering column is not allowed: struct of a nested clustering column") { + val testTable = this.testTable + withSQLConf(DeltaSQLConf.DELTA_ALTER_TABLE_DROP_COLUMN_ENABLED.key -> "true") { + withClusteredTable(testTable, "id INT, a STRUCT", "a.b") { + Seq("a", "A", "a.b").foreach { droppedColumn => + val e = intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE $testTable DROP COLUMNS ($droppedColumn)") + } + checkError( + e, + "DELTA_UNSUPPORTED_DROP_CLUSTERING_COLUMN", + parameters = Map("columnList" -> "a.b") + ) + } + sql(s"ALTER TABLE $testTable DROP COLUMNS (a.c)") + val (_, snapshot) = DeltaLog.forTableWithSnapshot(spark, TableIdentifier(testTable)) + verifyClusteringColumnsInDomainMetadata(snapshot, Seq("a.b")) + } + } + } } trait ClusteredTableDDLWithColumnMappingV2Base extends ClusteredTableDDLWithColumnMapping { From 29292651b3074c8711cca088e30a9e2a727da7a2 Mon Sep 17 00:00:00 2001 From: tmaire111 <36109575+tmaire111@users.noreply.github.com> Date: Tue, 17 Nov 2026 10:58:42 -0800 Subject: [PATCH 24/44] [Spark] Make writer V2 test assertions and setup reusable (#8183) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Make `DeltaDataFrameWriterV2Suite` easier to reuse with other table providers while preserving its existing Delta expectations: - Extract partition assertions into overridable `assertPartitionedById` and `assertUnpartitioned` helpers. - Use the existing `createTableSQL` and `writeFormat` helpers in the literal-string overwrite tests instead of hardcoded provider names. - Remove an unused import. ## How was this patch tested? `git apply --check` and `git diff --check` passed. The test suite has not been run in this checkout. ## Does this PR introduce _any_ user-facing changes? No. This only refactors test scaffolding; the default assertions and provider remain unchanged. Signed-off-by: Tejas Maire <36109575+tmaire111@users.noreply.github.com> --- .../delta/DeltaDataFrameWriterV2Suite.scala | 45 +++++++++++-------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaDataFrameWriterV2Suite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaDataFrameWriterV2Suite.scala index c6d76284e7e..ade5b7a6c53 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaDataFrameWriterV2Suite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaDataFrameWriterV2Suite.scala @@ -34,7 +34,6 @@ import org.apache.spark.sql.functions._ import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.test.SharedSparkSession import org.apache.spark.sql.types.{LongType, StringType, StructType} -import org.apache.spark.util.Utils // These tests are copied from Apache Spark (minus partition by expressions) and should work exactly // the same with Delta minus some writer options @@ -74,6 +73,14 @@ trait OpenSourceDataFrameWriterV2Tests .toMap } + protected def assertPartitionedById(table: Table): Unit = { + assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + } + + protected def assertUnpartitioned(table: Table): Unit = { + assert(table.partitioning.isEmpty) + } + test("Append: basic append") { spark.sql(createTableSQL("table_name", "id bigint, data string")) @@ -309,7 +316,7 @@ trait OpenSourceDataFrameWriterV2Tests assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table).isEmpty) } @@ -328,7 +335,7 @@ trait OpenSourceDataFrameWriterV2Tests // table should not have been changed assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table).isEmpty) } @@ -346,7 +353,7 @@ trait OpenSourceDataFrameWriterV2Tests // validate the initial table assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table).isEmpty) spark.table("source2") @@ -366,7 +373,7 @@ trait OpenSourceDataFrameWriterV2Tests .add("id", LongType) .add("data", StringType) .add("even_or_odd", StringType)) - assert(replaced.partitioning.isEmpty) + assertUnpartitioned(replaced) assert(getProperties(replaced) === Map("delta.appendOnly" -> "true")) } @@ -404,7 +411,7 @@ trait OpenSourceDataFrameWriterV2Tests .add("id", LongType) .add("data", StringType) .add("even_or_odd", StringType)) - assert(replaced.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(replaced) assert(getProperties(replaced).isEmpty) } @@ -447,7 +454,7 @@ trait OpenSourceDataFrameWriterV2Tests // validate the initial table assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table).isEmpty) spark.table("source2") @@ -466,7 +473,7 @@ trait OpenSourceDataFrameWriterV2Tests .add("id", LongType) .add("data", StringType) .add("even_or_odd", StringType)) - assert(replaced.partitioning.isEmpty) + assertUnpartitioned(replaced) assert(getProperties(replaced).isEmpty) } @@ -559,7 +566,7 @@ class DeltaDataFrameWriterV2Suite case OverwriteApi.DATAFRAME_WRITER_V2 => replacement.writeTo("table_name").overwrite(expr(predicate)) case OverwriteApi.REPLACE_WHERE_OPTION => - replacement.write.format("delta").mode("overwrite") + replacement.write.format(writeFormat).mode("overwrite") .option("replaceWhere", predicate).saveAsTable("table_name") } } @@ -582,7 +589,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: startsWith percent ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "%first"), (2, "%second"), (3, "plain"), (4, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "%first")).toDF("id", "value") @@ -603,7 +610,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: endsWith underscore ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "first_"), (2, "second_"), (3, "plain"), (4, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "first_")).toDF("id", "value") @@ -624,7 +631,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: contains backslash ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "a\\b"), (2, "c\\d"), (3, "plain"), (4, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "a\\b")).toDF("id", "value") @@ -653,7 +660,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: contains percent ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "%first"), (2, "second%"), (3, "plain"), (4, ""), (5, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "%new")).toDF("id", "value") @@ -674,7 +681,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: mixed incoming rows ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "%old"), (2, "plain"), (3, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "%new"), (11, "plain")).toDF("id", "value") @@ -705,7 +712,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: brackets and braces ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "[a]"), (2, "a{2}"), (3, "[a-c]"), (4, "[^a]"), (5, "^"), (6, "-"), (20, "a"), (21, "aa"), (22, "b"), (23, "c"), (24, "plain")) .toDF("id", "value").writeTo("table_name").append() @@ -729,7 +736,7 @@ class DeltaDataFrameWriterV2Suite test(s"Overwrite: literal string predicates: LIKE prefix wildcard ($api, enabled=$enabled)") { withLiteralStringPredicateConf(enabled) { withTable("table_name") { - spark.sql("CREATE TABLE table_name (id int, value string) USING delta") + spark.sql(createTableSQL("table_name", "id int, value string")) Seq((1, "alice"), (2, "a%b"), (3, "a_b"), (4, "a"), (5, "plain"), (6, null)) .toDF("id", "value").writeTo("table_name").append() val replacement = Seq((10, "anna")).toDF("id", "value") @@ -793,7 +800,7 @@ class DeltaDataFrameWriterV2Suite assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table) === Map("delta.appendOnly" -> "true")) } @@ -811,7 +818,7 @@ class DeltaDataFrameWriterV2Suite // validate the initial table assert(table.name === s"${catalogPrefix}default.table_name") assert(table.schema === new StructType().add("id", LongType).add("data", StringType)) - assert(table.partitioning === Seq(IdentityTransform(FieldReference("id")))) + assertPartitionedById(table) assert(getProperties(table).isEmpty) spark.table("source2").where("false") @@ -831,7 +838,7 @@ class DeltaDataFrameWriterV2Suite .add("id", LongType) .add("data", StringType) .add("even_or_odd", StringType)) - assert(replaced.partitioning.isEmpty) + assertUnpartitioned(replaced) assert(getProperties(replaced) === Map("delta.appendOnly" -> "true")) } From 44ddab5c0e43680e8354470db5b9c8c31881f5b1 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Tue, 17 Nov 2026 15:08:20 -0500 Subject: [PATCH 25/44] [Spark][DEDUP] Drop the redundant DeltaV2ScanBuilder.create factory (#8121) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description `DeltaV2ScanUtils.newScanBuilder` was a pass-through to `DeltaV2ScanBuilder.create`, which only derived the snapshot manager from the table manager (`tableManager.snapshotManager(catalogTable)`) and called the `DeltaV2ScanBuilder` constructor. Two factory layers did one job. This PR removes the extra layer: - `DeltaV2ScanUtils.newScanBuilder` now constructs the `DeltaV2ScanBuilder` directly, with the same arguments `create` used. It stays the single entry point because `DeltaV2ScanBuilder` is `private[read]` and its production caller, `DeltaV2Table`, lives in another package. It also returns only the `ScanBuilder` interface. - `DeltaV2ScanBuilder.create` is deleted. - `DeltaV2ScanBuilderTest` now builds its scan builder through `DeltaV2ScanUtils.newScanBuilder`, the same path `DeltaV2Table` uses. This is a pure refactor with no behavior change. ## How was this patch tested? Existing tests: - `build/sbt "sparkV2/Test/javafmtCheck" "sparkV2/javafmtCheckAll"` passes. - `build/sbt "sparkV2/testOnly org.apache.spark.sql.delta.v2.read.DeltaV2ScanBuilderTest org.apache.spark.sql.delta.v2.read.DeltaV2ScanTest"` passes all 120 test cases: 35 in `DeltaV2ScanBuilderTest` and 85 in `DeltaV2ScanTest`. ## Does this PR introduce _any_ user-facing changes? No. This pull request and its description were written by Isaac. Signed-off-by: tdas Co-authored-by: Isaac Co-authored-by: omnigent --- .../delta/v2/read/DeltaV2ScanBuilder.scala | 24 ------------------- .../sql/delta/v2/read/DeltaV2ScanUtils.scala | 8 +++---- .../delta/v2/read/DeltaV2ScanBuilderTest.java | 23 +++++++++--------- 3 files changed, 16 insertions(+), 39 deletions(-) diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala index 0a10af51e9c..e4a7f21d031 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala @@ -266,30 +266,6 @@ private[read] object DeltaV2ScanBuilder { case a: AttributeReference => a.withExprId(ExprId(0L)).withQualifier(Nil) } - def create( - tableName: String, - initialSnapshot: Snapshot, - kernelEngine: Engine, - catalogTable: Option[CatalogTable], - tableManager: DeltaV2TableManager, - dataSchema: StructType, - partitionSchema: StructType, - tableSchema: StructType, - catalogStats: Option[Statistics], - options: CaseInsensitiveStringMap): DeltaV2ScanBuilder = - new DeltaV2ScanBuilder( - tableName = tableName, - initialSnapshot = initialSnapshot, - kernelEngine = kernelEngine, - catalogTable = catalogTable, - snapshotManager = tableManager.snapshotManager(catalogTable), - tableManager = Some(tableManager), - dataSchema = dataSchema, - partitionSchema = partitionSchema, - tableSchema = tableSchema, - catalogStats = catalogStats, - options = options) - /** * Adapter for callers that hold a Kernel snapshot but push no filters -- currently Delta Sharing * DSv2, whose batch scan builds a full-table read (filter pushdown is a follow-up milestone). diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanUtils.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanUtils.scala index 13677bc44e2..f1e680424b0 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanUtils.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanUtils.scala @@ -46,17 +46,17 @@ object DeltaV2ScanUtils { tableSchema: StructType, catalogStats: Option[Statistics], options: CaseInsensitiveStringMap): ScanBuilder = { - DeltaV2ScanBuilder.create( + new DeltaV2ScanBuilder( tableName = tableName, initialSnapshot = initialSnapshot, kernelEngine = kernelEngine, catalogTable = catalogTable, - tableManager = tableManager, + snapshotManager = tableManager.snapshotManager(catalogTable), + tableManager = Some(tableManager), dataSchema = dataSchema, partitionSchema = partitionSchema, tableSchema = tableSchema, catalogStats = catalogStats, - options = options - ) + options = options) } } diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java index 2de0114f051..b7f481b85c6 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java @@ -548,17 +548,18 @@ private DeltaV2ScanBuilder newScanBuilder( DeltaV2TableManager tableManager = DeltaV2TableManagerCache$.MODULE$.forTable( spark, path, Collections.emptyMap(), Option.empty()); - return DeltaV2ScanBuilder.create( - tableName, - snapshot, - engine, - Option.empty(), - tableManager, - dataSchema, - partitionSchema, - tableSchema, - Option.empty(), - CaseInsensitiveStringMap.empty()); + return (DeltaV2ScanBuilder) + DeltaV2ScanUtils.newScanBuilder( + tableName, + snapshot, + engine, + Option.empty(), + tableManager, + dataSchema, + partitionSchema, + tableSchema, + Option.empty(), + CaseInsensitiveStringMap.empty()); } // Limit Pushdown Tests From 3b1bb78574d65ec7b7b337956ec807312e95f9b8 Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Tue, 17 Nov 2026 15:15:49 -0500 Subject: [PATCH 26/44] [Spark][DEDUP] Clarify partition-only guarantee for pushed limits (#8118) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Clarify that the limit-aware scan receives partition-only filters because `build()` only sets `effectiveLimit` when there are no residual data filters. ## How was this patch tested? - `sparkV2/Compile/compileIncremental` - `sparkV2/Compile/javafmtCheckAll` - `sparkV2/Compile/scalafmtCheckAll` (blocked by pre-existing formatting failures) ## Does this PR introduce _any_ user-facing changes? No. Signed-off-by: tdas --- .../apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala index e4a7f21d031..de39a0fedaf 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala @@ -208,8 +208,9 @@ private[read] class DeltaV2ScanBuilder( val snapshot = initialSnapshot.asInstanceOf[DeltaV2Snapshot] // When a limit is pushed, route selection through V1's limit-aware filesForScan. It - // requires partition-only filters and prunes files by accumulating record counts until the - // limit is satisfied. + // requires partition-only filters (guaranteed by build(): effectiveLimit is only set when + // there are no residual data filters) and prunes files by accumulating record counts until + // the limit is satisfied. def selectFiles(): DeltaScan = if (effectiveLimit.isPresent) { recordFrameProfile("filesForScan.limitAndFilters") { From cdb19155f32ee2b07be7c613a53f7a271e548261 Mon Sep 17 00:00:00 2001 From: Eric Tseng Date: Tue, 17 Nov 2026 14:04:02 -0800 Subject: [PATCH 27/44] [Spark] Cover catalog-managed coordinator failures in transaction tests (#8202) ## Summary - Run coordinator retry and `commitLarge` failure tests against catalog-managed Delta tables. - Preserve the retry limits, exception checks, and failure telemetry assertions. - Remove a legacy property-based commit-directory test and mark four coordinator cases as expected failures in the V2 interop suite. ## Testing - `git diff --check` - Focused sbt test could not start because the sbt launcher download failed in the local checkout. Public CI will run the suite. Signed-off-by: Eric Tseng <52102337+EricTsengTy@users.noreply.github.com> --- .../DeltaV2OptimisticTransactionSuite.scala | 5 + .../delta/OptimisticTransactionSuite.scala | 249 +++++++++--------- 2 files changed, 134 insertions(+), 120 deletions(-) diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2OptimisticTransactionSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2OptimisticTransactionSuite.scala index 56b0dfc5861..66a2b7f6f76 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2OptimisticTransactionSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/v2/interop/DeltaV2OptimisticTransactionSuite.scala @@ -81,6 +81,11 @@ class DeltaV2OptimisticTransactionSuite "partition column changes allowed for CLONE operations" , "partition column changes allowed for RenameColumn when partition column renamed" + , + "Limited retries for non-conflict retryable CommitFailedExceptions", + "No retries for FileAlreadyExistsException with commit-coordinator", + "commitLarge should handle Commit Failed Exception with conflict: true", + "commitLarge should handle Commit Failed Exception with conflict: false" ) override protected def shouldFail(testName: String): Boolean = shouldFailTests.contains(testName) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala index 25d1904ffb5..fe738ffecd7 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala @@ -30,7 +30,7 @@ import org.apache.spark.sql.delta.DeltaOperations.{ManualUpdate, Truncate} import org.apache.spark.sql.delta.DeltaTestUtils.createTestAddFile import org.apache.spark.sql.delta.RowId.RowTrackingMetadataDomain import org.apache.spark.sql.delta.actions.{Action, AddCDCFile, AddFile, CommitInfo, DomainMetadata, Metadata, Protocol, RemoveFile, SetTransaction} -import org.apache.spark.sql.delta.coordinatedcommits.{CommitCoordinatorBuilder, CommitCoordinatorProvider, InMemoryCommitCoordinator, InMemoryCommitCoordinatorBuilder, TableCommitCoordinatorClient} +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorBuilder, CatalogOwnedCommitCoordinatorProvider, CatalogOwnedTableUtils, CommitCoordinatorProvider, InMemoryCommitCoordinator} import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.test.DeltaTestImplicits._ import org.apache.spark.sql.delta.util.{FileNames, JsonUtils} @@ -447,37 +447,6 @@ class OptimisticTransactionSuite } } - test("enabling Coordinated Commits on an existing table should create commit dir") { - withTempDir { tempDir => - val log = DeltaLog.forTable(spark, new Path(tempDir.getAbsolutePath)) - val metadata = Metadata() - log.startTransaction().commit(Seq(metadata), ManualUpdate) - val fs = log.logPath.getFileSystem(log.newDeltaHadoopConf()) - val commitDir = FileNames.commitDirPath(log.logPath) - // Delete commit directory. - fs.delete(commitDir) - assert(!fs.exists(commitDir)) - // With no Coordinated Commits conf, commit directory should not be created. - log.startTransaction().commit(Seq(metadata), ManualUpdate) - assert(!fs.exists(commitDir)) - // Enabling Coordinated Commits on an existing table should create the commit dir. - CommitCoordinatorProvider.registerBuilder(InMemoryCommitCoordinatorBuilder(3)) - val newMetadata = metadata.copy(configuration = - (metadata.configuration ++ - Map(DeltaConfigs.COORDINATED_COMMITS_COORDINATOR_NAME.key -> "in-memory")).toMap) - log.startTransaction().commit(Seq(newMetadata), ManualUpdate) - assert(fs.exists(commitDir)) - log.update().ensureCommitFilesBackfilled() - // With no new Coordinated Commits conf, commit directory should not be created and so the - // transaction should fail because of corrupted dir. - fs.delete(commitDir) - assert(!fs.exists(commitDir)) - intercept[java.io.FileNotFoundException] { - log.startTransaction().commit(Seq(newMetadata), ManualUpdate) - } - } - } - test("concurrent feature enablement with failConcurrentTransactionsAtUpgrade should conflict") { withSQLConf( DeltaSQLConf.DELTA_CONFLICT_CHECKER_ENFORCE_FEATURE_ENABLEMENT_VALIDATION.key -> "true") { @@ -736,7 +705,8 @@ class OptimisticTransactionSuite val initialNonConflictErrors = 5 val initialConflictErrors = 5 - object RetryableNonConflictCommitCoordinatorBuilder$ extends CommitCoordinatorBuilder { + object RetryableNonConflictCommitCoordinatorBuilder$ + extends CatalogOwnedCommitCoordinatorBuilder { override def getName: String = commitCoordinatorName @@ -771,24 +741,35 @@ class OptimisticTransactionSuite override def build( spark: SparkSession, conf: Map[String, String]): CommitCoordinatorClient = commitCoordinatorClient + override def buildForCatalog( + spark: SparkSession, + catalogName: String): CommitCoordinatorClient = commitCoordinatorClient } - CommitCoordinatorProvider.registerBuilder(RetryableNonConflictCommitCoordinatorBuilder$) - - withSQLConf( - DeltaSQLConf.DELTA_MAX_RETRY_COMMIT_ATTEMPTS.key -> numRetries, - DeltaSQLConf.DELTA_MAX_NON_CONFLICT_RETRY_COMMIT_ATTEMPTS.key -> numNonConflictRetries) { - withTempDir { tempDir => - val log = DeltaLog.forTable(spark, new Path(tempDir.getCanonicalPath)) - val conf = - Map(DeltaConfigs.COORDINATED_COMMITS_COORDINATOR_NAME.key -> commitCoordinatorName) - log.startTransaction().commit(Seq(Metadata(configuration = conf)), ManualUpdate) - val testTxn = log.startTransaction() - intercept[CommitFailedException] { testTxn.commit(Seq.empty, ManualUpdate) } - // num-attempts = 1 + num-retries - assert(commitAttempts == - (initialNonConflictErrors + initialConflictErrors + numNonConflictRetries.toInt + 1)) + CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, + RetryableNonConflictCommitCoordinatorBuilder$) + try { + withSQLConf( + DeltaSQLConf.DELTA_MAX_RETRY_COMMIT_ATTEMPTS.key -> numRetries, + DeltaSQLConf.DELTA_MAX_NON_CONFLICT_RETRY_COMMIT_ATTEMPTS.key -> numNonConflictRetries) { + withTable("retryable_catalog_owned") { + sql(s"CREATE TABLE retryable_catalog_owned (id BIGINT) USING delta TBLPROPERTIES " + + s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + val catalogTable = spark.sessionState.catalog.getTableMetadata( + TableIdentifier("retryable_catalog_owned")) + val log = DeltaLog.forTable(spark, catalogTable) + assert(log.update(catalogTableOpt = Some(catalogTable)).isCatalogOwned) + val testTxn = log.startTransaction(catalogTableOpt = Some(catalogTable)) + intercept[CommitFailedException] { testTxn.commit(Seq.empty, ManualUpdate) } + // num-attempts = 1 + num-retries + assert(commitAttempts == + (initialNonConflictErrors + initialConflictErrors + numNonConflictRetries.toInt + 1)) + } } + } finally { + CatalogOwnedCommitCoordinatorProvider.clearBuilders() } } @@ -796,7 +777,7 @@ class OptimisticTransactionSuite val commitCoordinatorName = "file-already-exists-commit-coordinator" var commitAttempts = 0 - object FileAlreadyExistsCommitCoordinatorBuilder extends CommitCoordinatorBuilder { + object FileAlreadyExistsCommitCoordinatorBuilder extends CatalogOwnedCommitCoordinatorBuilder { override def getName: String = commitCoordinatorName @@ -827,25 +808,36 @@ class OptimisticTransactionSuite override def build( spark: SparkSession, conf: Map[String, String]): CommitCoordinatorClient = commitCoordinatorClient + override def buildForCatalog( + spark: SparkSession, + catalogName: String): CommitCoordinatorClient = commitCoordinatorClient } - CommitCoordinatorProvider.registerBuilder(FileAlreadyExistsCommitCoordinatorBuilder) - - withSQLConf( - DeltaSQLConf.DELTA_MAX_RETRY_COMMIT_ATTEMPTS.key -> "100", - DeltaSQLConf.DELTA_MAX_NON_CONFLICT_RETRY_COMMIT_ATTEMPTS.key -> "10") { - withTempDir { tempDir => - val log = DeltaLog.forTable(spark, new Path(tempDir.getCanonicalPath)) - val conf = - Map(DeltaConfigs.COORDINATED_COMMITS_COORDINATOR_NAME.key -> commitCoordinatorName) - log.startTransaction().commit(Seq(Metadata(configuration = conf)), ManualUpdate) - val testTxn = log.startTransaction() - intercept[FileAlreadyExistsException] { testTxn.commit(Seq.empty, ManualUpdate) } - // Test that there are no retries for the FileAlreadyExistsException in - // CommitCoordinatorClient.commit() - // num-attempts(1) = 1 + num-retries(0) - assert(commitAttempts == 1) + CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, + FileAlreadyExistsCommitCoordinatorBuilder) + try { + withSQLConf( + DeltaSQLConf.DELTA_MAX_RETRY_COMMIT_ATTEMPTS.key -> "100", + DeltaSQLConf.DELTA_MAX_NON_CONFLICT_RETRY_COMMIT_ATTEMPTS.key -> "10") { + withTable("file_exists_catalog_owned") { + sql(s"CREATE TABLE file_exists_catalog_owned (id BIGINT) USING delta TBLPROPERTIES " + + s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + val catalogTable = spark.sessionState.catalog.getTableMetadata( + TableIdentifier("file_exists_catalog_owned")) + val log = DeltaLog.forTable(spark, catalogTable) + assert(log.update(catalogTableOpt = Some(catalogTable)).isCatalogOwned) + val testTxn = log.startTransaction(catalogTableOpt = Some(catalogTable)) + intercept[FileAlreadyExistsException] { testTxn.commit(Seq.empty, ManualUpdate) } + // Test that there are no retries for the FileAlreadyExistsException in + // CommitCoordinatorClient.commit() + // num-attempts(1) = 1 + num-retries(0) + assert(commitAttempts == 1) + } } + } finally { + CatalogOwnedCommitCoordinatorProvider.clearBuilders() } } @@ -1277,67 +1269,84 @@ class OptimisticTransactionSuite BOOLEAN_DOMAIN.foreach { conflict => test(s"commitLarge should handle Commit Failed Exception with conflict: $conflict") { - withTempDir { tempDir => - val deltaLog = DeltaLog.forTable(spark, tempDir.getAbsolutePath) - val commitCoordinatorName = "retryable-conflict-commit-coordinator" - class RetryableConflictCommitCoordinatorClient - extends InMemoryCommitCoordinator(batchSize = 5) { - override def commit( - logStore: LogStore, - hadoopConf: Configuration, - tableDesc: TableDescriptor, - commitVersion: Long, - actions: java.util.Iterator[String], - updatedActions: UpdatedActions): CommitResponse = { - if (updatedActions.getCommitInfo.asInstanceOf[CommitInfo].operation - == DeltaOperations.OP_RESTORE) { - deltaLog.startTransaction().commit(addB :: Nil, ManualUpdate) - throw new CommitFailedException(true, conflict, "") + val tableName = "commit_large_catalog_owned" + CatalogOwnedCommitCoordinatorProvider.clearBuilders() + try { + withTable(tableName) { + lazy val catalogTable = spark.sessionState.catalog.getTableMetadata( + TableIdentifier(tableName)) + lazy val deltaLog = DeltaLog.forTable(spark, catalogTable) + val commitCoordinatorName = "retryable-conflict-commit-coordinator" + class RetryableConflictCommitCoordinatorClient + extends InMemoryCommitCoordinator(batchSize = 5) { + override def commit( + logStore: LogStore, + hadoopConf: Configuration, + tableDesc: TableDescriptor, + commitVersion: Long, + actions: java.util.Iterator[String], + updatedActions: UpdatedActions): CommitResponse = { + if (updatedActions.getCommitInfo.asInstanceOf[CommitInfo].operation + == DeltaOperations.OP_RESTORE) { + deltaLog.startTransaction(catalogTableOpt = Some(catalogTable)) + .commit(addB :: Nil, ManualUpdate) + throw new CommitFailedException(true, conflict, "") + } + super.commit(logStore, hadoopConf, tableDesc, commitVersion, actions, updatedActions) } - super.commit(logStore, hadoopConf, tableDesc, commitVersion, actions, updatedActions) } - } - object RetryableConflictCommitCoordinatorBuilder$ extends CommitCoordinatorBuilder { - lazy val commitCoordinatorClient = new RetryableConflictCommitCoordinatorClient() - override def getName: String = commitCoordinatorName - override def build( - spark: SparkSession, - conf: Map[String, String]): CommitCoordinatorClient = commitCoordinatorClient - } - CommitCoordinatorProvider.registerBuilder(RetryableConflictCommitCoordinatorBuilder$) - val conf = - Map(DeltaConfigs.COORDINATED_COMMITS_COORDINATOR_NAME.key -> commitCoordinatorName) - deltaLog.startTransaction().commit(Seq(Metadata(configuration = conf)), ManualUpdate) - deltaLog.startTransaction().commit(addA :: Nil, ManualUpdate) - val records = Log4jUsageLogger.track { - // commitLarge must fail because of a conflicting commit at version-2. - val e = intercept[Exception] { - deltaLog.startTransaction().commitLarge( - spark, - nonProtocolMetadataActions = (addB :: Nil).iterator, - newProtocolOpt = None, - op = DeltaOperations.Restore(Some(0), None), - context = Map.empty, - metrics = Map.empty, - dataChange = true) + object RetryableConflictCommitCoordinatorBuilder$ + extends CatalogOwnedCommitCoordinatorBuilder { + lazy val commitCoordinatorClient = new RetryableConflictCommitCoordinatorClient() + override def getName: String = commitCoordinatorName + override def build( + spark: SparkSession, + conf: Map[String, String]): CommitCoordinatorClient = commitCoordinatorClient + override def buildForCatalog( + spark: SparkSession, + catalogName: String): CommitCoordinatorClient = commitCoordinatorClient } - if (conflict) { - assert(e.isInstanceOf[ConcurrentWriteException]) - assert( - e.getMessage.contains( - "A concurrent transaction has written new data since the current transaction " + - s"read the table. Please try the operation again")) - } else { + CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, + RetryableConflictCommitCoordinatorBuilder$) + sql(s"CREATE TABLE $tableName (id BIGINT) USING delta TBLPROPERTIES " + + s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + assert(deltaLog.update(catalogTableOpt = Some(catalogTable)).isCatalogOwned) + deltaLog.startTransaction(catalogTableOpt = Some(catalogTable)) + .commit(addA :: Nil, ManualUpdate) + val records = Log4jUsageLogger.track { + // commitLarge must fail because of a conflicting commit at version-2. + val e = intercept[Exception] { + deltaLog.startTransaction(catalogTableOpt = Some(catalogTable)) + .commitLarge( + spark, + nonProtocolMetadataActions = (addB :: Nil).iterator, + newProtocolOpt = None, + op = DeltaOperations.Restore(Some(0), None), + context = Map.empty, + metrics = Map.empty, + dataChange = true) + } + if (conflict) { + assert(e.isInstanceOf[ConcurrentWriteException]) + assert( + e.getMessage.contains( + "A concurrent transaction has written new data since the current transaction " + + s"read the table. Please try the operation again")) + } else { assert(e.isInstanceOf[CommitFailedException]) + } + assert(deltaLog.update(catalogTableOpt = Some(catalogTable)).version == 2) } - assert(deltaLog.update().version == 2) + val failureRecord = filterUsageRecords(records, "delta.commitLarge.failure") + assert(failureRecord.size == 1) + val data = JsonUtils.fromJson[Map[String, Any]](failureRecord.head.blob) + assert(data("fromCoordinatedCommits") == true) + assert(data("fromCoordinatedCommitsConflict") == conflict) + assert(data("fromCoordinatedCommitsRetryable") == true) } - val failureRecord = filterUsageRecords(records, "delta.commitLarge.failure") - assert(failureRecord.size == 1) - val data = JsonUtils.fromJson[Map[String, Any]](failureRecord.head.blob) - assert(data("fromCoordinatedCommits") == true) - assert(data("fromCoordinatedCommitsConflict") == conflict) - assert(data("fromCoordinatedCommitsRetryable") == true) + } finally { + CatalogOwnedCommitCoordinatorProvider.clearBuilders() } } } From 15b622a40c0a240ddc180ab6998ea0c261b52f64 Mon Sep 17 00:00:00 2001 From: Zihao Xu Date: Tue, 17 Nov 2026 15:57:05 -0800 Subject: [PATCH 28/44] [Spark] Rename CatalogOwnedCommitCoordinator* to CatalogManagedCommitCoordinator* (#8153) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Stacked on #8157; review the last commit. Renames `CatalogOwnedCommitCoordinatorBuilder` and `CatalogOwnedCommitCoordinatorProvider` to `CatalogManagedCommitCoordinatorBuilder` and `CatalogManagedCommitCoordinatorProvider`. The `coordinatedcommits` package object keeps both old names as aliases. ## How was this patch tested? Rename only, no new tests. Apart from the aliases and the line wrapping, every changed token is an old name changed to the new one. ## Does this PR introduce _any_ user-facing changes? No. --- .../CommitCoordinatorClient.scala | 14 ++++----- .../CoordinatedCommitsUtils.scala | 4 +-- .../UCCommitCoordinatorBuilder.scala | 2 +- .../delta/coordinatedcommits/package.scala | 3 ++ .../sql/delta/DeltaProtocolVersionSuite.scala | 4 +-- .../sql/delta/DeltaTableFeatureSuite.scala | 8 ++--- .../sql/delta/InCommitTimestampSuite.scala | 6 ++-- .../spark/sql/delta/amt/AMTDMLTestUtils.scala | 6 ++-- .../spark/sql/delta/amt/UpdateAMTMixin.scala | 4 +-- .../CatalogOwnedEnablementSuite.scala | 4 +-- .../CoordinatedCommitsSuite.scala | 2 +- .../CoordinatedCommitsTestUtils.scala | 30 +++++++++---------- .../sql/delta/test/DeltaSQLTestUtils.scala | 6 ++-- 13 files changed, 48 insertions(+), 45 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala index cd8d0f4639d..5cc854f8427 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CommitCoordinatorClient.scala @@ -50,7 +50,7 @@ trait CommitCoordinatorBuilder { /** * An extended builder interface for [[CommitCoordinatorClient]] with CatalogManaged table feature */ -trait CatalogOwnedCommitCoordinatorBuilder extends CommitCoordinatorBuilder { +trait CatalogManagedCommitCoordinatorBuilder extends CommitCoordinatorBuilder { /** Returns a catalog-managed commit-coordinator client based for the given catalog. */ def buildForCatalog(spark: SparkSession, catalogName: String): CommitCoordinatorClient } @@ -118,12 +118,12 @@ object CommitCoordinatorProvider { } /** - * Factory to get the correct [[CatalogOwnedCommitCoordinatorBuilder]] for a catalog-managed table + * Factory to get the correct [[CatalogManagedCommitCoordinatorBuilder]] for a catalog-managed table */ -object CatalogOwnedCommitCoordinatorProvider { - // mapping from catalog names to the corresponding [[CatalogOwnedCommitCoordinatorBuilder]]s. +object CatalogManagedCommitCoordinatorProvider { + // mapping from catalog names to the corresponding [[CatalogManagedCommitCoordinatorBuilder]]s. private val catalogNameToBuilderMapping = - mutable.Map.empty[String, CatalogOwnedCommitCoordinatorBuilder] + mutable.Map.empty[String, CatalogManagedCommitCoordinatorBuilder] // Visible only for UTs private[delta] def clearBuilders(): Unit = synchronized { @@ -132,7 +132,7 @@ object CatalogOwnedCommitCoordinatorProvider { /** Registers a new [[CommitCoordinatorBuilder]] with the [[CommitCoordinatorProvider]] */ def registerBuilder( - catalogName: String, commitCoordinatorBuilder: CatalogOwnedCommitCoordinatorBuilder): Unit = + catalogName: String, commitCoordinatorBuilder: CatalogManagedCommitCoordinatorBuilder): Unit = synchronized { catalogNameToBuilderMapping.get(catalogName) match { case Some(existingBuilder: CommitCoordinatorBuilder) => @@ -144,6 +144,6 @@ object CatalogOwnedCommitCoordinatorProvider { } } - def getBuilder(catalogName: String): Option[CatalogOwnedCommitCoordinatorBuilder] = + def getBuilder(catalogName: String): Option[CatalogManagedCommitCoordinatorBuilder] = catalogNameToBuilderMapping.get(catalogName) } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala index 1586d01fea7..08b9e862a5c 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala @@ -116,7 +116,7 @@ object CatalogManagedTableUtils extends DeltaLogging { // in-memory commit coordinator. In this case, we return table commit coordinator // registered in the provider so that it can still test CatalogManaged table feature // capability. - CatalogOwnedCommitCoordinatorProvider.getBuilder(DEFAULT_CATALOG_NAME_FOR_TESTING) + CatalogManagedCommitCoordinatorProvider.getBuilder(DEFAULT_CATALOG_NAME_FOR_TESTING) .flatMap{ builder => Some(builder.buildForCatalog(spark, DEFAULT_CATALOG_NAME_FOR_TESTING)) } @@ -144,7 +144,7 @@ object CatalogManagedTableUtils extends DeltaLogging { identifier: CatalystTableIdentifier): Option[CommitCoordinatorClient] = { identifier.nameParts match { case spark.sessionState.analyzer.CatalogAndIdentifier(catalog, _) => - CatalogOwnedCommitCoordinatorProvider.getBuilder(catalog.name) + CatalogManagedCommitCoordinatorProvider.getBuilder(catalog.name) .map(_.buildForCatalog(spark, catalog.name)).orElse { if (catalog.getClass.getName == UCCommitCoordinatorBuilder.UNITY_CATALOG_CONNECTOR_CLASS) { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/UCCommitCoordinatorBuilder.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/UCCommitCoordinatorBuilder.scala index 81a7ee65693..8284e4df21c 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/UCCommitCoordinatorBuilder.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/UCCommitCoordinatorBuilder.scala @@ -44,7 +44,7 @@ import org.apache.spark.util.Utils * It caches the UCCommitCoordinatorClient instance for a given metastore ID upon its first access. */ object UCCommitCoordinatorBuilder - extends CatalogOwnedCommitCoordinatorBuilder with DeltaLogging { + extends CatalogManagedCommitCoordinatorBuilder with DeltaLogging { /** The coordinator name used in table metadata to identify UC-managed tables. */ final val COORDINATOR_NAME: String = "unity-catalog" diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala index 9e037cf7fc6..45d3b77038d 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/package.scala @@ -19,6 +19,9 @@ package org.apache.spark.sql.delta package object coordinatedcommits { // The old names, kept until their callers use the new ones. + val CatalogOwnedCommitCoordinatorProvider: CatalogManagedCommitCoordinatorProvider.type = + CatalogManagedCommitCoordinatorProvider + type CatalogOwnedCommitCoordinatorBuilder = CatalogManagedCommitCoordinatorBuilder val CatalogOwnedTableUtils: CatalogManagedTableUtils.type = CatalogManagedTableUtils val CatalogOwnedUsageLogs: CatalogManagedUsageLogs.type = CatalogManagedUsageLogs } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala index 862b56e73a1..31a47694639 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala @@ -3799,8 +3799,8 @@ trait DeltaProtocolVersionSuiteBase extends QueryTest val featureName = VacuumProtocolCheckTableFeature.name withTempTable(createTable = false) { tableName => // Register a temporary InMemory-CC builder to support CatalogManaged table creation. - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, TrackingInMemoryCommitCoordinatorBuilder(batchSize = 1) ) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala index d10e194d82a..dac173193d7 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala @@ -24,7 +24,7 @@ import scala.collection.mutable import org.apache.spark.sql.delta.actions._ import org.apache.spark.sql.delta.actions.TableFeatureProtocolUtils._ import org.apache.spark.sql.delta.catalog.DeltaTableV2 -import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorProvider, InMemoryCommitCoordinatorBuilder} +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, InMemoryCommitCoordinatorBuilder} import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.test.DeltaSQLCommandTest import org.apache.spark.sql.delta.test.DeltaTestImplicits._ @@ -506,9 +506,9 @@ class DeltaTableFeatureSuite val table = "tbl" DeltaLog.clearCache() withTable(table) { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.clearBuilders() try { - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.registerBuilder( "spark_catalog", InMemoryCommitCoordinatorBuilder(batchSize = 100)) spark.range(0).write.format("delta") .option(propertyKey(CatalogOwnedTableFeature), "supported") @@ -562,7 +562,7 @@ class DeltaTableFeatureSuite sql(s"ALTER TABLE $table DROP FEATURE $featureName") assert(!log.update().protocol.readerAndWriterFeatureNames.contains(featureName)) } finally { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.clearBuilders() } } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala index 9fc0aef9728..693e399f599 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/InCommitTimestampSuite.scala @@ -24,7 +24,7 @@ import com.databricks.spark.util.Log4jUsageLogger import org.apache.spark.sql.delta.DeltaOperations.ManualUpdate import org.apache.spark.sql.delta.DeltaTestUtils.createTestAddFile import org.apache.spark.sql.delta.actions.{Action, CommitInfo, Metadata} -import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorProvider, +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, CatalogOwnedTableUtils, CatalogOwnedTestBaseSuite, CommitCoordinatorProvider, CommitCoordinatorUtilBase, TrackingInMemoryCommitCoordinatorBuilder} import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -1941,8 +1941,8 @@ class InCommitTimestampWithCatalogOwnedBatch5Suite extends InCommitTimestampSuit override def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = Some(5) test("getActiveCommitAtTime works correctly within catalog owned range") { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, commitCoordinatorBuilder = TrackingInMemoryCommitCoordinatorBuilder(batchSize = 10) ) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala index d41c1179744..35bac7bf951 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala @@ -18,7 +18,7 @@ package org.apache.spark.sql.delta.amt import org.apache.spark.sql.delta.{AdaptiveMetadataPreviewTableFeature, DeltaConfigs, DeltaLog, DeltaTable, DeltaTestUtils, RowCommitVersion, RowId, Snapshot} import org.apache.spark.sql.delta.actions.TableFeatureProtocolUtils._ -import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorProvider, CatalogOwnedTableUtils, TrackingInMemoryCommitCoordinatorBuilder} +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, CatalogOwnedTableUtils, TrackingInMemoryCommitCoordinatorBuilder} import org.apache.spark.sql.delta.files.TahoeLogFileIndex import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -67,9 +67,9 @@ trait AMTDMLTestUtils extends AMTCheckpointTestBase { // RowTrackingMergeSuiteBase) create catalog-managed tables in their own beforeAll(), which runs // before the beforeEach() that normally registers the coordinator. override protected def beforeAll(): Unit = { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.clearBuilders() catalogOwnedCoordinatorBackfillBatchSize.foreach { batchSize => - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, commitCoordinatorBuilder = TrackingInMemoryCommitCoordinatorBuilder(batchSize)) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/UpdateAMTMixin.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/UpdateAMTMixin.scala index c24be2433cf..8642ff3e0a7 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/UpdateAMTMixin.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/UpdateAMTMixin.scala @@ -19,7 +19,7 @@ package org.apache.spark.sql.delta.amt import scala.util.Try import org.apache.spark.sql.delta.UpdateBaseMixin -import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorProvider, CatalogOwnedTableUtils, InMemoryCommitCoordinator, TrackingCommitCoordinatorClient} +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, CatalogOwnedTableUtils, InMemoryCommitCoordinator, TrackingCommitCoordinatorClient} import org.apache.spark.sql.delta.rowid.RowTrackingUpdateSuiteBase import org.apache.spark.sql.delta.sources.DeltaSQLConf @@ -78,7 +78,7 @@ trait UpdateAMTMixin extends UpdateBaseMixin with UpdateAMTTestBase { val logPathOpt = Try(deltaLog.logPath).toOption super.dropTable() val catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING - val coordinatorOpt = CatalogOwnedCommitCoordinatorProvider.getBuilder(catalogName) + val coordinatorOpt = CatalogManagedCommitCoordinatorProvider.getBuilder(catalogName) .map(_.buildForCatalog(spark, catalogName)) .map { case tracking: TrackingCommitCoordinatorClient => tracking.delegatingCommitCoordinatorClient diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala index 6711ca265b5..5a7e3efd992 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala @@ -39,8 +39,8 @@ class CatalogOwnedEnablementSuite override protected def beforeEach(): Unit = { super.beforeEach() - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, commitCoordinatorBuilder = TrackingInMemoryCommitCoordinatorBuilder(batchSize = 3) ) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala index f10d698cea5..21b3602bce8 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsSuite.scala @@ -344,7 +344,7 @@ abstract class CommitCoordinatorSuiteBase test("0th commit happens via filesystem") { val commitCoordinatorName = "tracking-in-memory" object NoBackfillingCommitCoordinatorBuilder$ - extends CatalogOwnedCommitCoordinatorBuilder { + extends CatalogManagedCommitCoordinatorBuilder { override def getName: String = commitCoordinatorName diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala index e8bad430d74..36fdd5dbc77 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala @@ -111,7 +111,7 @@ trait CatalogOwnedTestBaseSuite */ protected def getCatalogOwnedCommitCoordinatorClient( catalogName: String): CommitCoordinatorClient = { - CatalogOwnedCommitCoordinatorProvider.getBuilder(catalogName).getOrElse { + CatalogManagedCommitCoordinatorProvider.getBuilder(catalogName).getOrElse { throw new IllegalStateException( s"Commit coordinator builder is not available for the specified catalog: $catalogName") }.buildForCatalog(spark, catalogName) @@ -126,7 +126,7 @@ trait CatalogOwnedTestBaseSuite } override def clearBuilders(): Unit = { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.clearBuilders() } override def propertiesString: String = @@ -134,9 +134,9 @@ trait CatalogOwnedTestBaseSuite override protected def beforeEach(): Unit = { super.beforeEach() - CatalogOwnedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.clearBuilders() catalogOwnedCoordinatorBackfillBatchSize.foreach { batchSize => - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.registerBuilder( catalogName = CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, commitCoordinatorBuilder = TrackingInMemoryCommitCoordinatorBuilder(batchSize) ) @@ -188,8 +188,8 @@ trait CatalogOwnedTestBaseSuite override def testWithDifferentBackfillInterval(testName: String)(f: Int => Unit): Unit = { Seq(1, 2, 10).foreach { backfillBatchSize => test(s"$testName [Backfill batch size: $backfillBatchSize]") { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( "spark_catalog", TrackingInMemoryCommitCoordinatorBuilder(batchSize = backfillBatchSize)) f(backfillBatchSize) } @@ -219,8 +219,8 @@ trait CatalogOwnedTestBaseSuite */ def testWithCatalogOwned(backfillBatchSize: Int)(testName: String)(f: => Unit): Unit = { test(s"$testName [Backfill batch size: $backfillBatchSize]") { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, TrackingInMemoryCommitCoordinatorBuilder(batchSize = backfillBatchSize)) withDefaultCCTableFeature { @@ -230,10 +230,10 @@ trait CatalogOwnedTestBaseSuite } override def registerBuilder(builder: CommitCoordinatorBuilder): Unit = { - assert(builder.isInstanceOf[CatalogOwnedCommitCoordinatorBuilder], - s"builder $builder(${builder.getName}) must be CatalogOwnedCommitCoordinatorBuilder") - CatalogOwnedCommitCoordinatorProvider.registerBuilder( - "spark_catalog", builder.asInstanceOf[CatalogOwnedCommitCoordinatorBuilder]) + assert(builder.isInstanceOf[CatalogManagedCommitCoordinatorBuilder], + s"builder $builder(${builder.getName}) must be CatalogManagedCommitCoordinatorBuilder") + CatalogManagedCommitCoordinatorProvider.registerBuilder( + "spark_catalog", builder.asInstanceOf[CatalogManagedCommitCoordinatorBuilder]) } override def isCatalogOwnedTest: Boolean = true @@ -254,9 +254,9 @@ trait CatalogOwnedTestBaseSuite def deleteCatalogOwnedTableFromCommitCoordinator(path: Path): Unit = { val catalogName = "spark_catalog" - val cc = CatalogOwnedCommitCoordinatorProvider.getBuilder(catalogName).getOrElse { + val cc = CatalogManagedCommitCoordinatorProvider.getBuilder(catalogName).getOrElse { throw new IllegalStateException( - s"Unable to get CatalogOwnedCommitCoordinatorBuilder for table at path: ${path.toString}") + s"Unable to get CatalogManagedCommitCoordinatorBuilder for table at path: ${path.toString}") }.buildForCatalog(spark, catalogName) assert( @@ -579,7 +579,7 @@ case class TrackingInMemoryCommitCoordinatorBuilder( batchSize: Long, defaultCommitCoordinatorClientOpt: Option[CommitCoordinatorClient] = None, defaultCommitCoordinatorName: String = "tracking-in-memory") - extends CatalogOwnedCommitCoordinatorBuilder { + extends CatalogManagedCommitCoordinatorBuilder { lazy val trackingInMemoryCommitCoordinatorClient = defaultCommitCoordinatorClientOpt.getOrElse { new TrackingCommitCoordinatorClient( diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala index a5973d3b5b1..492ee2c12ea 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala @@ -23,7 +23,7 @@ import scala.util.Random import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, DeltaColumnMappingTestUtilsBase, DeltaLog, DeltaTable, Snapshot, TableFeature} import org.apache.spark.sql.delta.actions.Protocol -import org.apache.spark.sql.delta.coordinatedcommits.{CatalogOwnedCommitCoordinatorProvider, CatalogOwnedTableUtils, TrackingInMemoryCommitCoordinatorBuilder} +import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, CatalogOwnedTableUtils, TrackingInMemoryCommitCoordinatorBuilder} import org.apache.spark.sql.delta.stats.{DeltaStatistics, PreparedDeltaFileIndex} import com.fasterxml.jackson.databind.{JsonNode, ObjectMapper} @@ -112,8 +112,8 @@ trait DeltaSQLTestUtils extends SQLTestUtils { * @param f The function to execute with the generated table name. */ protected def withCatalogManagedTable(createTable: Boolean = true)(f: String => Unit): Unit = { - CatalogOwnedCommitCoordinatorProvider.clearBuilders() - CatalogOwnedCommitCoordinatorProvider.registerBuilder( + CatalogManagedCommitCoordinatorProvider.clearBuilders() + CatalogManagedCommitCoordinatorProvider.registerBuilder( CatalogOwnedTableUtils.DEFAULT_CATALOG_NAME_FOR_TESTING, TrackingInMemoryCommitCoordinatorBuilder(batchSize = 3)) withTempTable(createTable = false) { tableName => From 41f79646b3edaed57665a040ec22268944573eae Mon Sep 17 00:00:00 2001 From: Cuong Nguyen Date: Tue, 17 Nov 2026 17:44:24 -0800 Subject: [PATCH 29/44] [Spark] Require isPreviewCompatible in AMTUtils.amtSupported and amtEnabled (#8205) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Adds a required `isPreviewCompatible` parameter to `AMTUtils.amtSupported` and `AMTUtils.amtEnabled`, so every caller states whether it handles `adaptiveMetadata-preview` tables. With `false`, preview tables don't count as AMT tables; `adaptiveMetadata-dev` tables behave as before. New code paths, such as `tightStats`, pass `false` so they don't run on preview tables, which older clients still read and write. Every existing caller passes `true`, so this PR doesn't change behavior. The single-argument `amtEnabled(snapshot)` overload is removed; callers use `amtEnabled(snapshot, isPreviewCompatible)`. ## How was this patch tested? `AMTUtilsSuite` checks every feature and AMT property case with the flag set to `true` and to `false`. `AdaptiveMetadataTableFeatureSuite` checks the snapshot form on real tables: with `false`, only `adaptiveMetadata-dev` tables count as AMT tables. ## Does this PR introduce _any_ user-facing changes? No. --- .../apache/spark/sql/delta/Checkpoints.scala | 4 +-- .../org/apache/spark/sql/delta/Checksum.scala | 2 +- .../spark/sql/delta/MetadataCleanup.scala | 2 +- .../sql/delta/OptimisticTransaction.scala | 7 +++-- .../org/apache/spark/sql/delta/Snapshot.scala | 6 ++-- .../spark/sql/delta/SnapshotManagement.scala | 4 +-- .../spark/sql/delta/actions/actions.scala | 4 +-- .../apache/spark/sql/delta/amt/AMTUtils.scala | 29 +++++++++++++------ .../sql/delta/amt/AMTWriterManager.scala | 10 +++---- .../apache/spark/sql/delta/amt/actions.scala | 2 +- .../sql/delta/commands/CloneTableBase.scala | 2 +- .../sql/delta/commands/VacuumCommand.scala | 5 ++-- .../sql/delta/hooks/CheckpointHook.scala | 2 +- .../spark/sql/delta/DeltaTestUtils.scala | 2 +- .../spark/sql/delta/amt/AMTDMLTestUtils.scala | 2 +- .../delta/amt/AMTSnapshotDiscoverySuite.scala | 2 +- .../spark/sql/delta/amt/AMTUtilsSuite.scala | 17 ++++++++--- .../AdaptiveMetadataTableFeatureSuite.scala | 16 ++++++++-- 18 files changed, 75 insertions(+), 43 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala b/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala index 8ef3750e8d4..85186320092 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala @@ -385,7 +385,7 @@ trait Checkpoints extends DeltaLogging { snapshotToCheckpoint: Snapshot, catalogTableOpt: Option[CatalogTable], amtTriggerModeOpt: Option[AMTTriggerMode] = None): Unit = { - if (AMTUtils.amtEnabled(snapshotToCheckpoint)) { + if (AMTUtils.amtEnabled(snapshotToCheckpoint, isPreviewCompatible = true)) { // Note: This also takes care of writing the last checkpoint file via optimistic transaction AMTWriterManager.emitAMTCheckpoint(snapshotToCheckpoint, catalogTableOpt, amtTriggerModeOpt) return @@ -800,7 +800,7 @@ trait Checkpoints extends DeltaLogging { * root makes snapshot discovery reject the table. */ protected def assertNonAMTCheckpointAllowed(snapshot: Snapshot): Unit = { - if (AMTUtils.amtEnabled(snapshot)) { + if (AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true)) { throw new IllegalStateException( s"Cannot write a non-AMT checkpoint at version ${snapshot.version} for AMT table " + s"$logPath.") diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/Checksum.scala b/spark/src/main/scala/org/apache/spark/sql/delta/Checksum.scala index 05073005fff..c4c6128424c 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/Checksum.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/Checksum.scala @@ -938,7 +938,7 @@ trait ValidateChecksum extends DeltaLogging { self: Snapshot => // AMT manifest trees do not yet round-trip every AddFile field: `DataEntry.toAddFile` zeroes // `modificationTime`, forces `dataChange = false`, drops `tags`, and reduces `stats` to // `{"numRecords":n}`. Project those lossy fields before comparing. - if (AMTUtils.amtSupported(protocol)) { + if (AMTUtils.amtSupported(protocol, isPreviewCompatible = true)) { def normalizeForAmtTreeRoundTrip(f: AddFile): AddFile = f.copy( // CRC and AMT reconstruction may use different path encodings for the same on-disk DV, // so normalize both to absolute paths before comparing. diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/MetadataCleanup.scala b/spark/src/main/scala/org/apache/spark/sql/delta/MetadataCleanup.scala index 73daac71ad3..6d7e0af73db 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/MetadataCleanup.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/MetadataCleanup.scala @@ -86,7 +86,7 @@ trait MetadataCleanup extends DeltaLogging { * a cleanup boundary that no AMT checkpoint backs and try to write a non-AMT checkpoint there. */ protected def shouldSkipMetadataCleanupForAMT(snapshotToCleanup: Snapshot): Boolean = { - val skip = AMTUtils.amtSupported(snapshotToCleanup.protocol) + val skip = AMTUtils.amtSupported(snapshotToCleanup.protocol, isPreviewCompatible = true) if (skip) { logInfo(log"Skipping metadata cleanup for AMT table " + log"${MDC(DeltaLogKeys.PATH, dataPath)}") 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 0de90f6f3d0..8c3dfe8cafa 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 @@ -1184,7 +1184,7 @@ trait OptimisticTransactionImpl extends TransactionHelper val amtFeatureName = amtFeature.name val existingTableHasAdaptiveMetadata = - AMTUtils.amtEnabled(snapshot) + AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true) // REPLACE counts as creating a new table, but it keeps the existing table and its history, so // adding AMT through it is an upgrade too. if (readVersion >= 0 && !existingTableHasAdaptiveMetadata) { @@ -1285,7 +1285,8 @@ trait OptimisticTransactionImpl extends TransactionHelper val addFileMustHaveWideBounds = op.checkAddFileWithDeletionVectorStatsAreNotTightBounds // A manifest tree cannot store inline DVs, so the next tree build would fail on such a file. - val inlineDeletionVectorDisallowed = AMTUtils.amtEnabled(metadata, protocol) + val inlineDeletionVectorDisallowed = + AMTUtils.amtEnabled(metadata, protocol, isPreviewCompatible = true) action => action match { case a: AddFile if a.deletionVector != null => @@ -3453,7 +3454,7 @@ trait OptimisticTransactionImpl extends TransactionHelper isIdempotentRetry = isIdempotentRetry) val postCommitReconstructionTime = System.nanoTime() maintenanceOperation = if ( - !AMTUtils.amtEnabled(postCommitSnapshot)) { + !AMTUtils.amtEnabled(postCommitSnapshot, isPreviewCompatible = true)) { MaintenanceOperation( shouldCheckpoint = isCheckpointNeeded(attemptVersion, postCommitSnapshot)) } else if (amtWriteResultOpt.isEmpty) { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/Snapshot.scala b/spark/src/main/scala/org/apache/spark/sql/delta/Snapshot.scala index a2aec7bd44b..94a8758e642 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/Snapshot.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/Snapshot.scala @@ -238,7 +238,7 @@ class Snapshot( /** Returns the lastManifestCommit reliably for this snapshot's version. */ lazy val lastManifestCommitOpt: Option[LastManifestCommit] = - Option.when(AMTUtils.amtSupported(protocol)) { + Option.when(AMTUtils.amtSupported(protocol, isPreviewCompatible = true)) { _reconstructedProtocolMetadataICTAndLMC.bestEffortLastManifestCommit.orElse { // Only fallback to direct CommitInfo read if there are no trailing deltas. // This avoids unnecessary I/O when there isn't any AMT checkpoint yet. @@ -517,7 +517,7 @@ class Snapshot( case _ => None } - if (!AMTUtils.amtSupported(protocol)) { + if (!AMTUtils.amtSupported(protocol, isPreviewCompatible = true)) { deltaAssert( check = amtCheckpointProviderOpt.isEmpty, name = AMTUsageLogs.AMT_CHECKPOINT_PROVIDER_WITH_FEATURE_DISABLED, @@ -1075,7 +1075,7 @@ object Snapshot extends DeltaLogging { // back-reference-free list that matches state reconstruction. // The tree is checked even when the read snapshot is not AMT because the commit that upgrades // the table to AMT can land a leaf bearing tree. - if ((AMTUtils.amtSupported(snapshot.protocol) || + if ((AMTUtils.amtSupported(snapshot.protocol, isPreviewCompatible = true) || effectiveLatestAMTCheckpointAtCommitVersion.isDefined) && !AMTUtils.isRootOnlyCheckpoint(effectiveLatestAMTCheckpointAtCommitVersion)) { return false diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/SnapshotManagement.scala b/spark/src/main/scala/org/apache/spark/sql/delta/SnapshotManagement.scala index 1130fedd0ec..84ca90a8257 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/SnapshotManagement.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/SnapshotManagement.scala @@ -1619,7 +1619,7 @@ trait SnapshotManagement { self: DeltaLog => // The supplied provider is the latest checkpoint through committedVersion. val shouldReconcileAMTCheckpointProvider = - AMTUtils.amtSupported(previousSnapshot.protocol) && + AMTUtils.amtSupported(previousSnapshot.protocol, isPreviewCompatible = true) && amtCheckpointProviderForPostCommitSnapshot.isEmpty val newSnapshot = createSnapshotAfterCommit( segment, @@ -1703,7 +1703,7 @@ trait SnapshotManagement { self: DeltaLog => // because we have the precise pointer to the last manifest commit as of the target version. // We assume that there is no AMT upgrade/downgrade for now, and if the upper-bound snapshot // is AMT-enabled, then the target version is also AMT-enabled. - case _ if AMTUtils.amtEnabled(upperBoundSnapshot) => + case _ if AMTUtils.amtEnabled(upperBoundSnapshot, isPreviewCompatible = true) => computeLastCheckpointHintsForAMT(version, upperBoundSnapshot) case _ => val lastCheckpointInfoForListing = lastCheckpointHint diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala b/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala index cf72b593f92..542b8359f36 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/actions/actions.scala @@ -981,7 +981,7 @@ object FileAction { metadata: Metadata, protocol: Protocol, spark: SparkSession): Boolean = - AMTUtils.amtSupported(protocol) || + AMTUtils.amtSupported(protocol, isPreviewCompatible = true) || spark.conf.get(DeltaSQLConf.DELETION_VECTORS_USE_OBJECT_IDENTITY_FOR_NON_AMT) /** @@ -1855,7 +1855,7 @@ object CommitInfo { metadata: Metadata, protocol: Protocol, spark: SparkSession): Option[Boolean] = { - if (AMTUtils.amtEnabled(metadata, protocol) || + if (AMTUtils.amtEnabled(metadata, protocol, isPreviewCompatible = true) || spark.conf.get(DeltaSQLConf.DELTA_COMMIT_INFO_DATA_CHANGE_WRITE_FOR_NON_AMT_ENABLED)) { Some(dataChange) } else { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala index 51ca8714a01..f52120b4831 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala @@ -39,26 +39,37 @@ object AMTUtils extends DeltaLogging { /** * Whether AMT is **supported** as per the protocol. Code that reads or keeps AMT state (trees, * back references, `r` DVs) checks this, because that state stays while AMT writes are off. + * + * `isPreviewCompatible` says whether the caller also handles private-preview AMT tables, that + * is, tables with [[AdaptiveMetadataPreviewTableFeature]]. Only code paths that predate + * [[AdaptiveMetadataTableFeature]] may treat preview tables as AMT tables; those callers pass + * `true`. New code paths pass `false` and only see tables with [[AdaptiveMetadataTableFeature]]. */ - def amtSupported(protocol: Protocol): Boolean = - AdaptiveMetadataTableFeatureBase.isSupportedBy(protocol) + def amtSupported(protocol: Protocol, isPreviewCompatible: Boolean): Boolean = + AdaptiveMetadataTableFeatureBase.supportedBy(protocol) match { + case Some(AdaptiveMetadataPreviewTableFeature) => isPreviewCompatible + case Some(AdaptiveMetadataTableFeature) => true + case None => false + } /** * Whether AMT (Adaptive Metadata Tree) writes are enabled for a table with this `protocol` and - * `metadata`. + * `metadata`. See [[amtSupported]] for `isPreviewCompatible`. */ - def amtEnabled(metadata: Metadata, protocol: Protocol): Boolean = + def amtEnabled(metadata: Metadata, protocol: Protocol, isPreviewCompatible: Boolean): Boolean = AdaptiveMetadataTableFeatureBase.supportedBy(protocol) match { // Preview tables were created before the AMT property existed. - case Some(AdaptiveMetadataPreviewTableFeature) => true + case Some(AdaptiveMetadataPreviewTableFeature) => isPreviewCompatible case Some(AdaptiveMetadataTableFeature) => DeltaConfigs.ADAPTIVE_METADATA_ENABLED.fromMetaData(metadata) case None => false } - /** Whether AMT writes are enabled for `snapshot`. */ - def amtEnabled(snapshot: SnapshotDescriptor): Boolean = - amtEnabled(snapshot.metadata, snapshot.protocol) + /** + * Whether AMT writes are enabled for `snapshot`. See [[amtSupported]] for `isPreviewCompatible`. + */ + def amtEnabled(snapshot: SnapshotDescriptor, isPreviewCompatible: Boolean): Boolean = + amtEnabled(snapshot.metadata, snapshot.protocol, isPreviewCompatible) /** * Whether `amtCheckpointOpt` holds a ROOT-ONLY tree (no leaf manifests). A root-only tree keeps @@ -111,7 +122,7 @@ object AMTUtils extends DeltaLogging { amtFeatures.foreach { amtFeature => // Adding AMT to an existing table is an unsupported upgrade. `updateMetadata` already rejects // it, but CLONE adds the source's protocol after that, so REPLACE CLONE is caught here. - if (snapshot.version >= 0 && !amtSupported(snapshot.protocol)) { + if (snapshot.version >= 0 && !amtSupported(snapshot.protocol, isPreviewCompatible = true)) { throw DeltaErrors.adaptiveMetadataUpgradeNotSupported(amtFeature.name) } val creationConf = AdaptiveMetadataTableFeatureBase.creationConf(amtFeature) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala index b58432247cb..35f7b7269c0 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala @@ -335,7 +335,7 @@ class AMTWriterManager( /** The read snapshot's own AMT checkpoint, if it is AMT-backed. */ private def readSnapshotAMTCheckpointOpt: Option[Checkpoint] = { - if (!AMTUtils.amtEnabled(readSnapshot)) return None + if (!AMTUtils.amtEnabled(readSnapshot, isPreviewCompatible = true)) return None readSnapshot.checkpointProvider match { case amt: AMTCheckpointProviderBase => Some(amt.checkpointAction) case _ => None @@ -382,7 +382,7 @@ class AMTWriterManager( currentTransactionInfo: CurrentTransactionInfo, preCommitLogSegment: LogSegment, winningCommitMetricsForConflictedRange: Seq[WinningCommitMetrics]): Option[AMTWriteResult] = { - if (!AMTUtils.amtEnabled(readSnapshot)) return None + if (!AMTUtils.amtEnabled(readSnapshot, isPreviewCompatible = true)) return None val actionsToCommit = currentTransactionInfo.actions val roundId = nextRoundId nextRoundId += 1 @@ -818,7 +818,7 @@ class AMTWriterManager( pendingBackRefRebaseMetrics = BackRefRebaseMetrics(SKIP_REASON_NO_NEW_TREE) val actions = currentTransactionInfo.actions - if (!AMTUtils.amtEnabled(readSnapshot)) { + if (!AMTUtils.amtEnabled(readSnapshot, isPreviewCompatible = true)) { return currentTransactionInfo } if (!winningCommitInstalledNewAMTTree(currentTransactionInfo)) { @@ -1062,7 +1062,7 @@ object AMTWriterManager extends DeltaLogging { postCommitSnapshot: Snapshot): MaintenanceOperation = { // if the commit itself was to do a checkpoint, don't schedule any maintenance as part // of its post-commit hook. - if (!AMTUtils.amtEnabled(readSnapshot) + if (!AMTUtils.amtEnabled(readSnapshot, isPreviewCompatible = true) || initialOperation.isInstanceOf[DeltaOperations.OptimizeCheckpoint]) { return MaintenanceOperation() } @@ -1089,7 +1089,7 @@ object AMTWriterManager extends DeltaLogging { commitVersion: Long, postCommitSnapshot: Snapshot): MaintenanceOperation = { // The follow-up OPTIMIZE CHECKPOINT commit itself must never schedule more maintenance. - if (!AMTUtils.amtEnabled(readSnapshot) + if (!AMTUtils.amtEnabled(readSnapshot, isPreviewCompatible = true) || initialOperation.isInstanceOf[DeltaOperations.OptimizeCheckpoint]) { return MaintenanceOperation() } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/actions.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/actions.scala index 069972fdad4..3618ebd467f 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/actions.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/actions.scala @@ -719,7 +719,7 @@ object AMTSnapshotId { actions: Iterator[Action], snapshotId: Long): Iterator[Action] = { require(snapshotId >= 0L, s"AMT snapshot ID must be non-negative: $snapshotId.") - if (!AMTUtils.amtEnabled(metadata, protocol)) { + if (!AMTUtils.amtEnabled(metadata, protocol, isPreviewCompatible = true)) { return actions } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala index 2aa0f6ca6f2..9a7d7875060 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala @@ -437,7 +437,7 @@ abstract class CloneTableBase( !sourceTable.isInstanceOf[CloneIcebergSource] && sourceTable.metadata.columnMappingMode != IdMapping && (AMTUtils.amtRequested(metadata.configuration) || - AMTUtils.amtSupported(targetSnapshot.protocol))) { + AMTUtils.amtSupported(targetSnapshot.protocol, isPreviewCompatible = true))) { throw DeltaErrors.adaptiveMetadataRequiresColumnMappingIdMode( AdaptiveMetadataTableFeature.name, sourceTable.metadata.columnMappingMode.name) } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/VacuumCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/VacuumCommand.scala index 57b5cd70f9d..37887136174 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/VacuumCommand.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/VacuumCommand.scala @@ -237,7 +237,8 @@ object VacuumCommand extends VacuumCommandImpl with Serializable { val partitionColumns = snapshot.metadata.partitionSchema.fieldNames val parallelism = spark.sessionState.conf.parallelPartitionDiscoveryParallelism - val isAdaptiveMetadataTable = AMTUtils.amtSupported(snapshot.protocol) + val isAdaptiveMetadataTable = + AMTUtils.amtSupported(snapshot.protocol, isPreviewCompatible = true) val shouldIcebergMetadataDirBeHidden = isAdaptiveMetadataTable || UniversalFormat.icebergEnabled(snapshot.metadata) val latestCommitVersionOutsideOfRetentionWindowOpt: Option[Long] = @@ -993,7 +994,7 @@ trait VacuumCommandImpl extends DeltaCommand { // do not carry tombstones, so the checkpoint state cannot supply them. Evaluated per snapshot // so the base table and each clone independently pick the right source for their own protocol. val sourceTombstonesFromCommits = config.sourceTombstonesFromCommits || - AMTUtils.amtEnabled(snapshot) + AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true) val files = snapshot.stateDS.mapPartitions { actions => val reservoirBase = new Path(basePath) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/hooks/CheckpointHook.scala b/spark/src/main/scala/org/apache/spark/sql/delta/hooks/CheckpointHook.scala index 4be0b8ee405..7212be668e7 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/hooks/CheckpointHook.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/hooks/CheckpointHook.scala @@ -29,7 +29,7 @@ object CheckpointHook extends PostCommitHook { if (!txn.maintenanceOperation.shouldCheckpoint) return val snapshotToCheckpoint = - if (AMTUtils.amtEnabled(txn.postCommitSnapshot)) { + if (AMTUtils.amtEnabled(txn.postCommitSnapshot, isPreviewCompatible = true)) { txn.postCommitSnapshot } else { // Two txns writing multi-part checkpoints at the same version has the risk of corruption. diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTestUtils.scala index 2fd5a141e4f..2c58aea7151 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTestUtils.scala @@ -532,7 +532,7 @@ trait DeltaMinorCompactionTestUtils extends DeltaTestUtilsBase { tableRoot = deltaLog.dataPath, useDeletionVectorObjectIdentity = FileAction.useDeletionVectorObjectIdentity( snapshotForReplay.metadata, snapshotForReplay.protocol, spark), - retainFirstBackreference = AMTUtils.amtEnabled(snapshotForReplay)) + retainFirstBackreference = AMTUtils.amtEnabled(snapshotForReplay, isPreviewCompatible = true)) val hadoopConf = deltaLog.newDeltaHadoopConf() val catalogTable = tableName .map(name => spark.sessionState.catalog.getTableMetadata(new TableIdentifier(name))) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala index 35bac7bf951..71030a8685d 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTDMLTestUtils.scala @@ -100,7 +100,7 @@ trait AMTDMLTestUtils extends AMTCheckpointTestBase { fail(s"DML target $target resolves to a Delta table accessed by path, but AMT tables " + "are catalog-managed and accessed by name")) val amtTarget = AMTTarget(index.deltaLog, catalogTable) - assert(AMTUtils.amtEnabled(amtTarget.snapshot), + assert(AMTUtils.amtEnabled(amtTarget.snapshot, isPreviewCompatible = true), s"DML target $target resolves to a Delta table without AMT") amtTarget } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala index efbe59174f7..9b9ad0f7916 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala @@ -1640,7 +1640,7 @@ class AMTSnapshotDiscoverySuite sql(s"INSERT INTO $name VALUES (1)") val deltaLog = deltaLogForName(name) val snapshot = deltaLog.unsafeVolatileSnapshot - assert(AMTUtils.amtEnabled(snapshot)) + assert(AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true)) assert(snapshot.version == 1) assert(snapshot.checksumOpt.isDefined) assert(snapshot.lastManifestCommitOpt.isEmpty) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala index 0cfdaec3165..21c363f945c 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala @@ -49,8 +49,17 @@ class AMTUtilsSuite extends QueryTest with SharedSparkSession { val metadata = Metadata( configuration = property.map(DeltaConfigs.ADAPTIVE_METADATA_ENABLED.key -> _).toMap) val clue = s"protocol: $protocol, AMT property: $property" - assert(AMTUtils.amtSupported(protocol) === supported, clue) - assert(AMTUtils.amtEnabled(metadata, protocol) === enabled, clue) + assert(AMTUtils.amtSupported(protocol, isPreviewCompatible = true) === supported, clue) + assert(AMTUtils.amtEnabled(metadata, protocol, isPreviewCompatible = true) === enabled, clue) + // Callers that are not preview compatible do not see preview tables as AMT tables. + val isPreview = protocol == previewProtocol + assert( + AMTUtils.amtSupported(protocol, isPreviewCompatible = false) === (supported && !isPreview), + clue) + assert( + AMTUtils.amtEnabled(metadata, protocol, isPreviewCompatible = false) === + (enabled && !isPreview), + clue) } } @@ -159,11 +168,11 @@ class AMTUtilsSuite extends QueryTest with SharedSparkSession { test("amtEnabled: true when the protocol supports the AMT feature") { val protocol = Protocol.forTableFeature(AdaptiveMetadataPreviewTableFeature) - assert(AMTUtils.amtEnabled(Metadata(), protocol)) + assert(AMTUtils.amtEnabled(Metadata(), protocol, isPreviewCompatible = true)) } test("amtEnabled: false when the protocol lacks the AMT feature") { - assert(!AMTUtils.amtEnabled(Metadata(), Protocol())) + assert(!AMTUtils.amtEnabled(Metadata(), Protocol(), isPreviewCompatible = true)) } test("AMTSnapshotId fills missing AddFile and RemoveFile lifecycle IDs") { diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala index e21bbd3dd62..f9bf21a5d81 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala @@ -77,6 +77,9 @@ class AdaptiveMetadataTableFeatureSuite private def protocolOf(tableName: String) = DeltaLog.forTableWithSnapshot(spark, new TableIdentifier(tableName))._2.protocol + private def snapshotOf(tableName: String) = + DeltaLog.forTableWithSnapshot(spark, new TableIdentifier(tableName))._2 + test("feature is a ReaderWriterFeature and a RemovableFeature") { assert(AdaptiveMetadataPreviewTableFeature.isReaderWriterFeature) assert(AdaptiveMetadataPreviewTableFeature.isInstanceOf[RemovableFeature]) @@ -106,7 +109,8 @@ class AdaptiveMetadataTableFeatureSuite val protocol = protocolOf("amt_supported") assert(protocol.isFeatureSupported(AdaptiveMetadataPreviewTableFeature), s"Protocol must record adaptiveMetadata-preview as supported. Got: $protocol") - assert(AMTUtils.amtEnabled(metadataOf("amt_supported"), protocol), + assert( + AMTUtils.amtEnabled(metadataOf("amt_supported"), protocol, isPreviewCompatible = true), s"AMTUtils.amtEnabled must report the table as AMT-enabled. Got: $protocol") // Every required feature (and their transitive dependencies) must be present. dependentFeatures(AdaptiveMetadataPreviewTableFeature).foreach { f => @@ -380,9 +384,15 @@ class AdaptiveMetadataTableFeatureSuite withTable(tableName) { if (creatable) { createAdaptiveMetadataTable(tableName, feature = feature) - val protocol = protocolOf(tableName) + val snapshot = snapshotOf(tableName) + val protocol = snapshot.protocol assert(protocol.isFeatureSupported(feature), s"Got: $protocol") - assert(AMTUtils.amtEnabled(metadataOf(tableName), protocol), s"Got: $protocol") + assert(AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true), s"Got: $protocol") + // Callers that are not preview compatible only see `adaptiveMetadata-dev` tables. + assert( + AMTUtils.amtEnabled(snapshot, isPreviewCompatible = false) == + (feature == AdaptiveMetadataTableFeature), + s"Got: $protocol") } else { checkError( intercept[DeltaAnalysisException] { From be6041cae43f2e46983a862467c6f447821ccbb1 Mon Sep 17 00:00:00 2001 From: Lin Zhou <87341375+linzhou-db@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:44:41 -0800 Subject: [PATCH 30/44] [Sharing] Remove spark.sql.delta.sharing.enableAutoResolveForCdf (#8206) #### Which Delta project/connector is this regarding? - [ ] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [x] Other (Delta Sharing) ## Description Removes the internal conf `spark.sql.delta.sharing.enableAutoResolveForCdf` (`DeltaSQLConf.DELTA_SHARING_ENABLE_AUTO_RESOLVE_FOR_CDF`). A Delta Sharing batch CDF read without an explicit `responseFormat` now always auto-resolves its response format. - `DeltaSharingDataSource.createRelation`: every batch read without a `responseFormat`, snapshot or CDF, goes to `autoResolveBaseRelation`. That method calls getMetadata, pinned to the end of the CDF range (or the latest version when the range has no end), and takes the parquet or delta path that the server answers with. Before this change, a CDF read with the conf off (its default) fell back to the legacy parquet path. The `shouldAutoResolveCDF` helper is removed. Reads with an explicit `responseFormat` are unchanged. - `DeltaSQLConf`: the conf is removed. - `DeltaSharingDataSourceDeltaSuite`: the two tests parameterized on the conf are replaced by always-on versions. One reads delta-format CDF across version and timestamp bounds. The other reads a parquet-format share and checks that it resolves to the parquet path (the parquet CDF reader's `LongType` `_commit_timestamp`). The conf was added so the CDF auto-resolve path could be rolled out gradually. That rollout is done, so the conf is no longer needed. ## How was this patch tested? Updated the tests in `DeltaSharingDataSourceDeltaSuite` as described above. - `build/sbt "spark/scalastyle" "sharing/scalastyle" "sharing/Test/scalastyle" "sharing/testOnly io.delta.sharing.spark.*"` Result: scalastyle reports 0 errors and 0 warnings. `sharing/testOnly`: 130 passed, 2 failed. The same 2 tests fail with this command on unmodified master (3b1bb7857): `DeltaSharingDataSource able to auto resolve responseFormat` fails only when run after `DeltaFormatSharingSourceSuite` in the same JVM (the global `requestedFormat` map collects `shared_parquet_table*` entries from that suite) and passes when its suite runs alone. `versionless CDF refresh preserves timestamp bounds and isolates queries` (`DeltaSharingCDFUtilsSuite`) hits a 20s `eventually` timeout. ## Does this PR introduce _any_ user-facing changes? Yes. A Delta Sharing batch CDF read without a `responseFormat` option (for example `spark.read.format("deltaSharing").option("readChangeFeed", "true").load(path)` or `table_changes`) now asks the server for the table's format and reads through the delta-format path when the server answers delta. Before, by default it always used the parquet path. The removed conf was internal. This pull request and its description were written by Isaac. Signed-off-by: lin.zhou Co-authored-by: Isaac --- .../spark/DeltaSharingDataSource.scala | 16 +- .../DeltaSharingDataSourceDeltaSuite.scala | 380 ++++++++---------- .../sql/delta/sources/DeltaSQLConf.scala | 10 - 3 files changed, 166 insertions(+), 240 deletions(-) diff --git a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala index 5c96d0bbdca..7522dd35d90 100644 --- a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala +++ b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala @@ -355,8 +355,7 @@ private[sharing] class DeltaSharingDataSource val userInputResponseFormat = options.options.get(DeltaSharingOptions.RESPONSE_FORMAT) - if (userInputResponseFormat.isEmpty && - (!options.readChangeFeed || shouldAutoResolveCDF(options, sqlContext))) { + if (userInputResponseFormat.isEmpty) { return autoResolveBaseRelation(options, sqlContext) } @@ -430,19 +429,6 @@ private[sharing] class DeltaSharingDataSource } } - /** - * Whether a CDF query should auto-resolve its response format (parquet vs delta) by asking the - * server, rather than falling back to the legacy parquet path. True only for change-feed reads - * with the CDF auto-resolve flag enabled. - */ - private def shouldAutoResolveCDF( - options: DeltaSharingOptions, - sqlContext: SQLContext): Boolean = { - options.readChangeFeed && sqlContext.sparkSession.sessionState.conf.getConf( - DeltaSQLConf.DELTA_SHARING_ENABLE_AUTO_RESOLVE_FOR_CDF - ) - } - /** * Auto-resolves the response format for a batch query (snapshot or CDF). * "parquet format sharing" leverages the existing set of remote classes to directly handle the diff --git a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingDataSourceDeltaSuite.scala b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingDataSourceDeltaSuite.scala index fddcc60b140..a1f1680aa78 100644 --- a/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingDataSourceDeltaSuite.scala +++ b/sharing/src/test/scala/io/delta/sharing/spark/DeltaSharingDataSourceDeltaSuite.scala @@ -1135,243 +1135,114 @@ trait DeltaSharingDataSourceDeltaSuiteBase } } - test("DeltaSharingDataSource auto-resolves responseFormat for cdf query gated by flag") { + test("DeltaSharingDataSource auto-resolves responseFormat for cdf query") { withTempDir { tempDir => - for (autoResolveEnabled <- Seq(true, false)) { - val suffix = if (autoResolveEnabled) "on" else "off" - val deltaTableName = s"delta_table_cdf_autoresolve_$suffix" - withTable(deltaTableName) { - sql(s""" - |CREATE TABLE $deltaTableName (c1 INT, c2 STRING) USING DELTA PARTITIONED BY (c2) - |TBLPROPERTIES ( - | delta.enableChangeDataFeed = true, - | delta.enableDeletionVectors = true - |) - |""".stripMargin) - sql(s"""INSERT INTO $deltaTableName VALUES (1, "one"), (2, "two")""") - sql(s"""INSERT INTO $deltaTableName VALUES (3, "two")""") - sql(s"""UPDATE $deltaTableName SET c2="new two" where c1=2""") - sql(s"""DELETE FROM $deltaTableName WHERE c1 = 2""") - - val sharedTableName = s"shared_cdf_autoresolve_$suffix" - prepareMockedClientGetTableVersion(deltaTableName, sharedTableName) - - val autoResolveConf = Map( - DeltaSQLConf.DELTA_SHARING_ENABLE_AUTO_RESOLVE_FOR_CDF.key -> - autoResolveEnabled.toString - ) - - val expectedSchema: StructType = new StructType() - .add("c1", IntegerType) - .add("c2", StringType) - .add("_change_type", StringType) - .add("_commit_version", LongType) - .add("_commit_timestamp", TimestampType) - - // Versions: v0 CREATE, v1/v2 INSERT, v3 UPDATE, v4 DELETE. Read CDF from v1, and use v3 - // as the (inclusive) end bound for the bounded cases so it excludes the v4 delete. - val startVersion = 1L - val endVersion = 3L - def isoTimestampForVersion(version: Long): String = - DateTimeUtils - .toJavaTimestamp(getTimeStampForVersion(deltaTableName, version) * 1000) - .toInstant - .toString - val startTimestamp = isoTimestampForVersion(startVersion) - val endTimestamp = isoTimestampForVersion(endVersion) - - // Auto-resolve calls getMetadata to learn the server's preferred format, pinned to the - // end of the CDF range (latest when unbounded), and the legacy parquet RemoteDeltaLog - // also calls getMetadata on init. Mock every boundary the cases below exercise. - prepareMockedClientMetadata(deltaTableName, sharedTableName) - prepareMockedClientMetadata( - deltaTableName, - sharedTableName, - versionAsOf = Some(endVersion) - ) - prepareMockedClientMetadata( - deltaTableName, - sharedTableName, - timestampAsOf = Some(endTimestamp) - ) - - // Flatten an exception and its causes into the concatenated message text, so assertions - // can look for a marker anywhere in the chain regardless of wrapping. - def causeChain(ex: Throwable): String = - Iterator - .iterate[Throwable](ex)(t => if (t == null) null else t.getCause) - .takeWhile(_ != null) - .map(t => Option(t.getMessage).getOrElse("")) - .mkString("\n") - - val versionOnlyOpts = Seq("startingVersion" -> startVersion.toString) - val versionRangeOpts = - Seq("startingVersion" -> startVersion.toString, "endingVersion" -> endVersion.toString) - val timestampOnlyOpts = Seq("startingTimestamp" -> startTimestamp) - val timestampRangeOpts = - Seq("startingTimestamp" -> startTimestamp, "endingTimestamp" -> endTimestamp) - - // (label, options applied to the sharing read, options applied to the expected delta - // read). Timestamp-based sharing reads are compared against the equivalent version - // bounds on the delta side to avoid depending on delta's timestamp-resolution edges. - val cdfCases = Seq( - ("startingVersion, no end", versionOnlyOpts, versionOnlyOpts), - ("startingVersion, endingVersion", versionRangeOpts, versionRangeOpts), - ("startingTimestamp, no end", timestampOnlyOpts, versionOnlyOpts), - ("startingTimestamp, endingTimestamp", timestampRangeOpts, versionRangeOpts) - ) - - for ((label, sharingOptions, deltaOptions) <- cdfCases) { - // The test client keys getCDFFiles on the starting bound only, so register the - // starting timestamp block when needed, and bound the mocked files by endingVersion - // so an ending bound is reflected in what the server returns (the local delta CDF read - // derives its end from those files, not from the request option). - val mockStartTimestamp = - sharingOptions.collectFirst { case ("startingTimestamp", value) => value } - val mockEndingVersion = - if (deltaOptions.exists(_._1 == "endingVersion")) Some(endVersion) else None - prepareMockedClientAndFileSystemResultForCdf( - deltaTableName, - sharedTableName, - startVersion, - startingTimestamp = mockStartTimestamp, - endingVersion = mockEndingVersion - ) + val deltaTableName = "delta_table_cdf_autoresolve" + withTable(deltaTableName) { + sql(s""" + |CREATE TABLE $deltaTableName (c1 INT, c2 STRING) USING DELTA PARTITIONED BY (c2) + |TBLPROPERTIES ( + | delta.enableChangeDataFeed = true, + | delta.enableDeletionVectors = true + |) + |""".stripMargin) + sql(s"""INSERT INTO $deltaTableName VALUES (1, "one"), (2, "two")""") + sql(s"""INSERT INTO $deltaTableName VALUES (3, "two")""") + sql(s"""UPDATE $deltaTableName SET c2="new two" where c1=2""") + sql(s"""DELETE FROM $deltaTableName WHERE c1 = 2""") - if (autoResolveEnabled) { - def testAutoResolveCdf(tablePath: String): Unit = { - val sharingDf = spark.read - .format("deltaSharing") - .option("readChangeFeed", "true") - .options(sharingOptions.toMap) - .load(tablePath) - assert(sharingDf.schema == expectedSchema, s"schema mismatch for case: $label") - - val expected = spark.read - .format("delta") - .option("readChangeFeed", "true") - .options(deltaOptions.toMap) - .table(deltaTableName) - checkAnswer(sharingDf, expected) - assert(sharingDf.count() > 0, s"expected non-empty result for case: $label") - } + val sharedTableName = "shared_cdf_autoresolve" + prepareMockedClientGetTableVersion(deltaTableName, sharedTableName) - withSQLConf((autoResolveConf ++ getDeltaSharingClassesSQLConf).toSeq: _*) { - val profileFile = prepareProfileFile(tempDir) - testAutoResolveCdf( - profileFile.getCanonicalPath + s"#share1.default.$sharedTableName" - ) - } - } else { - withSQLConf((autoResolveConf ++ getDeltaSharingClassesSQLConf).toSeq: _*) { - val profileFile = prepareProfileFile(tempDir) - val tablePath = profileFile.getCanonicalPath + s"#share1.default.$sharedTableName" - // With flag off + no responseFormat, the query falls through to the legacy parquet - // path. The OSS parquet RemoteDeltaLog receives the delta-format response from - // TestClientForDeltaFormatSharing (the test client always responds delta) and dies - // initializing its RemoteSnapshot. That failure proves the auto-resolve gate did - // NOT fire: had it fired, the request would have succeeded via the delta CDF path - // (as the flag-on branch demonstrates). - val ex = intercept[Exception] { - spark.read - .format("deltaSharing") - .option("readChangeFeed", "true") - .options(sharingOptions.toMap) - .load(tablePath) - .collect() - } - val chain = causeChain(ex) - assert( - chain.contains("RemoteSnapshot"), - s"Expected the legacy parquet path (RemoteSnapshot) to surface for case " + - s"$label; got:\n$chain" - ) - } - } - } - } - } - } - } + val expectedSchema: StructType = new StructType() + .add("c1", IntegerType) + .add("c2", StringType) + .add("_change_type", StringType) + .add("_commit_version", LongType) + .add("_commit_timestamp", TimestampType) + + // Versions: v0 CREATE, v1/v2 INSERT, v3 UPDATE, v4 DELETE. Read CDF from v1, and use v3 + // as the (inclusive) end bound for the bounded cases so it excludes the v4 delete. + val startVersion = 1L + val endVersion = 3L + def isoTimestampForVersion(version: Long): String = + DateTimeUtils + .toJavaTimestamp(getTimeStampForVersion(deltaTableName, version) * 1000) + .toInstant + .toString + val startTimestamp = isoTimestampForVersion(startVersion) + val endTimestamp = isoTimestampForVersion(endVersion) + + // Auto-resolve calls getMetadata to learn the server's preferred format, pinned to the + // end of the CDF range (latest when unbounded). Mock every boundary the cases exercise. + prepareMockedClientMetadata(deltaTableName, sharedTableName) + prepareMockedClientMetadata( + deltaTableName, + sharedTableName, + versionAsOf = Some(endVersion) + ) + prepareMockedClientMetadata( + deltaTableName, + sharedTableName, + timestampAsOf = Some(endTimestamp) + ) - test("DeltaSharingDataSource reads cdf from a parquet-format shared table " + - "regardless of auto-resolve flag") { - withTempDir { tempDir => - // A parquet-format shared table has no advanced delta features, so a CDF read lands on the - // legacy parquet path either way: with the flag on it is resolved to parquet via getMetadata, - // and with the flag off it is the default parquet fall-through. Both should read the - // parquet-format CDF response end-to-end and match a direct Delta CDF read. - for (autoResolveEnabled <- Seq(true, false)) { - val suffix = if (autoResolveEnabled) "on" else "off" - val deltaTableName = s"delta_table_cdf_parquet_$suffix" - withTable(deltaTableName) { - // Mimic a parquet-format table: change data feed on, deletion vectors off (a real - // parquet-format share cannot carry advanced features like deletion vectors). - sql(s""" - |CREATE TABLE $deltaTableName (c1 INT, c2 STRING) USING DELTA PARTITIONED BY (c2) - |TBLPROPERTIES ( - | delta.enableChangeDataFeed = true, - | delta.enableDeletionVectors = false - |) - |""".stripMargin) - sql(s"""INSERT INTO $deltaTableName VALUES (1, "one"), (2, "two")""") - sql(s"""INSERT INTO $deltaTableName VALUES (3, "two")""") - sql(s"""UPDATE $deltaTableName SET c2="new two" where c1=2""") - sql(s"""DELETE FROM $deltaTableName WHERE c1 = 2""") + val versionOnlyOpts = Seq("startingVersion" -> startVersion.toString) + val versionRangeOpts = + Seq("startingVersion" -> startVersion.toString, "endingVersion" -> endVersion.toString) + val timestampOnlyOpts = Seq("startingTimestamp" -> startTimestamp) + val timestampRangeOpts = + Seq("startingTimestamp" -> startTimestamp, "endingTimestamp" -> endTimestamp) + + // (label, options applied to the sharing read, options applied to the expected delta + // read). Timestamp-based sharing reads are compared against the equivalent version + // bounds on the delta side to avoid depending on delta's timestamp-resolution edges. + val cdfCases = Seq( + ("startingVersion, no end", versionOnlyOpts, versionOnlyOpts), + ("startingVersion, endingVersion", versionRangeOpts, versionRangeOpts), + ("startingTimestamp, no end", timestampOnlyOpts, versionOnlyOpts), + ("startingTimestamp, endingTimestamp", timestampRangeOpts, versionRangeOpts) + ) - val startVersion = 1L - val parquetSharedTable = s"shared_parquet_table_cdf_$suffix" - prepareMockedClientGetTableVersion(deltaTableName, parquetSharedTable) - // getMetadata responds parquet (SingleAction-shaped) -- used by the auto-resolve probe - // (flag on) and by the legacy parquet RemoteSnapshot init (flag off). - prepareMockedClientAndFileSystemResultForParquet(deltaTableName, parquetSharedTable) - // Parquet-format CDF response so the parquet CDF reader can read it end-to-end. + for ((label, sharingOptions, deltaOptions) <- cdfCases) { + // The test client keys getCDFFiles on the starting bound only, so register the + // starting timestamp block when needed, and bound the mocked files by endingVersion + // so an ending bound is reflected in what the server returns (the local delta CDF read + // derives its end from those files, not from the request option). + val mockStartTimestamp = + sharingOptions.collectFirst { case ("startingTimestamp", value) => value } + val mockEndingVersion = + if (deltaOptions.exists(_._1 == "endingVersion")) Some(endVersion) else None prepareMockedClientAndFileSystemResultForCdf( deltaTableName, - parquetSharedTable, + sharedTableName, startVersion, - responseFormat = DeltaSharingOptions.RESPONSE_FORMAT_PARQUET + startingTimestamp = mockStartTimestamp, + endingVersion = mockEndingVersion ) - val autoResolveConf = Map( - DeltaSQLConf.DELTA_SHARING_ENABLE_AUTO_RESOLVE_FOR_CDF.key -> - autoResolveEnabled.toString - ) - - // The legacy parquet CDF reader surfaces the same CDF columns but orders them differently - // and emits _commit_timestamp as epoch-millis (LongType) rather than delta's - // TimestampType, so compare on the columns whose representation is identical, and assert - // on the column set rather than strict schema equality. - val cdfColumns = Seq("c1", "c2", "_change_type", "_commit_version") - val expectedColumns = - Set("c1", "c2", "_change_type", "_commit_version", "_commit_timestamp") - - def testParquetCdf(tablePath: String): Unit = { + // No responseFormat: the read probes getMetadata and takes the delta CDF path. + def testAutoResolveCdf(tablePath: String): Unit = { val sharingDf = spark.read .format("deltaSharing") .option("readChangeFeed", "true") - .option("startingVersion", startVersion) + .options(sharingOptions.toMap) .load(tablePath) - assert( - sharingDf.columns.toSet == expectedColumns, - s"unexpected columns for parquet cdf read: ${sharingDf.columns.mkString(",")}" - ) + assert(sharingDf.schema == expectedSchema, s"schema mismatch for case: $label") val expected = spark.read .format("delta") .option("readChangeFeed", "true") - .option("startingVersion", startVersion) + .options(deltaOptions.toMap) .table(deltaTableName) - .select(cdfColumns.map(col): _*) - val sharingCdf = sharingDf.select(cdfColumns.map(col): _*) - checkAnswer(sharingCdf, expected) - assert(sharingCdf.count() > 0, "expected non-empty result for parquet cdf read") + checkAnswer(sharingDf, expected) + assert(sharingDf.count() > 0, s"expected non-empty result for case: $label") } - withSQLConf((autoResolveConf ++ getDeltaSharingClassesSQLConf).toSeq: _*) { + withSQLConf(getDeltaSharingClassesSQLConf.toSeq: _*) { val profileFile = prepareProfileFile(tempDir) - testParquetCdf( - profileFile.getCanonicalPath + s"#share1.default.$parquetSharedTable" + testAutoResolveCdf( + profileFile.getCanonicalPath + s"#share1.default.$sharedTableName" ) } } @@ -1379,6 +1250,85 @@ trait DeltaSharingDataSourceDeltaSuiteBase } } + test("DeltaSharingDataSource auto-resolves cdf from a parquet-format shared table to the " + + "parquet path") { + withTempDir { tempDir => + // A parquet-format shared table has no advanced delta features, so a CDF read without a + // responseFormat is resolved to parquet via getMetadata and lands on the parquet path. It + // should read the parquet-format CDF response end-to-end and match a direct Delta CDF read. + val deltaTableName = "delta_table_cdf_parquet" + withTable(deltaTableName) { + // Mimic a parquet-format table: change data feed on, deletion vectors off (a real + // parquet-format share cannot carry advanced features like deletion vectors). + sql(s""" + |CREATE TABLE $deltaTableName (c1 INT, c2 STRING) USING DELTA PARTITIONED BY (c2) + |TBLPROPERTIES ( + | delta.enableChangeDataFeed = true, + | delta.enableDeletionVectors = false + |) + |""".stripMargin) + sql(s"""INSERT INTO $deltaTableName VALUES (1, "one"), (2, "two")""") + sql(s"""INSERT INTO $deltaTableName VALUES (3, "two")""") + sql(s"""UPDATE $deltaTableName SET c2="new two" where c1=2""") + sql(s"""DELETE FROM $deltaTableName WHERE c1 = 2""") + + val startVersion = 1L + val parquetSharedTable = "shared_parquet_table_cdf" + prepareMockedClientGetTableVersion(deltaTableName, parquetSharedTable) + // getMetadata responds parquet (SingleAction-shaped) to the auto-resolve probe. + prepareMockedClientAndFileSystemResultForParquet(deltaTableName, parquetSharedTable) + // Parquet-format CDF response so the parquet CDF reader can read it end-to-end. + prepareMockedClientAndFileSystemResultForCdf( + deltaTableName, + parquetSharedTable, + startVersion, + responseFormat = DeltaSharingOptions.RESPONSE_FORMAT_PARQUET + ) + + // The parquet CDF reader surfaces the same CDF columns but orders them differently + // and emits _commit_timestamp as epoch-millis (LongType) rather than delta's + // TimestampType, so compare on the columns whose representation is identical, and assert + // on the column set rather than strict schema equality. + val cdfColumns = Seq("c1", "c2", "_change_type", "_commit_version") + val expectedColumns = + Set("c1", "c2", "_change_type", "_commit_version", "_commit_timestamp") + + def testParquetCdf(tablePath: String): Unit = { + val sharingDf = spark.read + .format("deltaSharing") + .option("readChangeFeed", "true") + .option("startingVersion", startVersion) + .load(tablePath) + assert( + sharingDf.columns.toSet == expectedColumns, + s"unexpected columns for parquet cdf read: ${sharingDf.columns.mkString(",")}" + ) + // Only the parquet CDF path emits _commit_timestamp as epoch-millis LongType (the delta + // path emits TimestampType), so this pins the read to the parquet path. + assert(sharingDf.schema("_commit_timestamp").dataType == LongType, + s"expected the parquet CDF path, got schema: ${sharingDf.schema}") + + val expected = spark.read + .format("delta") + .option("readChangeFeed", "true") + .option("startingVersion", startVersion) + .table(deltaTableName) + .select(cdfColumns.map(col): _*) + val sharingCdf = sharingDf.select(cdfColumns.map(col): _*) + checkAnswer(sharingCdf, expected) + assert(sharingCdf.count() > 0, "expected non-empty result for parquet cdf read") + } + + withSQLConf(getDeltaSharingClassesSQLConf.toSeq: _*) { + val profileFile = prepareProfileFile(tempDir) + testParquetCdf( + profileFile.getCanonicalPath + s"#share1.default.$parquetSharedTable" + ) + } + } + } + } + test("DeltaSharingDataSource able to read data for cdf query with more entries") { withTempDir { tempDir => val deltaTableName = "delta_table_cdf_more" 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 debcf386b06..cfb7b09e113 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 @@ -3840,16 +3840,6 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(false) - val DELTA_SHARING_ENABLE_AUTO_RESOLVE_FOR_CDF = - buildConf("spark.sql.delta.sharing.enableAutoResolveForCdf") - .doc("When true, Delta Sharing CDF queries without an explicit responseFormat will " + - "call getMetadata on the sharing server and pick the parquet or delta CDF code path " + - "based on the server's responded format. When false, CDF queries without a response " + - "format fall back to the legacy parquet path.") - .internal() - .booleanConf - .createWithDefault(false) - /////////////////// // IDENTITY COLUMN /////////////////// From e364662f30e1260d3198304f38f1aa8a096ce9fe Mon Sep 17 00:00:00 2001 From: Lin Zhou <87341375+linzhou-db@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:44:50 -0800 Subject: [PATCH 31/44] [Sharing] Remove spark.sql.delta.sharing.cdfStreamingAutoResolveResponseFormat (#8207) #### Which Delta project/connector is this regarding? - [ ] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [x] Other (Delta Sharing) ## Description Removes the internal conf `spark.sql.delta.sharing.cdfStreamingAutoResolveResponseFormat` (`DeltaSQLConf.DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT`). Delta Sharing streaming CDF (`readChangeFeed=true`) now always auto-resolves its response format. - `DeltaSharingDataSource.autoResolveStreamingSource`: a CDF stream always uses getMetadata. When `responseFormat` is not set, it takes the format the server answers with, and an explicit `responseFormat=delta` goes to the delta-format source. Non-CDF streaming is still gated by `spark.sql.delta.sharing.streamingAutoResolveResponseFormat`. - `DeltaFormatSharingSource.isAutoResolveEnabled`: always true for CDF streams, so the delta-format source accepts a legacy `DeltaSharingSourceOffset` checkpoint left by an earlier parquet CDF stream and picks the matching file-id hash. - `DeltaSQLConf`: the conf is removed. - `DeltaFormatSharingSourceSuite`: the `forceToDeltaSourceOffset` flag-routing grid now covers CDF auto-resolve with the non-CDF conf both on and off, and non-CDF with the non-CDF conf on and off. The conf was added so CDF streaming auto-resolve could be rolled out separately from non-CDF streaming. That rollout is done, so the conf is no longer needed. ## How was this patch tested? Updated the routing-grid test in `DeltaFormatSharingSourceSuite` as described above. - `build/sbt "spark/scalastyle" "sharing/scalastyle" "sharing/Test/scalastyle" "sharing/testOnly io.delta.sharing.spark.*"` Result: scalastyle reports 0 errors and 0 warnings. `sharing/testOnly`: 130 passed, 2 failed. The same 2 tests fail with this command on unmodified master (3b1bb7857): `DeltaSharingDataSource able to auto resolve responseFormat` fails only when run after `DeltaFormatSharingSourceSuite` in the same JVM (the global `requestedFormat` map collects `shared_parquet_table*` entries from that suite) and passes when its suite runs alone. `versionless CDF refresh preserves timestamp bounds and isolates queries` (`DeltaSharingCDFUtilsSuite`) hits a 20s `eventually` timeout. ## Does this PR introduce _any_ user-facing changes? Yes. A Delta Sharing streaming CDF read now always asks the server for the table's format. If `responseFormat` is not set and the server answers delta, the stream uses the delta-format source even when `spark.sql.delta.sharing.streamingAutoResolveResponseFormat` is off. Before, by default it used the parquet source. A CDF stream that restarts with `responseFormat=delta` from a legacy parquet CDF checkpoint now resumes from that checkpoint instead of failing to parse it. The removed conf was internal. This pull request and its description were written by Isaac. Signed-off-by: lin.zhou Co-authored-by: Isaac --- .../spark/DeltaFormatSharingSource.scala | 14 +++----- .../spark/DeltaSharingDataSource.scala | 20 +++++------ .../spark/DeltaFormatSharingSourceSuite.scala | 34 ++++++++++--------- .../sql/delta/sources/DeltaSQLConf.scala | 11 ------ 4 files changed, 31 insertions(+), 48 deletions(-) diff --git a/sharing/src/main/scala/io/delta/sharing/spark/DeltaFormatSharingSource.scala b/sharing/src/main/scala/io/delta/sharing/spark/DeltaFormatSharingSource.scala index eeea519ed2a..4c147f575dc 100644 --- a/sharing/src/main/scala/io/delta/sharing/spark/DeltaFormatSharingSource.scala +++ b/sharing/src/main/scala/io/delta/sharing/spark/DeltaFormatSharingSource.scala @@ -430,17 +430,13 @@ case class DeltaFormatSharingSource( } /** - * Whether the auto-resolve conf is enabled for this stream. CDF streaming - * (readChangeFeed=true) is gated by DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT; - * non-CDF streaming is gated by DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT. + * Whether auto-resolve is enabled for this stream. CDF streaming (readChangeFeed=true) always + * auto-resolves; non-CDF streaming is gated by + * DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT. */ private def isAutoResolveEnabled: Boolean = { - val confKey = if (options.readChangeFeed) { - DeltaSQLConf.DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT - } else { - DeltaSQLConf.DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT - } - sqlConf.getConf(confKey) + options.readChangeFeed || + sqlConf.getConf(DeltaSQLConf.DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT) } /** Returns the file ID hash option based on auto-resolve config and whether MD5 is needed. */ diff --git a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala index 7522dd35d90..cef6f0cdd39 100644 --- a/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala +++ b/sharing/src/main/scala/io/delta/sharing/spark/DeltaSharingDataSource.scala @@ -245,12 +245,11 @@ private[sharing] class DeltaSharingDataSource } /** - * Resolves the response format for streaming: when the relevant auto-resolve conf is true, - * calls getMetadata on the table and uses the server's responded format; otherwise uses the - * user's responseFormat option. CDF streaming (readChangeFeed=true) is gated independently by - * DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT, while non-CDF streaming is gated by - * DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT. - * Returns (responseFormat, parsedPath, deltaTableMetadataOpt). When the conf is on, + * Resolves the response format for streaming: when auto-resolve applies, calls getMetadata on + * the table and uses the server's responded format; otherwise uses the user's responseFormat + * option. CDF streaming (readChangeFeed=true) always auto-resolves, while non-CDF streaming is + * gated by DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT. + * Returns (responseFormat, parsedPath, deltaTableMetadataOpt). When auto-resolve applies, * deltaTableMetadataOpt is Some; sourceSchema's delta path reuses it to avoid a second RPC. */ private def autoResolveStreamingSource( @@ -258,12 +257,9 @@ private[sharing] class DeltaSharingDataSource path: String, options: DeltaSharingOptions ): (String, ParsedDeltaSharingTablePath, Option[DeltaTableMetadata]) = { - val autoResolveConf = if (options.readChangeFeed) { - DeltaSQLConf.DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT - } else { - DeltaSQLConf.DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT - } - val useGetMetadata = sqlContext.sparkSession.sessionState.conf.getConf(autoResolveConf) + val useGetMetadata = options.readChangeFeed || + sqlContext.sparkSession.sessionState.conf.getConf( + DeltaSQLConf.DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT) val parsedPath = DeltaSharingRestClient.parsePath(path, options.shareCredentialsOptions) diff --git a/sharing/src/test/scala/io/delta/sharing/spark/DeltaFormatSharingSourceSuite.scala b/sharing/src/test/scala/io/delta/sharing/spark/DeltaFormatSharingSourceSuite.scala index 83f2400632f..949776b9b08 100644 --- a/sharing/src/test/scala/io/delta/sharing/spark/DeltaFormatSharingSourceSuite.scala +++ b/sharing/src/test/scala/io/delta/sharing/spark/DeltaFormatSharingSourceSuite.scala @@ -720,20 +720,18 @@ class DeltaFormatSharingSourceSuite } } - // forceToDeltaSourceOffset gates legacy-JSON parsing on the auto-resolve conf. CDF streaming - // (readChangeFeed=true) must be gated by the new - // DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT and ignore the non-CDF flag, and - // vice versa for non-CDF streaming. This grid verifies all four conf combinations against both - // source kinds and confirms the two flags route independently. + // forceToDeltaSourceOffset gates legacy-JSON parsing on auto-resolve. CDF streaming + // (readChangeFeed=true) always auto-resolves, regardless of the non-CDF flag; non-CDF streaming + // is gated by DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT. Seq( - // (readChangeFeed, cdfFlag, streamingFlag, expectAutoResolveOn) - (true, true, false, true), // CDF: CDF flag on -> auto-resolve on, ignores streamingFlag=false - (true, false, true, false), // CDF: non-CDF flag must not enable CDF auto-resolve - (false, true, false, false), // non-CDF: CDF flag must not enable non-CDF auto-resolve - (false, false, true, true) // non-CDF: streaming flag on -> auto-resolve on (existing path) - ).foreach { case (readChangeFeed, cdfFlag, streamingFlag, expectAutoResolveOn) => - test(s"forceToDeltaSourceOffset: flag routing readChangeFeed=$readChangeFeed " + - s"cdfFlag=$cdfFlag streamingFlag=$streamingFlag -> autoResolve=$expectAutoResolveOn") { + // (readChangeFeed, streamingFlag, expectAutoResolveOn) + (true, false, true), // CDF: always on, even with the non-CDF flag off + (true, true, true), // CDF: always on with the non-CDF flag on + (false, false, false), // non-CDF: streaming flag off -> auto-resolve off + (false, true, true) // non-CDF: streaming flag on -> auto-resolve on + ).foreach { case (readChangeFeed, streamingFlag, expectAutoResolveOn) => + test(s"forceToDeltaSourceOffset: readChangeFeed=$readChangeFeed " + + s"streamingFlag=$streamingFlag -> autoResolve=$expectAutoResolveOn") { withTempDir { tempDir => val deltaTableName = "delta_table_cdf_flag_routing" withTable(deltaTableName) { @@ -743,13 +741,10 @@ class DeltaFormatSharingSourceSuite prepareMockedClientGetTableVersion(deltaTableName, sharedTableName) val profileFile = prepareProfileFile(tempDir) val tableId = "test-table-id" - val cdfKey = DeltaSQLConf - .DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT.key val streamingKey = DeltaSQLConf .DELTA_SHARING_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT.key withSQLConf( (getDeltaSharingClassesSQLConf ++ Seq( - cdfKey -> cdfFlag.toString, streamingKey -> streamingFlag.toString )).toSeq: _* ) { @@ -772,6 +767,13 @@ class DeltaFormatSharingSourceSuite assert(deltaOffset.reservoirId === tableId) assert(deltaOffset.reservoirVersion === 1L) } else { + // With auto-resolve off the legacy fallback must not run: the call rethrows the + // underlying delta source's failure instead of converting the legacy JSON. The + // exception's type is not the table-id check itself - with this grid's minimal + // mocks the lazy delta source fails earlier, on its filesystem access - so the + // assertion pins the routing contract (throw, never return a converted offset), + // not the mock-dependent error type. The sibling auto-resolve-on cases prove the + // same legacy JSON parses fine once the fallback runs. intercept[Exception](source.forceToDeltaSourceOffset(serializedOffset)) } cleanUpDeltaSharingBlocks() 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 cfb7b09e113..fac53ac2301 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 @@ -3795,17 +3795,6 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { .booleanConf .createWithDefault(false) - val DELTA_SHARING_CDF_STREAMING_AUTO_RESOLVE_RESPONSE_FORMAT = - buildConf("spark.sql.delta.sharing.cdfStreamingAutoResolveResponseFormat") - .doc("When true, auto-resolve the Delta Sharing streaming CDF source format by calling " + - "getMetadata on the table and using the server's responded format (parquet or delta). " + - "When false, use the responseFormat option from the user. Gates the streaming CDF " + - "(readChangeFeed=true) path independently from the non-CDF streaming path controlled " + - "by spark.sql.delta.sharing.streamingAutoResolveResponseFormat.") - .internal() - .booleanConf - .createWithDefault(false) - val DELTA_SHARING_STREAMING_ENABLE_HISTORICAL_PROTOCOL = buildConf("spark.sql.delta.sharing.streamingEnableHistoricalProtocol") .doc("When true, a Delta Sharing streaming query (non-CDF, incremental getFiles) requests " + From fd8c620f05f1d86534967b5d1b9f36579682fa07 Mon Sep 17 00:00:00 2001 From: Cuong Nguyen Date: Tue, 17 Nov 2026 17:54:56 -0800 Subject: [PATCH 32/44] [Spark] Allow AMT leaves that mix live files and tombstones (#8208) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description The V4 spec lets a leaf manifest hold both live files and tombstones, and other engines write such leaves, for example Iceberg after a delete and insert. The incremental AMT writer rejected such a leaf when it carried the leaf forward, so every later write on the table failed with: ``` [INTERNAL_ERROR] ManifestInfo representing a leaf's initial state must not contain both live files and tombstones. ``` Readers already skip a carried leaf's tombstones by entry status, so this writer check was the only thing in the way. This PR: - Removes the check and its alert. - Records a non-fatal usage log instead, once per incremental write that carries mixed leaves, with how many it carried. - Picks a carried leaf's tracking from its live files only. Before, any leaf with a tombstone went straight to DELETED, which would have dropped a mixed leaf's live files. - Assumes a manifest deletion vector masks live files only, as the path that adds new masking already does. A leaf becomes DELETED once its deletion vector covers all of its live files. A deletion vector that covers more entries than the leaf has live files fails the write with the `amt.commit.mdvExceedsLiveFiles` alert instead of guessing which entry is still live. The V4 spec wants a leaf MODIFIED in the commit that masks its last live file and DELETED in the next commit. The writer still marks it DELETED right away, as before. ## How was this patch tested? New tests in `AMTIncrementalWriteInvariantSuite`: - Unit tests for `carryForwardOneLeaf` with a mixed leaf (EXISTING, MODIFIED and DELETED outcomes), a mixed leaf an earlier commit fully or partly masked, a manifest deletion vector that masks more entries than the live files, and live-only and tombstone-only leaves for comparison. - An end-to-end test that swaps one leaf of a real AMT table for a copy with an extra DELETED entry, then runs INSERTs and DELETEs on top. At each step it checks the leaf's tracking, the change feed (the tombstone never shows up as a remove), and the table's rows. It also checks that the first write records the mixed-leaf usage log once. Without the fix, the first write fails with the error above. ## Does this PR introduce _any_ user-facing changes? No. This pull request and its description were written by Isaac. Co-authored-by: Isaac --- .../spark/sql/delta/amt/AMTUsageLogs.scala | 12 +- .../sql/delta/amt/IncrementalAMTWriter.scala | 55 ++- .../AMTIncrementalWriteInvariantSuite.scala | 345 +++++++++++++++++- .../spark/sql/delta/amt/AMTUtilsSuite.scala | 4 +- 4 files changed, 384 insertions(+), 32 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUsageLogs.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUsageLogs.scala index aff5d36f62a..bf4d394ac7a 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUsageLogs.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUsageLogs.scala @@ -48,6 +48,12 @@ object AMTUsageLogs { /** Usage log emitted when an AMT write fails unexpectedly. */ val WRITE_FAILED = s"$PREFIX.writeFailed" + /** + * Usage log emitted when an incremental AMT write carries forward leaves that hold both live + * files and tombstones. Other engines write such leaves; this writer never does. + */ + val INCREMENTAL_WRITE_MIXED_LEAVES_CARRIED = s"$PREFIX.incrementalWrite.mixedLeavesCarried" + // ////////////////////// Invariant check usage log suffixes ////////////////////// /** Usage log emitted when a logging-only invariant check unexpectedly throws in production. */ @@ -96,12 +102,12 @@ object AMTUsageLogs { val DELTA_AT_CHECKPOINT_VERSION_MISMATCH = "amt.logSegmentInvariant.deltaAtCheckpointVersionMismatch" - // A manifest_info contains both live files and tombstones. - val ALERT_MIXED_LEAF_CONTENT = "amt.mixedLeafContent" - // A leaf without live files gains new manifest deletion vector positions. val ALERT_MDV_WITHOUT_LIVE_FILES = "amt.commit.mdvWithoutLiveFiles" + // A leaf's manifest deletion vector masks more entries than the leaf has live files. + val ALERT_MDV_EXCEEDS_LIVE_FILES = "amt.commit.mdvExceedsLiveFiles" + // A back reference names a leaf manifest that is not a live leaf of the base tree. val ALERT_BACK_REFERENCE_NOT_IN_BASE_TREE = "amt.commit.backReferenceNotInBaseTree" diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala index fddfaf6b79d..22eff55278f 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala @@ -24,6 +24,7 @@ import org.apache.spark.sql.delta.{DeltaFileProviderUtils, DeltaLog, RangedSingl import org.apache.spark.sql.delta.RowId.RowTrackingMetadataDomain import org.apache.spark.sql.delta.actions.{Action, AddFile, BackReference, Checkpoint, ContentRoot, DomainMetadata, FileAction, InMemoryLogReplay, Metadata, Protocol, RemoveFile, SetTransaction} import org.apache.spark.sql.delta.actions.FileAction.UniqueFileActionTuple +import org.apache.spark.sql.delta.metering.DeltaLogging import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.util.FileNames import org.apache.hadoop.fs.{FileStatus, Path} @@ -75,7 +76,7 @@ import org.apache.spark.sql.SparkSession * - MODIFIED / EXISTING / DELETED -- same rule as ADDED, from this commit's masking. * - DELETED is terminal: the tombstone pointer is emitted once, then dropped from the next AMT. */ -class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) { +class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) extends DeltaLogging { private def entriesPerLeaf: Int = spark.sessionState.conf.getConf(DeltaSQLConf.AMT_ENTRIES_PER_LEAF) @@ -322,6 +323,20 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) { val deletedPositionsByLeaf = positionsByLeaf(cdfDeletedBackrefs) val replacedPositionsByLeaf = positionsByLeaf(cdfReplacedBackrefs) val carriedLeaves = oldLeaves.filter(_.tracking.status != Tracking.Status.Deleted) + // Leaves from other engines can hold both live files and tombstones. Log how often they + // reach this writer. + val numMixedLeaves = carriedLeaves.count { leaf => + leaf.manifest_info.liveFilesCount > 0 && leaf.manifest_info.tombstoneFilesCount > 0 + } + if (numMixedLeaves > 0) { + recordDeltaEvent( + deltaLog, + opType = AMTUsageLogs.INCREMENTAL_WRITE_MIXED_LEAVES_CARRIED, + data = Map( + "oldAMTVersion" -> oldAMTVersion, + "numMixedLeaves" -> numMixedLeaves, + "numCarriedLeaves" -> carriedLeaves.size)) + } // This writer masks positions only in the live leaves of the base tree. A back reference to // any other leaf manifest masks nothing, so its file stays live in this tree and every later // tree. @@ -360,15 +375,11 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) { snapshotId: Long): DataManifestEntry = { // The file counts in manifest_info describe the leaf when it was initially created. They are // not updated when the leaf is carried forward; only its manifest deletion vector can grow. + // This writer creates each leaf with only live files or only tombstones, but the V4 spec + // allows a leaf to hold both, and other engines write such leaves (e.g. Iceberg after a + // delete + insert). val liveFileCount = pointer.manifest_info.liveFilesCount val tombstoneFileCount = pointer.manifest_info.tombstoneFilesCount - AMTUtils.invariantCheckWithLogging( - checkInvariant = liveFileCount == 0 || tombstoneFileCount == 0, - opTypeSuffix = AMTUsageLogs.ALERT_MIXED_LEAF_CONTENT, - message = "ManifestInfo representing a leaf's initial state must not contain both live " + - "files and tombstones.", - deltaLog = deltaLog, - data = Map("liveFileCount" -> liveFileCount, "tombstoneFileCount" -> tombstoneFileCount)) AMTUtils.invariantCheckWithLogging( checkInvariant = newMdvPositions.isEmpty || liveFileCount > 0, opTypeSuffix = AMTUsageLogs.ALERT_MDV_WITHOUT_LIVE_FILES, @@ -380,22 +391,34 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) { "tombstoneFileCount" -> tombstoneFileCount, "newMdvPositionCount" -> newMdvPositions.size)) val (tracking, manifestInfo) = - if (tombstoneFileCount > 0) { + if (liveFileCount == 0) { // A carried leaf with no live file -- a tombstone-only leaf born ADDED last commit -- // decays to DELETED so the next AMT drops it. AMTWriteHelper.deletedTrackingForCarriedLeaf(pointer, snapshotId) } else { - // this case means tombstoneFileCount = 0 and liveFileCount >= 0 - // In this scenario, mark the leaf as DELETED if any of below is true: - // a) all live files are marked for deletion in this commit (with newMdvPositions) OR - // b) all the live files were already striked off in previous commit itself but the - // leaf was not marked as DELETED then (this is not done by our implementation but - // could be done by external engine). + // The leaf holds live files, and maybe tombstones from another engine. Its MDV masks only + // live files, so the MDV cardinality counts the masked live files. + val mdvCardinality = pointer.manifest_info.dvCardinality + AMTUtils.invariantCheckWithLogging( + checkInvariant = mdvCardinality <= liveFileCount, + opTypeSuffix = AMTUsageLogs.ALERT_MDV_EXCEEDS_LIVE_FILES, + message = s"Leaf ${pointer.location} has an MDV that masks $mdvCardinality entries " + + s"but holds only $liveFileCount live files.", + deltaLog = deltaLog, + data = Map( + "leafLocation" -> pointer.location, + "liveFileCount" -> liveFileCount, + "tombstoneFileCount" -> tombstoneFileCount, + "mdvCardinality" -> mdvCardinality)) + // Mark the leaf as DELETED if any of below is true: + // a) this commit masks its last live files (with newMdvPositions) OR + // b) an earlier commit masked every live file but left the leaf live. This writer does + // not do that, but other engines can. if (newMdvPositions.nonEmpty) { // The MDV grew this commit: MODIFIED, or DELETED once every live entry is masked. AMTWriteHelper.modifiedOrDeletedTrackingForLeaf( pointer, newMdvPositions, deletedPositions, replacedPositions, snapshotId) - } else if (pointer.manifest_info.dvCardinality == pointer.record_count) { + } else if (mdvCardinality == liveFileCount) { AMTWriteHelper.deletedTrackingForCarriedLeaf(pointer, snapshotId) } else { // Untouched leaf (no new MDVs) that still holds live files: carry it forward EXISTING. diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTIncrementalWriteInvariantSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTIncrementalWriteInvariantSuite.scala index 52c08688be3..6cfdcb9cd01 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTIncrementalWriteInvariantSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTIncrementalWriteInvariantSuite.scala @@ -16,14 +16,22 @@ package org.apache.spark.sql.delta.amt -import org.apache.spark.sql.delta.DeltaOperations -import org.apache.spark.sql.delta.actions.{Action, AddFile, Metadata, Protocol} +import com.databricks.spark.util.{Log4jUsageLogger, MetricDefinitions} +import org.apache.spark.sql.delta.{DeltaLog, DeltaOperations} +import org.apache.spark.sql.delta.actions.{Action, AddFile, Checkpoint, ContentRoot, Metadata, Protocol, RemoveFile} +import org.apache.spark.sql.delta.deletionvectors.ManifestBitmap import org.apache.spark.sql.delta.sources.DeltaSQLConf -import org.apache.spark.sql.delta.util.FileNames +import org.apache.spark.sql.delta.util.{FileNames, JsonUtils} +import org.apache.hadoop.fs.Path + +import org.apache.spark.paths.SparkPath +import org.apache.spark.sql.functions.{col, lit} /** Invariant enforcement: rejecting commits that break a write- or commit-shape invariant. */ class AMTIncrementalWriteInvariantSuite extends AMTIncrementalWriteTestBase { + import testImplicits._ + private def processedActions( oldRootAdds: Seq[AddFile], actionsToCommit: Seq[Action]): ProcessedActions = @@ -201,13 +209,17 @@ class AMTIncrementalWriteInvariantSuite extends AMTIncrementalWriteTestBase { assert(refresh.reCommittedLiveAdd.isDefined) } - /** A carried leaf pointer whose manifest_info carries the given per-status file counts. */ + /** + * A carried leaf pointer whose manifest_info carries the given per-status file counts and, if + * `mdvPositions` is non-empty, a manifest DV that an earlier commit set at those positions. + */ private def carriedLeafPointer( addedFiles: Int = 0, existingFiles: Int = 0, deletedFiles: Int = 0, replacedFiles: Int = 0, - modifiedFiles: Int = 0): DataManifestEntry = + modifiedFiles: Int = 0, + mdvPositions: Seq[Int] = Seq.empty): DataManifestEntry = DataManifestEntry( location = "metadata/leaf-guard.parquet", file_format = AMTSingleAction.FileFormatParquet, @@ -226,20 +238,107 @@ class AMTIncrementalWriteInvariantSuite extends AMTIncrementalWriteTestBase { modified_files_count = modifiedFiles, added_rows_count = 0L, existing_rows_count = 0L, deleted_rows_count = 0L, replaced_rows_count = 0L, modified_rows_count = 0L, - min_sequence_number = 0L, dv = None)) + min_sequence_number = 0L, + dv = + if (mdvPositions.isEmpty) None + else Some(AMTUtils.serializeMdv(ManifestBitmap.fromPositions(mdvPositions))))) + + // Other engines (e.g. Iceberg after a delete + insert) can write a leaf that holds both live + // files and tombstones. The carried leaf's tracking must follow its live files only. + test("carryForwardOneLeaf keeps an untouched leaf mixing live files and tombstones EXISTING") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + val mixed = carriedLeafPointer(existingFiles = 2, deletedFiles = 1) + val carried = writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq.empty, + deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Existing) + assert(carried.manifest_info == mixed.manifest_info) + } + } + + test("carryForwardOneLeaf marks a mixed leaf MODIFIED when some live files are masked") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + // Positions 0 and 1 are the live files; position 2 is the tombstone. + val mixed = carriedLeafPointer(existingFiles = 2, deletedFiles = 1) + val carried = writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq(0), + deletedPositions = Seq(0), replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Modified) + assert(carried.manifest_info.dvCardinality == 1L) + } + } - test("carryForwardOneLeaf rejects a carried leaf mixing live files and tombstones") { + test("carryForwardOneLeaf marks a mixed leaf DELETED when all live files are masked") { withTables() { (_, amtDeltaLog) => val writer = new IncrementalAMTWriter(spark, amtDeltaLog) - // A carried leaf whose manifest_info counts both a live file and a tombstone is a corrupt - // shape the writer does not support. val mixed = carriedLeafPointer(existingFiles = 2, deletedFiles = 1) + val carried = writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq(0, 1), + deletedPositions = Seq(0, 1), replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Deleted) + assert(carried.tracking.snapshot_id.contains(1L)) + } + } + + test("carryForwardOneLeaf drops a mixed leaf whose earlier MDV masks every live file") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + // Another engine masked both live files (positions 0 and 1) but left the leaf live. + val mixed = carriedLeafPointer(existingFiles = 2, deletedFiles = 1, mdvPositions = Seq(0, 1)) + val carried = writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq.empty, + deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Deleted) + assert(carried.tracking.snapshot_id.contains(1L)) + assert(carried.manifest_info == mixed.manifest_info) + } + } + + test("carryForwardOneLeaf keeps a mixed leaf EXISTING when an earlier MDV masks part of it") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + // Position 1 is still live, so the leaf stays even though the MDV and tombstone cover two + // of its three entries. + val mixed = carriedLeafPointer(existingFiles = 2, deletedFiles = 1, mdvPositions = Seq(0)) + val carried = writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq.empty, + deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Existing) + assert(carried.manifest_info == mixed.manifest_info) + } + } + + test("carryForwardOneLeaf rejects an MDV that masks more entries than the live files") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + // Three masked positions but only two live files: the MDV masks the tombstone too. + val mixed = + carriedLeafPointer(existingFiles = 2, deletedFiles = 1, mdvPositions = Seq(0, 1, 2)) val ex = intercept[IllegalStateException] { writer.carryForwardOneLeaf(mixed, newMdvPositions = Seq.empty, deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) } - assert(ex.getMessage.contains("both live files and tombstones"), - s"expected the live+tombstone-mix invariant; got: ${ex.getMessage}") + assert(ex.getMessage.contains("masks 3 entries but holds only 2 live files"), + s"expected the MDV-exceeds-live-files invariant; got: ${ex.getMessage}") + } + } + + test("carryForwardOneLeaf drops a live-only leaf whose earlier MDV masks every entry") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + val masked = carriedLeafPointer(existingFiles = 2, mdvPositions = Seq(0, 1)) + val carried = writer.carryForwardOneLeaf(masked, newMdvPositions = Seq.empty, + deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Deleted) + assert(carried.tracking.snapshot_id.contains(1L)) + } + } + + test("carryForwardOneLeaf drops a tombstone-only leaf") { + withTables() { (_, amtDeltaLog) => + val writer = new IncrementalAMTWriter(spark, amtDeltaLog) + val tombstoneOnly = carriedLeafPointer(deletedFiles = 2, replacedFiles = 1) + val carried = writer.carryForwardOneLeaf(tombstoneOnly, newMdvPositions = Seq.empty, + deletedPositions = Seq.empty, replacedPositions = Seq.empty, snapshotId = 1L) + assert(carried.tracking.status == Tracking.Status.Deleted) + assert(carried.manifest_info == tombstoneOnly.manifest_info) } } @@ -257,4 +356,228 @@ class AMTIncrementalWriteInvariantSuite extends AMTIncrementalWriteTestBase { s"expected the dead-leaf-MDV invariant; got: ${ex.getMessage}") } } + + private val ghostLocation = "ghost-removed-by-other-engine.parquet" + + /** The leaf entry locations of `leaf`, in physical order. */ + private def leafLocations(deltaLog: DeltaLog, leaf: DataManifestEntry): Seq[String] = + allowReadWithinDeltaLog { + spark.read.parquet(leaf.getAbsolutePath(deltaLog.dataPath).toString) + .orderBy(col("_metadata.row_index")) + .select(col("location")).as[String].collect().toSeq + } + + /** + * Writes a copy of `leaf` with one DELETED entry appended after its live entries, and returns + * the root pointer for the copy. The live entries keep their positions. + */ + private def writeMixedLeaf( + deltaLog: DeltaLog, + checkpoint: Checkpoint, + leaf: DataManifestEntry): DataManifestEntry = { + val tableRoot = deltaLog.dataPath + val hadoopConf = deltaLog.newDeltaHadoopConf() + val schema = AMTSingleAction.persistedSchema(checkpoint.metaData, checkpoint.protocol) + val mixedLeafFile = FileNames.newAMTLeafManifestFile(FileNames.amtMetadataDirPath(tableRoot)) + val fs = mixedLeafFile.getFileSystem(hadoopConf) + val staging = new Path(tableRoot, "_staging_mixed_leaf") + val ghostRecordCount = allowReadWithinDeltaLog { + val entries = spark.read.schema(schema).parquet(leaf.getAbsolutePath(tableRoot).toString) + // The read schema is the persisted one made nullable. Casting back to it keeps the Parquet + // field ids (nested ones included) that the reader resolves columns by. + val tombstone = entries.limit(1).select(entries.schema.fields.toIndexedSeq.map { field => + val value = field.name match { + case "location" => lit(ghostLocation) + case "tracking" => + col("tracking").withField("status", lit(Tracking.Status.Deleted)) + case _ => col(field.name) + } + value.cast(field.dataType).as(field.name, field.metadata) + }: _*) + // Union does not keep row order, so sort on each row's position with the tombstone last. + val position = "_mixed_leaf_position" + entries.withColumn(position, col("_metadata.row_index")) + .union(tombstone.withColumn(position, lit(Long.MaxValue))) + .repartition(1) + .sortWithinPartitions(position) + .drop(position) + .write.parquet(staging.toString) + tombstone.select(col("record_count")).as[Long].head() + } + val part = fs.listStatus(staging).map(_.getPath).find(_.getName.endsWith(".parquet")) + .getOrElse(fail("the staged mixed leaf must have a parquet file")) + assert(fs.rename(part, mixedLeafFile)) + fs.delete(staging, true) + + val mixed = leaf.copy( + location = AMTUtils.relativizeLocation(tableRoot.toString, mixedLeafFile.toString), + file_size_in_bytes = fs.getFileStatus(mixedLeafFile).getLen, + record_count = leaf.record_count + 1, + manifest_info = leaf.manifest_info.copy( + deleted_files_count = leaf.manifest_info.deleted_files_count + 1, + deleted_rows_count = leaf.manifest_info.deleted_rows_count + ghostRecordCount)) + assert(leafLocations(deltaLog, mixed) == leafLocations(deltaLog, leaf) :+ ghostLocation, + "the mixed leaf must keep the live entries in place and append the tombstone") + mixed + } + + /** + * Points the table's current manifest tree at a new root in which `leaf` is replaced by a copy + * that also holds a tombstone. Returns the mixed leaf's root pointer. + */ + private def installMixedLeaf( + tableName: String, + deltaLog: DeltaLog, + leaf: DataManifestEntry): DataManifestEntry = { + val snapshot = deltaLog.update() + val provider = amtProvider(snapshot).getOrElse(fail("expected an AMT-backed snapshot")) + val checkpoint = provider.checkpointAction + val tableRoot = deltaLog.dataPath + val hadoopConf = deltaLog.newDeltaHadoopConf() + val oldRoot = checkpoint.contentRoot.getAbsolutePath(tableRoot).toString + assert(withManifestDataEntries(Seq(oldRoot))(_.count()) == 0, + "the root must hold only leaf pointers, so rebuilding it from them loses nothing") + + val mixed = writeMixedLeaf(deltaLog, checkpoint, leaf) + val rootFile = FileNames.newAMTRootManifestFile(FileNames.amtMetadataDirPath(tableRoot)) + val rootEntries = provider.leaves.map(l => if (l.location == leaf.location) mixed else l) + AMTWriteHelper.writeAMTParquet( + spark, hadoopConf, rootFile, checkpoint.metaData, checkpoint.protocol, + rootEntries.map(_.wrap)) + val newCheckpoint = updateCheckpointActions(checkpoint) { + case root: ContentRoot => root.copy( + path = AMTUtils.relativizeLocation(tableRoot.toString, rootFile.toString), + sizeInBytes = rootFile.getFileSystem(hadoopConf).getFileStatus(rootFile).getLen) + } + + // Backfill first, so the commit coordinator no longer serves the staged copy of the manifest + // commit, and rewrite the backfilled file. + snapshot.ensureCommitFilesBackfilled(Some(catalogTableFor(tableName))) + val commitPath = FileNames.unsafeDeltaFile(deltaLog.logPath, provider.manifestCommitVersion) + val actions = deltaLog.store.read(commitPath, hadoopConf).map(Action.fromJson) + assert(actions.count(_.isInstanceOf[Checkpoint]) == 1) + val rewritten = actions.map { + case _: Checkpoint => newCheckpoint.json + case action => action.json + } + deltaLog.store.write(commitPath, rewritten.iterator, overwrite = true, hadoopConf) + // The hint carries the whole Checkpoint, so a stale one would point at the old root. + deltaLog.LAST_CHECKPOINT.getFileSystem(hadoopConf).delete(deltaLog.LAST_CHECKPOINT, false) + DeltaLog.clearCache() + mixed + } + + /** The current tree's pointer for the leaf at `location`, if the tree still lists it. */ + private def currentLeaf(tableName: String, location: String): Option[DataManifestEntry] = + amtProvider(deltaLogForName(tableName).update()) + .getOrElse(fail("expected an AMT-backed snapshot")) + .leaves.find(_.location == location) + + /** The decoded file name of a URL-encoded path, as AddFile, RemoveFile and _metadata use. */ + private def fileName(urlEncodedPath: String): String = + SparkPath.fromUrlString(urlEncodedPath).toPath.getName + + /** File names of the RemoveFile and AddFile actions the current tree reconstructs. */ + private def reconstructedChanges(tableName: String): (Set[String], Set[String]) = { + val deltaLog = deltaLogForName(tableName) + val actions = amtProvider(deltaLog.update()) + .getOrElse(fail("expected an AMT-backed snapshot")) + .reconstructFileActions(deltaLog, dataChange = true, commitTimestamp = 0L) + def names(paths: Seq[String]): Set[String] = paths.map(fileName).toSet + (names(actions.collect { case r: RemoveFile => r.path }), + names(actions.collect { case a: AddFile => a.path })) + } + + private def ids(tableName: String): Seq[Int] = + sql(s"SELECT id FROM $tableName").as[Int].collect().toSeq.sorted + + // Unlike the carryForwardOneLeaf tests above, this runs real Delta writes on a table whose tree + // holds a mixed leaf, so it also covers the change feed and the table's rows. + test("Delta writes carry a leaf mixing live files and tombstones through every leaf state") { + val tableName = "amt_mixed_leaf" + withSQLConf(leafPackingConfs ++ Seq( + DeltaSQLConf.AMT_LARGE_COMMIT_ACTIONS_COUNT_THRESHOLD_FOR_INLINE_MANIFEST_COMMIT.key -> + Int.MaxValue.toString): _*) { + withTable(tableName) { + createAMTTable(tableName, checkpointInterval = 1000) + appendRowsAsSeparateFiles(tableName, leafPackedFiles) + val originalLog = deltaLogForName(tableName) + commitCheckpoint(originalLog, incremental = false) + val leaves = amtProvider(originalLog.update()) + .getOrElse(fail("expected an AMT-backed snapshot")).leaves + assertLeafCount(leaves) + val mixed = installMixedLeaf(tableName, originalLog, leaves.head) + // The cache was cleared, so this log loads the installed tree. + val deltaLog = deltaLogForName(tableName) + val idByFileName = sql(s"SELECT id, _metadata.file_path FROM $tableName") + .as[(Int, String)].collect().map { case (id, path) => fileName(path) -> id }.toMap + // Leaf entries store decoded paths. + val liveFileNames = leafLocations(deltaLog, mixed).dropRight(1).map(new Path(_).getName) + val liveIds = liveFileNames.map(idByFileName) + val allIds = (0 until leafPackedFiles) + + // The reader sees the mixed leaf and skips its tombstone. + val installed = currentLeaf(tableName, mixed.location) + .getOrElse(fail("the installed tree must list the mixed leaf")) + assert(installed.manifest_info.liveFilesCount == liveIds.size) + assert(installed.manifest_info.tombstoneFilesCount == 1) + assert(ids(tableName) == allIds) + + // An insert leaves the mixed leaf untouched: it is carried forward EXISTING, and the + // write logs that it carried one mixed leaf. + val insertedId = leafPackedFiles + val mixedLeafEvents = Log4jUsageLogger.track { + sql(s"INSERT INTO $tableName VALUES ($insertedId)") + commitCheckpoint(deltaLog, incremental = true) + }.filter(e => e.metric == MetricDefinitions.EVENT_TAHOE.name && + e.tags.get("opType").contains(AMTUsageLogs.INCREMENTAL_WRITE_MIXED_LEAVES_CARRIED)) + assert(mixedLeafEvents.size == 1, + s"expected one mixed-leaf usage log, got $mixedLeafEvents") + val mixedLeafEventData = JsonUtils.fromJson[Map[String, Any]](mixedLeafEvents.head.blob) + assert(mixedLeafEventData("numMixedLeaves").toString == "1") + assert(mixedLeafEventData("numCarriedLeaves").toString == leaves.size.toString) + val untouched = currentLeaf(tableName, mixed.location) + .getOrElse(fail("an untouched mixed leaf must stay in the tree")) + assert(untouched.tracking.status == Tracking.Status.Existing) + assert(untouched.manifest_info == mixed.manifest_info) + assert(ids(tableName) == allIds :+ insertedId) + + // Deleting one live file masks it: MODIFIED, and the change feed removes only that file. + // The DELETEs write their trees inline, since only then does a tree carry the commit's + // change-feed positions. + withInline { + sql(s"DELETE FROM $tableName WHERE id = ${liveIds.head}") + } + val modified = currentLeaf(tableName, mixed.location) + .getOrElse(fail("a partly masked mixed leaf must stay in the tree")) + assert(modified.tracking.status == Tracking.Status.Modified) + assert(modified.manifest_info.dvCardinality == 1L) + val deletedPositions = modified.tracking.deleted_positions + .map(ManifestBitmap.fromSerializedByteArray) + .getOrElse(fail("the MODIFIED leaf must record this commit's deleted positions")) + assert(deletedPositions.cardinality == 1L && deletedPositions.contains(0)) + assert(reconstructedChanges(tableName) == ((Set(liveFileNames.head), Set.empty[String]))) + assert(ids(tableName) == (allIds :+ insertedId).filterNot(_ == liveIds.head)) + + // Deleting the remaining live files masks every live entry: DELETED, even though the + // leaf still holds its tombstone. + withInline { + sql(s"DELETE FROM $tableName WHERE id IN (${liveIds.tail.mkString(", ")})") + } + val deleted = currentLeaf(tableName, mixed.location) + .getOrElse(fail("the DELETED pointer must be emitted once")) + assert(deleted.tracking.status == Tracking.Status.Deleted) + assert(reconstructedChanges(tableName) == + ((liveFileNames.tail.toSet, Set.empty[String]))) + val remainingIds = (allIds :+ insertedId).filterNot(liveIds.contains) + assert(ids(tableName) == remainingIds) + + // The next tree drops the DELETED leaf. + sql(s"INSERT INTO $tableName VALUES (${insertedId + 1})") + commitCheckpoint(deltaLog, incremental = true) + assert(currentLeaf(tableName, mixed.location).isEmpty) + assert(ids(tableName) == remainingIds :+ (insertedId + 1)) + } + } + } } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala index 21c363f945c..64268425d72 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTUtilsSuite.scala @@ -66,7 +66,7 @@ class AMTUtilsSuite extends QueryTest with SharedSparkSession { test("invariantCheckWithLogging: succeeds when the invariant holds") { AMTUtils.invariantCheckWithLogging( checkInvariant = true, - opTypeSuffix = AMTUsageLogs.ALERT_MIXED_LEAF_CONTENT, + opTypeSuffix = AMTUsageLogs.ALERT_MDV_WITHOUT_LIVE_FILES, message = "valid AMT invariant") } @@ -78,7 +78,7 @@ class AMTUtilsSuite extends QueryTest with SharedSparkSession { checkCount += 1 true }, - opTypeSuffix = AMTUsageLogs.ALERT_MIXED_LEAF_CONTENT, + opTypeSuffix = AMTUsageLogs.ALERT_MDV_WITHOUT_LIVE_FILES, message = "valid AMT invariant") assert(checkCount === 1) } From 456d7167f8ab6525d73685cc9d214e41b1ebfa51 Mon Sep 17 00:00:00 2001 From: Jinhua Song <114370144+PhilPlato@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:09:46 -0800 Subject: [PATCH 33/44] [Spark] Reuse the written AMT root rows for the next commit (#8172) ## Description When a snapshot discovers an AMT checkpoint from storage, the columnar provider can keep the root's rows in memory and reuse them. A warm commit does not go through discovery: it builds the next provider from `AMTWriteResult`, which only carried the leaf pointers. So the next incremental AMT write had to read the root Parquet file again. This PR carries the complete `AMTRootInfo`, leaf pointers plus any cached root rows, through `AMTWriteResult`. It keeps the rows the writer produced when the root is below the root-cache threshold: - Incremental writes and multi-leaf full writes keep the rows built on the driver to write the root. - When a full write produces a single leaf that is promoted to the root, no rows are kept, and the next commit reads that root from storage. The writer and discovery use the same check, `AMTUtils.shouldCacheRootRows`: columnar state reconstruction is enabled and the root has fewer entries than `amt.rootCache.maxNumEntries`. The cached rows are copied into unsafe rows so they don't depend on the writer's buffers. Turning the written rows into a local relation now applies `ConvertToLocalRelation` until the plan stops changing (`AMTUtils.convertToLocalRelationFully`). When the rule visits the plan top-down, one application folds only the projection directly above the local relation, which made the writer silently skip caching. The writer now asserts that the rows fold to a local relation. Decoding leaf pointers from a cached root uses the same helper. No extra Spark scan is added. Large roots, and the case where root caching is off (`amt.rootCache.maxNumEntries` = 0), keep reading the root from storage as before. This PR also raises the default of `amt.rootCache.maxNumEntries` from 12000 to 50000. ## How was this patch tested? New tests in `AMTSnapshotDiscoverySuite`: - After a warm commit, the columnar provider reuses the root rows the writer produced. - The writer does not keep root rows when the root is at or above the threshold, or when caching is off. - Discovering a cached root decodes its leaf pointers without launching another Spark job. `LastCheckpointInfoSuite` is updated for the new `AMTWriteResult` shape. ## Does this PR introduce _any_ user-facing changes? No. Co-authored-by: Jinhua Song --- .../apache/spark/sql/delta/Checkpoints.scala | 6 +- .../sql/delta/amt/AMTCheckpointProvider.scala | 29 +++--- .../apache/spark/sql/delta/amt/AMTUtils.scala | 24 +++++ .../spark/sql/delta/amt/AMTWriteHelper.scala | 78 +++++++++++----- .../sql/delta/amt/AMTWriterManager.scala | 8 +- .../sql/delta/amt/IncrementalAMTWriter.scala | 8 +- .../sql/delta/sources/DeltaSQLConf.scala | 10 +-- .../sql/delta/LastCheckpointInfoSuite.scala | 8 +- .../delta/amt/AMTSnapshotDiscoverySuite.scala | 88 +++++++++++++++++++ 9 files changed, 203 insertions(+), 56 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala b/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala index 85186320092..e24b2b95437 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/Checkpoints.scala @@ -400,9 +400,11 @@ trait Checkpoints extends DeltaLogging { def writeLastCheckpointFileForAMT( manifestCommitVersion: Long, writeResult: AMTWriteResult): Unit = { - val AMTWriteResult(contentRootVersion, checkpoint, leaves, _, _) = writeResult val lastCheckpointInfo = Checkpoints.buildLastCheckpointInfoForAMT( - manifestCommitVersion, contentRootVersion, checkpoint, leaves) + manifestCommitVersion, + writeResult.contentRootVersion, + writeResult.checkpoint, + writeResult.leaves) writeLastCheckpointFile(this, lastCheckpointInfo, LastCheckpointInfo.checksumEnabled(spark)) } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala index ff98e5e2748..d46fe208a80 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTCheckpointProvider.scala @@ -42,7 +42,6 @@ import org.apache.spark.sql.{Column, DataFrame, Dataset, Encoder, Row, SparkSess import org.apache.spark.sql.catalyst.InternalRow import org.apache.spark.sql.catalyst.catalog.CatalogTable import org.apache.spark.sql.catalyst.expressions.Literal -import org.apache.spark.sql.catalyst.optimizer.ConvertToLocalRelation import org.apache.spark.sql.catalyst.plans.logical.LocalRelation import org.apache.spark.sql.catalyst.types.DataTypeUtils.toAttributes import org.apache.spark.sql.execution.datasources.FileFormat.{FILE_PATH, METADATA_NAME} @@ -52,8 +51,8 @@ import org.apache.spark.sql.functions.{coalesce, col, element_at, lit, struct, s import org.apache.spark.sql.types.{IntegerType, LongType, MapType, StringType, StructField, StructType} /** - * Leaf pointers and optional cached root rows. The cached schema is the root Parquet read schema, - * based on [[AMTSingleAction.persistedSchema]]. Rows contain DATA and DATA_MANIFEST entries as + * Leaf pointers and optional cached root rows. The cached schema is + * [[AMTSingleAction.persistedSchema]]. Rows contain DATA and DATA_MANIFEST entries as * [[InternalRow]]s, with partition and content_stats kept as typed structs when present. */ private[delta] class AMTRootInfo( @@ -1243,18 +1242,17 @@ object AMTCheckpointProvider extends DeltaLogging { if (field.name == "content_type") field.copy(nullable = true) else field }) val persisted = deltaLog.loadIndex(index, readSchema) - val maxNumEntries = spark.sessionState.conf - .getConf(DeltaSQLConf.AMT_ROOT_CACHE_MAX_NUM_ENTRIES) // Decide before collecting rows so large roots only return leaf pointers to the driver. - val cacheRoot = maxNumEntries > 0 && - Snapshot.getParquetFileSchemaAndRowCount(spark, deltaLog, rootFile)._2 < maxNumEntries - val cachedRows = if (cacheRoot) { - Some((persisted.schema, persisted.queryExecution.executedPlan.executeCollect().toSeq)) + val cacheRoot = AMTUtils.shouldCacheRootRows( + spark, + Snapshot.getParquetFileSchemaAndRowCount(spark, deltaLog, rootFile)._2) + val collectedRows = if (cacheRoot) { + Some(persisted.queryExecution.executedPlan.executeCollect().toSeq) } else { None } - val rootEntries = cachedRows.map { case (schema, rows) => - DataFrameUtils.ofRows(spark, LocalRelation(toAttributes(schema), rows)) + val rootEntries = collectedRows.map { rows => + DataFrameUtils.ofRows(spark, LocalRelation(toAttributes(persisted.schema), rows)) }.getOrElse(persisted) // Decode pointers and reject unsupported entry kinds without decoding DATA rows. val pointers = rootEntries.where( @@ -1263,14 +1261,15 @@ object AMTCheckpointProvider extends DeltaLogging { val decodedPointers = decodeEntries(pointers, checkpoint.metaData, checkpoint.protocol) val pointersToCollect = if (cacheRoot) { // Evaluate these projections locally even when the general optimizer disables this rule. - DataFrameUtils - .ofRows(spark, ConvertToLocalRelation(decodedPointers.queryExecution.analyzed)) - .as[AMTSingleAction](decodedPointers.encoder) + val localPointers = + AMTUtils.convertToLocalRelationFully(decodedPointers.queryExecution.analyzed) + DataFrameUtils.ofRows(spark, localPointers).as[AMTSingleAction](decodedPointers.encoder) } else { decodedPointers } val leaves = pointersToCollect .collect().toSeq.map(_.unwrap.asInstanceOf[DataManifestEntry]) + val cachedRows = collectedRows.map(persistedSchema -> _) new AMTRootInfo(leaves, cachedRows) } recordDeltaEvent( @@ -1299,7 +1298,7 @@ object AMTCheckpointProvider extends DeltaLogging { spark = spark, manifestCommitVersion = manifestCommitVersion, checkpointAction = writeResult.checkpoint, - leaves = writeResult.leaves, + rootInfo = writeResult.rootInfo, tableRoot = deltaLog.dataPath) } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala index f52120b4831..d75314d2a30 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTUtils.scala @@ -16,16 +16,20 @@ package org.apache.spark.sql.delta.amt +import scala.annotation.tailrec import scala.util.control.NonFatal import org.apache.spark.sql.delta.{AdaptiveMetadataPreviewTableFeature, AdaptiveMetadataTableFeature, AdaptiveMetadataTableFeatureBase, CurrentTransactionInfo, DeltaConfigs, DeltaErrors, DeltaIllegalStateException, DeltaLog, FeatureAutomaticallyEnabledByMetadata, Snapshot, SnapshotDescriptor, TableFeature, WinningCommitSummary} import org.apache.spark.sql.delta.actions.{Checkpoint, LastManifestCommit, Metadata, Protocol, TableFeatureProtocolUtils} import org.apache.spark.sql.delta.deletionvectors.ManifestBitmap import org.apache.spark.sql.delta.metering.DeltaLogging +import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.util.{Utils => DeltaUtils} import org.apache.hadoop.fs.Path import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.optimizer.ConvertToLocalRelation +import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan /** * Path helpers for AMT (Adaptive Metadata Tree) manifest files. @@ -324,4 +328,24 @@ object AMTUtils extends DeltaLogging { // Deserializes a Manifest Deletion Vector previously written by [[serializeMdv]]. private[amt] def deserializeMdv(bytes: Array[Byte]): ManifestBitmap = ManifestBitmap.fromSerializedByteArray(bytes) + + private[amt] def shouldCacheRootRows( + spark: SparkSession, + numEntries: => Long): Boolean = { + val columnarEnabled = spark.sessionState.conf + .getConf(DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED) + val maxNumEntries = spark.sessionState.conf + .getConf(DeltaSQLConf.AMT_ROOT_CACHE_MAX_NUM_ENTRIES) + columnarEnabled && maxNumEntries > 0 && numEntries < maxNumEntries + } + + /** + * Applies [[ConvertToLocalRelation]] until the plan stops changing. When the rule visits the plan + * top-down, one application folds only the `Project` directly above the `LocalRelation`. + */ + @tailrec + private[amt] def convertToLocalRelationFully(plan: LogicalPlan): LogicalPlan = { + val converted = ConvertToLocalRelation(plan) + if (converted.fastEquals(plan)) plan else convertToLocalRelationFully(converted) + } } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriteHelper.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriteHelper.scala index cad288902dc..2a6672767eb 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriteHelper.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriteHelper.scala @@ -19,7 +19,7 @@ package org.apache.spark.sql.delta.amt import java.util.concurrent.TimeUnit.NANOSECONDS // scalastyle:off import.ordering.noEmptyLine -import org.apache.spark.sql.delta.{Checkpoints, DeltaLog, RowId, Snapshot} +import org.apache.spark.sql.delta.{Checkpoints, DataFrameUtils, DeltaLog, RowId, Snapshot} import org.apache.spark.sql.delta.actions.{AddFile, Checkpoint, ContentRoot, DomainMetadata, Metadata, Protocol, SetTransaction} import org.apache.spark.sql.delta.deletionvectors.ManifestBitmap import org.apache.spark.sql.delta.metering.DeltaLogging @@ -32,6 +32,9 @@ import org.apache.hadoop.mapreduce.Job import org.apache.spark.TaskContext import org.apache.spark.paths.SparkPath import org.apache.spark.sql.{DataFrame, SparkSession} +import org.apache.spark.sql.catalyst.InternalRow +import org.apache.spark.sql.catalyst.expressions.UnsafeProjection +import org.apache.spark.sql.catalyst.plans.logical.LocalRelation import org.apache.spark.sql.execution.SQLExecution import org.apache.spark.sql.functions.{col, hash, struct} import org.apache.spark.sql.types.StructType @@ -40,6 +43,10 @@ import org.apache.spark.util.SerializableConfiguration /** Helpers for emitting an inline AMT checkpoint during a commit. */ object AMTWriteHelper extends DeltaLogging { + private[amt] case class WrittenRoot( + contentRoot: ContentRoot, + cachedRows: Option[(StructType, Seq[InternalRow])]) + /** * Writes a new AMT from scratch representing the readSnapshot content metadata. Unlike the * driver-side incremental path, the live file set is clustered and flushed into leaves by @@ -120,14 +127,14 @@ object AMTWriteHelper extends DeltaLogging { contentRoot = contentRoot, numRootLiveDataEntries = clusteredWrite.numRootLiveDataEntries, numRootTombstoneDataEntries = clusteredWrite.numRootTombstoneDataEntries, - leaves = clusteredWrite.leaves, + leaves = clusteredWrite.rootInfo.leaves, numSetTransactions = txns.size.toLong, numDomainMetadata = domainMetadata.size.toLong, incrementalWriteMetrics = None) AMTWriteResult( contentRootVersion = contentTreeVersion, checkpoint = checkpoint, - leaves = clusteredWrite.leaves, + rootInfo = clusteredWrite.rootInfo, includeActionsInCommitJson = true, amtWriteMetrics = singleMetric) } @@ -144,8 +151,8 @@ object AMTWriteHelper extends DeltaLogging { * The outcome of [[writeClusteredManifestTree]]. * * @param contentRoot the written root manifest pointer. - * @param leaves the per-leaf [[DataManifestEntry]] pointers; empty for a promoted - * single-manifest checkpoint. + * @param rootInfo the root's leaf pointers and any cached rows retained while + * writing it * @param numRootLiveDataEntries live DATA files resident in the root manifest itself: the * promoted manifest's live file count when promoted, else 0 (a * multi-leaf root holds only pointers, no DATA entries). @@ -155,7 +162,7 @@ object AMTWriteHelper extends DeltaLogging { */ private case class AMTClusteredWriteResult( contentRoot: ContentRoot, - leaves: Seq[DataManifestEntry], + rootInfo: AMTRootInfo, numRootLiveDataEntries: Long, numRootTombstoneDataEntries: Long) @@ -217,12 +224,12 @@ object AMTWriteHelper extends DeltaLogging { numLeaves = 0L) AMTClusteredWriteResult( contentRoot, - leaves = Seq.empty, + rootInfo = new AMTRootInfo(leaves = Seq.empty, cachedRows = None), numRootLiveDataEntries = onlyLeaf.manifest_info.liveFilesCount.toLong, numRootTombstoneDataEntries = onlyLeaf.manifest_info.tombstoneFilesCount.toLong) case _ => // The root lists one pointer per leaf and holds no DATA entries of its own. - val baseRoot = writeRoot( + val writtenRoot = writeRoot( spark = spark, fs = fs, hadoopConf = hadoopConf, @@ -233,15 +240,15 @@ object AMTWriteHelper extends DeltaLogging { rows = leafEntries.map(_.wrap), version = contentTreeVersion) val contentRoot = ContentRoot( - path = baseRoot.path, - sizeInBytes = baseRoot.sizeInBytes, + path = writtenRoot.contentRoot.path, + sizeInBytes = writtenRoot.contentRoot.sizeInBytes, version = contentTreeVersion, isIncremental = false, lastManifestCommitWithFullRewrite = contentTreeVersion, numLeaves = leafEntries.size.toLong) AMTClusteredWriteResult( contentRoot, - leaves = leafEntries, + rootInfo = new AMTRootInfo(leafEntries, writtenRoot.cachedRows), numRootLiveDataEntries = 0L, numRootTombstoneDataEntries = 0L) } @@ -593,10 +600,9 @@ object AMTWriteHelper extends DeltaLogging { } /** - * Writes the root parquet file from a pre-built row set and returns a [[ContentRoot]] - * carrying its path, size, and version. The rows may be `DATA_MANIFEST` leaf pointers, - * root-resident `DATA` entries, or both. Callers still attach tags before embedding it in a - * [[Checkpoint]]. + * Writes the root parquet file from a pre-built row set. The rows may be `DATA_MANIFEST` leaf + * pointers, root-resident `DATA` entries, or both. Retains the persisted rows when the root is + * below the cache threshold, so the post-commit provider can reuse them. */ private[amt] def writeRoot( spark: SparkSession, @@ -607,14 +613,18 @@ object AMTWriteHelper extends DeltaLogging { metadata: Metadata, protocol: Protocol, rows: Seq[AMTSingleAction], - version: Long): ContentRoot = { + version: Long): WrittenRoot = { val rootFile = FileNames.newAMTRootManifestFile(metadataDir) - writeAMTParquet(spark, hadoopConf, rootFile, metadata, protocol, rows) + val cachedRows = writeAMTParquet( + spark, hadoopConf, rootFile, metadata, protocol, rows, + cacheRows = AMTUtils.shouldCacheRootRows(spark, rows.size.toLong)) val status = fs.getFileStatus(rootFile) - ContentRoot( - path = AMTUtils.relativizeLocation(tableRoot.toString, rootFile.toString), - sizeInBytes = status.getLen, - version = version) + WrittenRoot( + contentRoot = ContentRoot( + path = AMTUtils.relativizeLocation(tableRoot.toString, rootFile.toString), + sizeInBytes = status.getLen, + version = version), + cachedRows = cachedRows) } // Returns a copy of a carried-forward leaf's ManifestInfo with `mdv` recorded as its Manifest @@ -653,18 +663,38 @@ object AMTWriteHelper extends DeltaLogging { finalPath: Path, metadata: Metadata, protocol: Protocol, - rows: Seq[AMTSingleAction]): Unit = { + rows: Seq[AMTSingleAction], + cacheRows: Boolean = false): Option[(StructType, Seq[InternalRow])] = { import org.apache.spark.sql.delta.implicits._ val withPartition = AMTPartitionValues.forWrite( spark.createDataset(rows).toDF(), metadata.partitionSchema) val df = AMTContentStats.forWrite(withPartition, metadata, protocol) + val persistedSchema = AMTSingleAction.persistedSchema(metadata, protocol) + val (dfToWrite, cachedRows) = if (cacheRows) { + val converted = AMTUtils.convertToLocalRelationFully(df.queryExecution.analyzed) + deltaAssert( + converted.isInstanceOf[LocalRelation], + name = "amtRootRowsMustFoldToLocalRelation", + msg = s"AMT root rows did not fold to a LocalRelation:\n${converted.treeString}") + converted match { + case local: LocalRelation => + val toUnsafe = UnsafeProjection.create(local.schema) + val copiedRows = local.data.map(row => toUnsafe(row).copy()) + val copiedLocal = LocalRelation(local.output, copiedRows) + (DataFrameUtils.ofRows(spark, copiedLocal), Some(persistedSchema -> copiedRows)) + case _ => (df, None) + } + } else { + (df, None) + } Checkpoints.writeAtomicCheckpointParquetFile( spark = spark, - df = df, + df = dfToWrite, finalPath = finalPath, hadoopConf = hadoopConf, useRename = false, - outputSchema = Some(AMTSingleAction.persistedSchema(metadata, protocol)), + outputSchema = Some(persistedSchema), format = new AMTParquetFileFormat) + cachedRows } } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala index 35f7b7269c0..414b59f488f 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTWriterManager.scala @@ -269,7 +269,7 @@ case class IncrementalAMTWriteMetrics( * * @param contentRootVersion the table version the manifest tree describes * @param checkpoint the inline [[Checkpoint]] action to embed in the commit JSON - * @param leaves the root's `DATA_MANIFEST` pointer entries, one per leaf + * @param rootInfo the root's leaf pointers and cached rows, when retained * @param includeActionsInCommitJson whether the transaction should still write the commit's file * actions inline in the commit JSON. * @param amtWriteMetrics metrics for the materialization that produced this result @@ -277,9 +277,11 @@ case class IncrementalAMTWriteMetrics( case class AMTWriteResult( contentRootVersion: Long, checkpoint: Checkpoint, - leaves: Seq[DataManifestEntry], + rootInfo: AMTRootInfo, includeActionsInCommitJson: Boolean, - amtWriteMetrics: SingleAMTWriteMetrics) + amtWriteMetrics: SingleAMTWriteMetrics) { + def leaves: Seq[DataManifestEntry] = rootInfo.leaves +} /** A lazily-materialized [[AMTCheckpointProvider]] for `checkpointOpt`. */ class LazyAMTCheckpointProvider( diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala index 22eff55278f..d6e6704602e 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/IncrementalAMTWriter.scala @@ -211,7 +211,7 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) extends Delt allLeafPointers.map(_.wrap) ++ rootLiveEntries.map(_.wrap) ++ rootRemoveEntries.map(_.wrap) - val contentRootBase = AMTWriteHelper.writeRoot( + val writtenRoot = AMTWriteHelper.writeRoot( spark, fs, hadoopConf, tableRoot, metadataDir, processedActions.postCommitMetadata, processedActions.postCommitProtocol, rootRows, version = contentTreeVersion) @@ -221,8 +221,8 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) extends Delt val lastFullRewriteVersion = oldAMT.lastManifestCommitWithFullRewrite.getOrElse(contentTreeVersion) val contentRoot = ContentRoot( - path = contentRootBase.path, - sizeInBytes = contentRootBase.sizeInBytes, + path = writtenRoot.contentRoot.path, + sizeInBytes = writtenRoot.contentRoot.sizeInBytes, version = contentTreeVersion, isIncremental = true, lastManifestCommitWithFullRewrite = lastFullRewriteVersion, @@ -284,7 +284,7 @@ class IncrementalAMTWriter(spark: SparkSession, deltaLog: DeltaLog) extends Delt AMTWriteResult( contentRootVersion = contentTreeVersion, checkpoint = checkpoint, - leaves = allLeafPointers, + rootInfo = new AMTRootInfo(allLeafPointers, writtenRoot.cachedRows), includeActionsInCommitJson = true, amtWriteMetrics = metric) } 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 fac53ac2301..87fd5abdd9d 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 @@ -682,13 +682,13 @@ trait DeltaSQLConfBase extends DeltaSQLConfUtils { val AMT_ROOT_CACHE_MAX_NUM_ENTRIES = buildConf("amt.rootCache.maxNumEntries") .internal() - .doc("Cache the persisted AMT root rows only when the entry count from the Parquet " + - "footer, including DATA and DATA_MANIFEST entries, is less than this threshold. " + - "Otherwise collect only leaf pointers during discovery and read the root again for " + - "reconstruction. Set to 0 to disable root row caching and skip the footer count check.") + .doc("Cache persisted AMT root rows only when columnar state reconstruction is enabled " + + "and the root has fewer entries than this threshold. Discovery reads the entry count " + + "from the Parquet footer. Writers use the number of rows written. Set to 0 to disable " + + "root row caching and skip the footer count check.") .intConf .checkValue(_ >= 0, "amt.rootCache.maxNumEntries must be non-negative.") - .createWithDefault(12000) + .createWithDefault(50000) val AMT_LARGE_COMMIT_ACTIONS_COUNT_THRESHOLD_FOR_INLINE_MANIFEST_COMMIT = buildConf("amt.largeCommitActionsCountThresholdForInlineManifestCommit") diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/LastCheckpointInfoSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/LastCheckpointInfoSuite.scala index 7db3e45eeb5..1c385ba1129 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/LastCheckpointInfoSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/LastCheckpointInfoSuite.scala @@ -18,7 +18,7 @@ package org.apache.spark.sql.delta // scalastyle:off import.ordering.noEmptyLine import org.apache.spark.sql.delta.actions.{Checkpoint, ContentRoot, DomainMetadata, Metadata, Protocol, SetTransaction, SidecarFile, SidecarType} -import org.apache.spark.sql.delta.amt.{AMTLeafComparisons, AMTSingleAction, AMTWriteResult, DataManifestEntry, ManifestInfo, SingleAMTWriteMetrics, Tracking} +import org.apache.spark.sql.delta.amt.{AMTLeafComparisons, AMTRootInfo, AMTSingleAction, AMTWriteResult, DataManifestEntry, ManifestInfo, SingleAMTWriteMetrics, Tracking} import org.apache.spark.sql.delta.sources.DeltaSQLConf import org.apache.spark.sql.delta.test.DeltaSQLCommandTest import org.apache.spark.sql.delta.test.DeltaTestImplicits._ @@ -321,7 +321,7 @@ class LastCheckpointInfoSuite extends SharedSparkSession AMTWriteResult( contentRootVersion = contentRootVersion, checkpoint = sampleCheckpointAction(contentRootVersion), - leaves = leaves, + rootInfo = new AMTRootInfo(leaves, cachedRows = None), includeActionsInCommitJson = true, amtWriteMetrics = sampleAMTWriteMetrics) @@ -408,7 +408,9 @@ class LastCheckpointInfoSuite extends SharedSparkSession val newer = AMTWriteResult( contentRootVersion = 5, checkpoint = sampleCheckpointAction(version = 5, rootPath = "metadata/root-def.parquet"), - leaves = Seq(sampleLeaf("metadata/leaf-9.parquet")), + rootInfo = new AMTRootInfo( + leaves = Seq(sampleLeaf("metadata/leaf-9.parquet")), + cachedRows = None), includeActionsInCommitJson = true, amtWriteMetrics = sampleAMTWriteMetrics) log.writeLastCheckpointFileForAMT(manifestCommitVersion = 6, newer) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala index 9b9ad0f7916..9b35009bbb7 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotDiscoverySuite.scala @@ -190,6 +190,7 @@ class AMTSnapshotDiscoverySuite synchronous = AMTCheckpointProvider.fromCheckpoint( spark, deltaLog, checkpoint, context.provider.manifestCommitVersion) }) + assert(discoveryJobs == 1, "Leaf pointer decoding must not launch another Spark job") assert(prefetched.isInstanceOf[ColumnarAMTCheckpointProvider]) assert(synchronous.isInstanceOf[ColumnarAMTCheckpointProvider]) @@ -267,6 +268,7 @@ class AMTSnapshotDiscoverySuite synchronous = AMTCheckpointProvider.fromCheckpoint( spark, deltaLog, checkpoint, context.manifestCommitVersion) }) + assert(jobs == 1, "The footer count check must not launch another Spark job") } val scanQueries = queries.filter(_.analyzed.exists(_.isInstanceOf[LogicalRelation])) assert(scanQueries.size == (if (shouldCache) 0 else 1)) @@ -291,6 +293,92 @@ class AMTSnapshotDiscoverySuite } } + /////////////////////////// + // Warm snapshot providers + /////////////////////////// + + for ((layout, deferredScenarios) <- Seq( + "root-only" -> Seq(AMTCheckpointScenario.DeferredIncremental), + "leaf-backed" -> Seq( + AMTCheckpointScenario.DeferredIncremental, + AMTCheckpointScenario.DeferredFull))) { + testAcrossAMTCheckpointScenarios( + s"[warm commit] columnar provider reuses writer-produced root rows: $layout", + s"amt_written_root_cache_${layout.replace('-', '_')}", + deferredScenarios = deferredScenarios, + sqlConfs = Seq( + DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED.key -> "true", + DeltaSQLConf.AMT_ROOT_CACHE_MAX_NUM_ENTRIES.key -> "50000") ++ + (if (layout == "leaf-backed") leafPackingConfs else Seq( + DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "100")), + tableSchema = "id INT, part INT", + partitionColumns = Seq("part"))( + setup = name => appendRowsAsSeparateFiles( + name, + if (layout == "leaf-backed") leafPackedFiles + 1 else 2, + columnExprs = Seq("CAST(id AS INT)", "CAST(id % 3 AS INT)")), + inlineCheckpointTriggerActionsOrSQL = Some(name => Right( + s"INSERT INTO $name VALUES (100, 1)"))) { context => + val deltaLog = context.postCheckpointSnapshot.deltaLog + assert(context.provider.isInstanceOf[ColumnarAMTCheckpointProvider]) + assert(context.provider.leaves.nonEmpty == (layout == "leaf-backed")) + + val rootPath = context.checkpoint.contentRoot.getAbsolutePath(deltaLog.dataPath) + val uncached = AMTCheckpointProvider( + spark, + context.manifestCommitVersion, + context.checkpoint, + context.provider.leaves, + deltaLog.dataPath) + val expectedRootFiles = uncached.readLiveRootDataEntries(spark, deltaLog) + val expectedActions = + uncached.loadActionsForStateReconstruction(spark, deltaLog).get.collect() + if (layout == "root-only") assert(expectedRootFiles.nonEmpty) + + val savedRoot = new Path(rootPath.toString + ".saved") + val fs = rootPath.getFileSystem(deltaLog.newDeltaHadoopConf()) + assert(fs.rename(rootPath, savedRoot)) + try { + assert(context.provider.readLiveRootDataEntries(spark, deltaLog) == expectedRootFiles) + val actions = context.provider.loadActionsForStateReconstruction(spark, deltaLog).get + assert(!actions.inputFiles.map(new Path(_)).contains(rootPath)) + checkAnswer(actions, expectedActions.toSeq) + + // The next checkpoint starts from this in-memory snapshot and needs its root DATA entries. + commitCheckpoint(deltaLog, incremental = true) + assert(deltaLog.update().version == context.manifestCommitVersion + 1) + } finally { + assert(fs.rename(savedRoot, rootPath)) + } + } + } + + for ((suffix, maxNumEntries) <- Seq( + ("cache_disabled", 0), + ("above_limit", 1))) { + testAcrossAMTCheckpointScenarios( + s"[warm commit] writer does not retain root rows when $suffix", + s"amt_written_root_$suffix", + sqlConfs = Seq( + DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED.key -> "true", + DeltaSQLConf.AMT_ROOT_CACHE_MAX_NUM_ENTRIES.key -> maxNumEntries.toString, + DeltaSQLConf.AMT_ENTRIES_PER_LEAF.key -> "100"))( + setup = name => appendRowsAsSeparateFiles(name, 2)) { context => + val deltaLog = context.postCheckpointSnapshot.deltaLog + val rootPath = context.checkpoint.contentRoot.getAbsolutePath(deltaLog.dataPath) + val actions = context.provider.loadActionsForStateReconstruction(spark, deltaLog).get + assert(actions.inputFiles.map(new Path(_)).contains(rootPath)) + } + } + + test("[root cache] skips the entry count when columnar reconstruction is disabled") { + withSQLConf( + DeltaSQLConf.AMT_COLUMNAR_STATE_RECONSTRUCTION_ENABLED.key -> "false", + DeltaSQLConf.AMT_ROOT_CACHE_MAX_NUM_ENTRIES.key -> "50000") { + assert(!AMTUtils.shouldCacheRootRows(spark, fail("the entry count must not be evaluated"))) + } + } + /** Asserts that the cold snapshot is installed with the expected state. */ private def assertColdSnapshotStates( tableName: String, From 965a3c05d654f47b82004a23522ceab5bd39ca5a Mon Sep 17 00:00:00 2001 From: Zihao Xu Date: Tue, 17 Nov 2026 20:43:40 -0800 Subject: [PATCH 34/44] [Spark] Use CatalogManagedTableFeature (#8154) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Stacked on #8153; review the last commit. Moves callers of `CatalogOwnedTableFeature` to the new name `CatalogManagedTableFeature`. Each change is the name only. ## How was this patch tested? Rename only, no new tests. Apart from the aliases and the line wrapping, every changed token is an old name changed to the new one. ## Does this PR introduce _any_ user-facing changes? No. --- .../spark/sql/delta/ConflictChecker.scala | 2 +- .../spark/sql/delta/DeltaAnalysis.scala | 10 ++--- .../sql/delta/commands/CloneTableBase.scala | 8 ++-- .../commands/CreateDeltaTableCommand.scala | 10 ++--- .../CoordinatedCommitsUtils.scala | 30 ++++++------- .../sql/delta/util/TransactionHelper.scala | 4 +- .../DeltaGenerateSymlinkManifestSuite.scala | 2 +- .../spark/sql/delta/DeltaLogSuite.scala | 4 +- .../sql/delta/DeltaProtocolVersionSuite.scala | 6 +-- .../apache/spark/sql/delta/DeltaSuite.scala | 2 +- .../sql/delta/DeltaTableFeatureSuite.scala | 2 +- .../FeatureEnablementConcurrencySuite.scala | 6 +-- .../delta/OptimisticTransactionSuite.scala | 6 +-- .../OptimisticTransactionSuiteBase.scala | 3 +- .../sql/delta/amt/AMTContentStatsSuite.scala | 4 +- .../AdaptiveMetadataTableFeatureSuite.scala | 6 +-- .../CatalogOwnedEnablementSuite.scala | 32 +++++++------- .../CatalogOwnedPropertySuite.scala | 42 +++++++++---------- .../CoordinatedCommitsTestUtils.scala | 6 +-- .../RowTrackingConflictResolutionSuite.scala | 2 +- .../clustering/ClusteredTableDDLSuite.scala | 2 +- .../sql/delta/test/DeltaSQLTestUtils.scala | 6 +-- .../sql/delta/test/DeltaTestImplicits.scala | 8 ++-- 23 files changed, 102 insertions(+), 101 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 ce9d9f82079..87ff90f4350 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 @@ -913,7 +913,7 @@ private[delta] class ConflictChecker( case DeltaConfigs.IN_COMMIT_TIMESTAMP_ENABLEMENT_TIMESTAMP.key => isNew // Catalog-managed enablement configuration case UCCommitCoordinatorClient.UC_TABLE_ID_KEY - if currentTransactionInfo.protocol.isFeatureSupported(CatalogOwnedTableFeature) => + if currentTransactionInfo.protocol.isFeatureSupported(CatalogManagedTableFeature) => isNew case _ => true } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala index 9db1cb9f9b3..b42f41bbe26 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaAnalysis.scala @@ -225,13 +225,13 @@ class DeltaAnalysis(protected val session: SparkSession) // Check whether we are trying to enable Catalog-Managed via explicit property overrides. // The reason to check this is, if the source table is a Catalog-Managed table, and // we are also trying to enable Catalog-Managed for the target table - We do *NOT* - // want to filter out [[CatalogOwnedTableFeature]] from the source table. If we do that, + // want to filter out [[CatalogManagedTableFeature]] from the source table. If we do that, // the resulting target table's protocol will *NOT* have CatalogManaged table feature // present though we have explicitly specified it in the TBLPROPERTIES clause. // This only applies to cases where source table has Catalog-Managed enabled. // It works as intended if source table is a normal delta table. if (TableFeatureProtocolUtils.getSupportedFeaturesFromTableConfigs( - configs = ctl.properties).contains(CatalogOwnedTableFeature)) { + configs = ctl.properties).contains(CatalogManagedTableFeature)) { isEnablingCatalogOwnedViaExplicitPropertyOverrides = true } @@ -280,11 +280,11 @@ class DeltaAnalysis(protected val session: SparkSession) } else { None } - // Catalog-Managed: Do not copy over [[CatalogOwnedTableFeature]] from source table + // Catalog-Managed: Do not copy over [[CatalogManagedTableFeature]] from source table // except the certain case. val protocolAfterFilteringCatalogOwnedFromSource = protocol match { case Some(p) if !isEnablingCatalogOwnedViaExplicitPropertyOverrides => - // Only filter out [[CatalogOwnedTableFeature]] when target table is not enabling + // Only filter out [[CatalogManagedTableFeature]] when target table is not enabling // CatalogManaged. // E.g., // - CREATE TABLE t1 LIKE t2 @@ -295,7 +295,7 @@ class DeltaAnalysis(protected val session: SparkSession) // ) // - Do not filter CatalogManaged table feature out if target table is enabling // CatalogManaged. - Some(p.removeFeature(targetFeature = CatalogOwnedTableFeature)) + Some(p.removeFeature(targetFeature = CatalogManagedTableFeature)) case _ => protocol } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala index 9a7d7875060..f590289a0ba 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CloneTableBase.scala @@ -454,9 +454,9 @@ abstract class CloneTableBase( spark: SparkSession, txn: OptimisticTransaction, opName: String): Protocol = { - // Catalog-Managed: Do not copy over [[CatalogOwnedTableFeature]] from source table. + // Catalog-Managed: Do not copy over [[CatalogManagedTableFeature]] from source table. val sourceProtocol = - sourceTable.protocol.removeFeature(targetFeature = CatalogOwnedTableFeature) + sourceTable.protocol.removeFeature(targetFeature = CatalogManagedTableFeature) // Pre-transaction version of the target table. val targetProtocol = txn.snapshot.protocol // Overriding properties during the CLONE can change the minimum required protocol for target. @@ -469,12 +469,12 @@ abstract class CloneTableBase( val catalogOwnedEnabledByDefaultConf = if (CatalogOwnedTableUtils.defaultCatalogOwnedEnabled(spark) && !tableExists(txn.snapshot)) { - // Append [[CatalogOwnedTableFeature]] to the `configWithOverrides` below if table + // Append [[CatalogManagedTableFeature]] to the `configWithOverrides` below if table // does not exist, to ensure the final target protocol contains CatalogManaged // if enabled by default. // Note: We need this because CatalogManaged is enabled through single protocol // without auxiliary metadata. - Map(s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported") + Map(s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported") } else { Map.empty } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala index ddd8d1b67ae..bc6e2f14ee3 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/CreateDeltaTableCommand.scala @@ -131,7 +131,7 @@ case class CreateDeltaTableCommand( val tableFeatures = TableFeatureProtocolUtils. getSupportedFeaturesFromTableConfigs(table.properties) if (!Utils.isTesting && !allowCatalogManaged && - (tableFeatures.contains(CatalogOwnedTableFeature) || + (tableFeatures.contains(CatalogManagedTableFeature) || CatalogOwnedTableUtils.defaultCatalogOwnedEnabled(spark = sparkSession))) { throw DeltaErrors.deltaCannotCreateCatalogManagedTable() } @@ -455,14 +455,14 @@ case class CreateDeltaTableCommand( // For commands like CREATE LIKE, the `protocol` here may contain table features // from source table. It will override the `newProtocol` being created in the above // `txn.updateMetadataForNewTable`. - // In order to enable [[CatalogOwnedTableFeature]] for target table w/ default + // In order to enable [[CatalogManagedTableFeature]] for target table w/ default // spark configuration of CatalogManaged enabled, we need to manually append - // [[CatalogOwnedTableFeature]] here to the existing source table protocol. + // [[CatalogManagedTableFeature]] here to the existing source table protocol. val finalizedProtocol = if (CatalogOwnedTableUtils.defaultCatalogOwnedEnabled( spark = sparkSession)) { val minCatalogOwnedProtocol = Protocol( - CatalogOwnedTableFeature.minReaderVersion, - CatalogOwnedTableFeature.minWriterVersion).withFeature(CatalogOwnedTableFeature) + CatalogManagedTableFeature.minReaderVersion, + CatalogManagedTableFeature.minWriterVersion).withFeature(CatalogManagedTableFeature) protocol.merge(minCatalogOwnedProtocol) } else { protocol diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala index 08b9e862a5c..712bf19451e 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsUtils.scala @@ -22,7 +22,7 @@ import java.util.Optional import scala.collection.JavaConverters._ import scala.util.control.NonFatal -import org.apache.spark.sql.delta.{AdaptiveMetadataTableFeature, CatalogOwnedTableFeature, CheckpointPolicy, CoordinatedCommitsTableFeature, DeletionVectorsTableFeature, DeltaConfig, DeltaConfigs, DeltaErrors, DeltaIllegalArgumentException, DeltaLog, NameMapping, OptimisticTransaction, RowTrackingFeature, Snapshot, SnapshotDescriptor, TableFeature, V2CheckpointTableFeature} +import org.apache.spark.sql.delta.{AdaptiveMetadataTableFeature, CatalogManagedTableFeature, CheckpointPolicy, CoordinatedCommitsTableFeature, DeletionVectorsTableFeature, DeltaConfig, DeltaConfigs, DeltaErrors, DeltaIllegalArgumentException, DeltaLog, NameMapping, OptimisticTransaction, RowTrackingFeature, Snapshot, SnapshotDescriptor, TableFeature, V2CheckpointTableFeature} import org.apache.spark.sql.delta.actions.{Metadata, Protocol, TableFeatureProtocolUtils} import org.apache.spark.sql.delta.amt.AMTUtils import org.apache.spark.sql.delta.commands.CloneTableCommand @@ -51,24 +51,24 @@ object CatalogManagedTableUtils extends DeltaLogging { val DEFAULT_CATALOG_NAME_FOR_TESTING: String = "spark_catalog" /** - * Sets or removes CatalogOwnedTableFeature from a transaction's protocol. + * Sets or removes CatalogManagedTableFeature from a transaction's protocol. * * This helper method is used to control whether a transaction should use CC. * * @param txn The OptimisticTransaction to modify protocol and metadata on - * @param withCatalogOwnedTableFeature If true, adds CatalogOwnedTableFeature to the protocol + * @param withCatalogOwnedTableFeature If true, adds CatalogManagedTableFeature to the protocol * and ensures ICT enablement. If false, removes it. * - * @note When adding CatalogOwnedTableFeature, this method also forces a metadata update + * @note When adding CatalogManagedTableFeature, this method also forces a metadata update * to ensure ICT (In-Commit Timestamp) is properly enabled. See the below comment * for details. */ def setTxnProtocol(txn: OptimisticTransaction, withCatalogOwnedTableFeature: Boolean): Unit = { if (withCatalogOwnedTableFeature) { - val p = txn.protocol.withFeature(feature = CatalogOwnedTableFeature) + val p = txn.protocol.withFeature(feature = CatalogManagedTableFeature) txn.updateProtocol(protocol = p) // Force a metadata update to trigger ICT (In-Commit Timestamp) enablement. - // CatalogOwnedTableFeature requires ICT to be enabled in the metadata, but + // CatalogManagedTableFeature requires ICT to be enabled in the metadata, but // updateMetadataAndProtocolWithRequiredFeatures in prepareInitialActions only runs // when there's an explicit metadata change (metadataChanges.headOption is non-empty). // Since we're only updating the protocol here without changing metadata content, @@ -78,7 +78,7 @@ object CatalogManagedTableUtils extends DeltaLogging { // causing UCCommitCoordinatorClient to fail with DELTA_MISSING_COMMIT_TIMESTAMP. txn.updateMetadata(proposedNewMetadata = txn.metadata) } else { - val p = txn.protocol.removeFeature(targetFeature = CatalogOwnedTableFeature) + val p = txn.protocol.removeFeature(targetFeature = CatalogManagedTableFeature) txn.updateProtocol(protocol = p) } } @@ -208,7 +208,7 @@ object CatalogManagedTableUtils extends DeltaLogging { isCreatingNew: Boolean = true): Boolean = { // Check explicit property overrides when creating a new or upgrading an existing table. val isExplicitlyEnablingCO = TableFeatureProtocolUtils.getSupportedFeaturesFromTableConfigs( - configs = propertyOverrides).contains(CatalogOwnedTableFeature) + configs = propertyOverrides).contains(CatalogManagedTableFeature) // Check default spark session configuration only when creating a new table. val isEnablingCOByDefault = @@ -278,12 +278,12 @@ object CatalogManagedTableUtils extends DeltaLogging { private[delta] def verifyCatalogManagedStatusIsSupported( propertyOverrides: Map[String, String]): Unit = { val catalogManagedKey = - TableFeatureProtocolUtils.propertyKey(CatalogOwnedTableFeature).toLowerCase(Locale.ROOT) + TableFeatureProtocolUtils.propertyKey(CatalogManagedTableFeature).toLowerCase(Locale.ROOT) propertyOverrides.foreach { case (key, status) => if (key.toLowerCase(Locale.ROOT) == catalogManagedKey && status.toLowerCase(Locale.ROOT) != TableFeatureProtocolUtils.FEATURE_PROP_SUPPORTED) { throw DeltaErrors.unsupportedTableFeatureStatusException( - feature = CatalogOwnedTableFeature.name, status = status) + feature = CatalogManagedTableFeature.name, status = status) } } } @@ -292,7 +292,7 @@ object CatalogManagedTableUtils extends DeltaLogging { * Validates the Catalog-Managed configurations in explicit command overrides for * `AlterTableSetPropertiesDeltaCommand`. * - * If [[CatalogOwnedTableFeature]] presents, we do NOT allow users to + * If [[CatalogManagedTableFeature]] presents, we do NOT allow users to * modify any ICT properties that Catalog-Managed depends on. */ def validatePropertiesForAlterTableSetPropertiesDeltaCommand( @@ -309,7 +309,7 @@ object CatalogManagedTableUtils extends DeltaLogging { /** * Validates the configurations to unset for `AlterTableUnsetPropertiesDeltaCommand`. * - * If the table already has [[CatalogOwnedTableFeature]] present, + * If the table already has [[CatalogManagedTableFeature]] present, * we do not allow users to unset any of the ICT properties that Catalog-Managed depends on. */ def validatePropertiesForAlterTableUnsetPropertiesDeltaCommand( @@ -355,7 +355,7 @@ object CatalogManagedTableUtils extends DeltaLogging { verifyCatalogManagedStatusIsSupported( DeltaConfigs.mergeGlobalConfigs(spark.sessionState.conf, propertyOverrides)) // We do not allow users to modify [[UCCommitCoordinatorClient.UC_TABLE_ID_KEY]] and - // [[CatalogOwnedTableFeature.name]] in any explicit overrides for REPLACE command. + // [[CatalogManagedTableFeature.name]] in any explicit overrides for REPLACE command. if (tableExists) { // Must be "REPLACE" or "REPLACE with CLONE" if the table already exists. assert(command == "REPLACE with CLONE" || command == "REPLACE", @@ -364,7 +364,7 @@ object CatalogManagedTableUtils extends DeltaLogging { val isSpecifyingCatalogManaged = TableFeatureProtocolUtils .getSupportedFeaturesFromTableConfigs(propertyOverrides) - .contains(CatalogOwnedTableFeature) + .contains(CatalogManagedTableFeature) val existingTableIsCatalogManaged = existingTableSnapshotOpt.exists(_.isCatalogOwned) // Allow specifying CatalogManaged in REPLACE TABLE if the existing table is already @@ -406,7 +406,7 @@ object CatalogManagedTableUtils extends DeltaLogging { */ def defaultCatalogOwnedEnabled(spark: SparkSession): Boolean = { spark.conf - .getOption(TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature)) + .getOption(TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature)) .contains("supported") } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala b/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala index 8c605947647..0b7bcaca045 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/util/TransactionHelper.scala @@ -21,7 +21,7 @@ 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.{CatalogOwnedTableFeature, CommitStats, CommittedTransaction, CoordinatedCommitsStats, CoordinatedCommitType, DeltaConfigs, DeltaLog, FileActionOperationClass, IsolationLevel, Serializable, Snapshot, WriteSerializable} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, CommitStats, CommittedTransaction, CoordinatedCommitsStats, CoordinatedCommitType, DeltaConfigs, DeltaLog, FileActionOperationClass, IsolationLevel, Serializable, Snapshot, WriteSerializable} import org.apache.spark.sql.delta.DeltaOperations.Operation import org.apache.spark.sql.delta.RowId.RowTrackingMetadataDomain import org.apache.spark.sql.delta.actions.{Action, AddCDCFile, AddFile, CommitInfo, DomainMetadata, FileAction, Metadata, Protocol, RemoveFile, SetTransaction} @@ -191,7 +191,7 @@ trait TransactionHelper extends DeltaLogging { // Only the 0th commit to a table can be a FS -> CO upgrade for now. // Upgrading an existing FS table to CO through ALTER TABLE is not supported yet. case None if newProtocol.exists(_.readerAndWriterFeatureNames - .contains(CatalogOwnedTableFeature.name)) => // FS -> CO + .contains(CatalogManagedTableFeature.name)) => // FS -> CO (CoordinatedCommitType.FS_TO_CO_UPGRADE_COMMIT, metadata) case None if metadata.coordinatedCommitsCoordinatorName.isDefined => // FS -> CC (CoordinatedCommitType.FS_TO_CC_UPGRADE_COMMIT, metadata) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaGenerateSymlinkManifestSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaGenerateSymlinkManifestSuite.scala index aad9e72cf28..ec12afb10cc 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaGenerateSymlinkManifestSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaGenerateSymlinkManifestSuite.scala @@ -82,7 +82,7 @@ trait DeltaGenerateSymlinkManifestSuiteBase test("symlink manifest generation is blocked for a catalog-managed table") { withCatalogManagedTable(createTable = false) { tableName => spark.sql(s"CREATE TABLE $tableName (id INT) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported', " + + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported', " + "'delta.enableDeletionVectors' = 'false')") assertManifest(tableName, expectSameFiles = false, expectedNumFiles = 0) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala index 77dbb0f09ec..e8be8a80b6d 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaLogSuite.scala @@ -252,7 +252,7 @@ class DeltaLogSuite extends QueryTest FileNames.unsafeDeltaFile(log.logPath, 0L), Iterator(Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), Metadata(), add) .map(a => JsonUtils.toJson(a.wrap)), overwrite = false, @@ -284,7 +284,7 @@ class DeltaLogSuite extends QueryTest FileNames.unsafeDeltaFile(log.logPath, 0L), Iterator(Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), Metadata(), add) .map(a => JsonUtils.toJson(a.wrap)), overwrite = false, diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala index 31a47694639..40161f144bf 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaProtocolVersionSuite.scala @@ -160,10 +160,10 @@ trait DeltaProtocolVersionSuiteBase extends QueryTest assert(log.snapshot.protocol === Protocol(1, 1)) log.upgradeProtocol(Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)) + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)) assert(log.snapshot.protocol === Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)) + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)) } } @@ -3858,7 +3858,7 @@ trait DeltaProtocolVersionSuiteBase extends QueryTest testRemoveVacuumProtocolCheckTableFeature( enableFeatureInitially = true, additionalTableProperties = Seq( - (s"$FEATURE_PROP_PREFIX${CatalogOwnedTableFeature.name}", "supported")), + (s"$FEATURE_PROP_PREFIX${CatalogManagedTableFeature.name}", "supported")), downgradeFailsWithException = Some("DELTA_FEATURE_DROP_DEPENDENT_FEATURE"), featureExpectedAtTheEnd = true) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaSuite.scala index 9e4f5e7fd30..cbb3d78865c 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaSuite.scala @@ -2159,7 +2159,7 @@ class DeltaSuite extends QueryTest // changes the schema val actions = Seq(Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features), newMetadata) ++ files.map(_.remove) deltaLog.store.write( FileNames.unsafeDeltaFile(deltaLog.logPath, snapshot.version + 1), diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala index dac173193d7..e02640753c8 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/DeltaTableFeatureSuite.scala @@ -511,7 +511,7 @@ class DeltaTableFeatureSuite CatalogManagedCommitCoordinatorProvider.registerBuilder( "spark_catalog", InMemoryCommitCoordinatorBuilder(batchSize = 100)) spark.range(0).write.format("delta") - .option(propertyKey(CatalogOwnedTableFeature), "supported") + .option(propertyKey(CatalogManagedTableFeature), "supported") .saveAsTable(table) val log = DeltaLog.forTable(spark, TableIdentifier(table)) val featureName = TestRemovableReaderWriterFeature.name diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/FeatureEnablementConcurrencySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/FeatureEnablementConcurrencySuite.scala index 33f911fb95b..e8b1c59c0e2 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/FeatureEnablementConcurrencySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/FeatureEnablementConcurrencySuite.scala @@ -367,8 +367,8 @@ class FeatureEnablementConcurrencySuite // Tests 14-16: UC_TABLE_ID_KEY per-key validator. Mirroring the rebase path, // currentTransactionInfo.protocol reflects the winning commit's enabled - // CatalogOwnedTableFeature, so we construct a conflict checker with CO in protocol. - val coProtocol = Protocol.forTableFeature(CatalogOwnedTableFeature) + // CatalogManagedTableFeature, so we construct a conflict checker with CO in protocol. + val coProtocol = Protocol.forTableFeature(CatalogManagedTableFeature) val conflictCheckerWithCO = new ConflictChecker( spark, initialCurrentTransactionInfo = dummyTransactionInfo.copy(protocol = coProtocol), @@ -404,7 +404,7 @@ class FeatureEnablementConcurrencySuite } test("CatalogOwned and VacuumProtocolCheck features allow concurrent txns at upgrade") { - assert(!CatalogOwnedTableFeature.failConcurrentTransactionsAtUpgrade) + assert(!CatalogManagedTableFeature.failConcurrentTransactionsAtUpgrade) assert(!VacuumProtocolCheckTableFeature.failConcurrentTransactionsAtUpgrade) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala index fe738ffecd7..9b535da338a 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuite.scala @@ -251,11 +251,11 @@ class OptimisticTransactionSuite concurrentWrites = Seq( Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)), + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features)), actions = Seq( Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features))) + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features))) check( "taint whole table", @@ -1111,7 +1111,7 @@ class OptimisticTransactionSuite deltaLog.withNewTransaction { txn => val protocol = Action.supportedProtocolVersion( featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) val metadata = Metadata( schemaString = schema.json, partitionColumns = partitionColumns) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuiteBase.scala b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuiteBase.scala index dae873837ae..9682e0f2b7a 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuiteBase.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/OptimisticTransactionSuiteBase.scala @@ -50,7 +50,8 @@ trait OptimisticTransactionSuiteBase */ protected def testDefaultMetadata(): Metadata = Metadata() protected def testDefaultProtocol(): Protocol = Action.supportedProtocolVersion( - featuresToExclude = Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) + featuresToExclude = + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) /** * Check whether the test transaction conflict with the concurrent writes by executing the diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala index 717f418ebdb..2249398e2fb 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala @@ -16,7 +16,7 @@ package org.apache.spark.sql.delta.amt -import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, ColumnMappingTableFeature, DeletionVectorsTableFeature, DeltaColumnMapping, DeltaConfigs, DomainMetadataTableFeature, RowTrackingFeature} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, ColumnMappingTableFeature, DeletionVectorsTableFeature, DeltaColumnMapping, DeltaConfigs, DomainMetadataTableFeature, RowTrackingFeature} import org.apache.spark.sql.delta.actions.{AddFile, Metadata, Protocol} import org.apache.spark.sql.delta.util.JsonUtils import com.fasterxml.jackson.databind.JsonNode @@ -227,7 +227,7 @@ class AMTContentStatsSuite extends AMTCheckpointTestBase { */ private def amtProtocol: Protocol = Protocol(3, 7) - .withFeature(CatalogOwnedTableFeature) + .withFeature(CatalogManagedTableFeature) .withFeature(RowTrackingFeature) .withFeature(DomainMetadataTableFeature) .withFeature(DeletionVectorsTableFeature) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala index f9bf21a5d81..76e93f8f919 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AdaptiveMetadataTableFeatureSuite.scala @@ -21,7 +21,7 @@ import java.util.Locale import org.apache.spark.sql.delta.{ AdaptiveMetadataPreviewTableFeature, AdaptiveMetadataTableFeature, - CatalogOwnedTableFeature, + CatalogManagedTableFeature, ColumnMappingTableFeature, DeletionVectorsTableFeature, DeltaAnalysisException, @@ -91,7 +91,7 @@ class AdaptiveMetadataTableFeatureSuite test("feature requires catalogManaged, rowTracking, domainMetadata, DVs and column mapping") { assert(AdaptiveMetadataPreviewTableFeature.requiredFeatures === Set( - CatalogOwnedTableFeature, + CatalogManagedTableFeature, RowTrackingFeature, DomainMetadataTableFeature, DeletionVectorsTableFeature, @@ -224,7 +224,7 @@ class AdaptiveMetadataTableFeatureSuite */ private def createNonAMTTableForReplace(tableName: String, checkpointPolicy: String): Unit = { sql(s"CREATE TABLE $tableName (id INT) USING $tableProvider " + - s"TBLPROPERTIES ('${propertyKey(CatalogOwnedTableFeature)}' = '$FEATURE_PROP_SUPPORTED', " + + s"TBLPROPERTIES ('${propertyKey(CatalogManagedTableFeature)}' = '$FEATURE_PROP_SUPPORTED', " + s"'${DeltaConfigs.COLUMN_MAPPING_MODE.key}' = 'id', " + s"'${DeltaConfigs.CHECKPOINT_POLICY.key}' = '$checkpointPolicy')") } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala index 5a7e3efd992..ca9130727c3 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedEnablementSuite.scala @@ -50,7 +50,7 @@ class CatalogOwnedEnablementSuite /** * Validate that the table has the expected enablement of Catalog-Managed table feature. - * Specifically, [[CatalogOwnedTableFeature]] and its dependent features should be present + * Specifically, [[CatalogManagedTableFeature]] and its dependent features should be present * in the table protocol. * * @param tableName The name of the table to validate. @@ -62,14 +62,14 @@ class CatalogOwnedEnablementSuite val (_, snapshot) = getDeltaLogWithSnapshot(TableIdentifier(tableName)) assert(snapshot.isCatalogOwned == expectEnabled) Seq( - CatalogOwnedTableFeature, + CatalogManagedTableFeature, VacuumProtocolCheckTableFeature, InCommitTimestampTableFeature ).foreach { feature => assert(snapshot.protocol.writerFeatures.exists(_.contains(feature.name)) == expectEnabled) } Seq( - CatalogOwnedTableFeature, + CatalogManagedTableFeature, VacuumProtocolCheckTableFeature ).foreach { feature => assert(snapshot.protocol.readerFeatures.exists(_.contains(feature.name)) == expectEnabled) @@ -107,7 +107,7 @@ class CatalogOwnedEnablementSuite createCatalogOwnedTableAtInit: Boolean): Unit = { if (createCatalogOwnedTableAtInit) { createTable(tableName, properties = Map( - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported")) + s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported")) } else { createTable(tableName) } @@ -250,7 +250,7 @@ class CatalogOwnedEnablementSuite "delta.feature.appendOnly" -> "supported", "delta.feature.invariants" -> "supported", // To avoid potential naming change in the future. - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported", + s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported", "delta.feature.inCommitTimestamp" -> "supported", "delta.feature.vacuumProtocolCheck" -> "supported", "delta.enableInCommitTimestamps" -> "true" @@ -270,7 +270,7 @@ class CatalogOwnedEnablementSuite sql(s"CREATE TABLE t1 SHALLOW CLONE $tableName") } sql(s"CREATE TABLE t2 SHALLOW CLONE $tableName TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") Seq("t1", "t2").foreach { t => validateOnlySpecifiedQoLTableFeaturesAndMetadataPresent( tableName = t, @@ -298,7 +298,7 @@ class CatalogOwnedEnablementSuite withTable("t1") { // Enable [[ClusteringTableFeature]] and [[ChangeDataFeedTableFeature]] during CO creation. createTable("t1", clusterBy = Seq("id"), properties = Map( - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported", + s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported", DeltaConfigs.CHANGE_DATA_FEED.key -> "true")) sql("INSERT INTO t1 VALUES (1), (2)") validateQoLFeaturesEnablement(tableName = "t1", expected = true) @@ -342,13 +342,13 @@ class CatalogOwnedEnablementSuite withTable(tableName) { val error = interceptWithUnwrapping[DeltaTableFeatureException] { createTable(tableName, properties = Map( - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "enabled")) + s"delta.feature.${CatalogManagedTableFeature.name}" -> "enabled")) } checkError( error, "DELTA_UNSUPPORTED_FEATURE_STATUS", parameters = Map( - "feature" -> CatalogOwnedTableFeature.name, + "feature" -> CatalogManagedTableFeature.name, "status" -> "enabled")) } } @@ -356,13 +356,13 @@ class CatalogOwnedEnablementSuite test("ALTER TABLE should be blocked if attempts to downgrade Catalog-Owned") { withRandomTable(createCatalogOwnedTableAtInit = true) { tableName => val error = intercept[DeltaTableFeatureException] { - spark.sql(s"ALTER TABLE $tableName DROP FEATURE '${CatalogOwnedTableFeature.name}'") + spark.sql(s"ALTER TABLE $tableName DROP FEATURE '${CatalogManagedTableFeature.name}'") } checkError( error, "DELTA_FEATURE_DROP_UNSUPPORTED_CLIENT_FEATURE", sqlState = "0AKDC", - parameters = Map("feature" -> CatalogOwnedTableFeature.name)) + parameters = Map("feature" -> CatalogManagedTableFeature.name)) } } @@ -373,7 +373,7 @@ class CatalogOwnedEnablementSuite ) { tableName => val error = intercept[NotImplementedException] { spark.sql(s"ALTER TABLE $tableName SET TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") } assert(error.getMessage.contains("Upgrading to CatalogOwned table is not yet supported.")) } @@ -390,7 +390,7 @@ class CatalogOwnedEnablementSuite sqlState = "55000", parameters = Map( "feature" -> InCommitTimestampTableFeature.name, - "dependentFeatures" -> CatalogOwnedTableFeature.name)) + "dependentFeatures" -> CatalogManagedTableFeature.name)) val error2 = intercept[DeltaTableFeatureException] { spark.sql(s"ALTER TABLE $tableName DROP FEATURE '${VacuumProtocolCheckTableFeature.name}'") @@ -401,7 +401,7 @@ class CatalogOwnedEnablementSuite sqlState = "55000", parameters = Map( "feature" -> VacuumProtocolCheckTableFeature.name, - "dependentFeatures" -> CatalogOwnedTableFeature.name)) + "dependentFeatures" -> CatalogManagedTableFeature.name)) } } @@ -425,7 +425,7 @@ class CatalogOwnedEnablementSuite withTable("t1") { val usageLog = Log4jUsageLogger.track { createTable("t1", properties = Map( - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported")) + s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported")) } val commitStatsUsageLog = filterUsageRecords(usageLog, "delta.commit.stats") val commitStats = JsonUtils.fromJson[CommitStats](commitStatsUsageLog.head.blob) @@ -446,7 +446,7 @@ class CatalogOwnedEnablementSuite // Create a path-based table so that we can simulate the scenario // where catalog table is not available. createTable(s"delta.`$tempDir`", properties = Map( - s"delta.feature.${CatalogOwnedTableFeature.name}" -> "supported")) + s"delta.feature.${CatalogManagedTableFeature.name}" -> "supported")) validateInvalidPathBasedAccessUsageLog( tempDir, expectedVersion = "0", diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala index 43f9543d62d..47e5125016c 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CatalogOwnedPropertySuite.scala @@ -42,7 +42,7 @@ class CatalogOwnedPropertySuite extends QueryTest * Validate if the table is catalog managed or not by checking the following: * 1) [[Snapshot.isCatalogOwned]] === expected * 2) [[Metadata.configuration]] contains [[UCCommitCoordinatorClient.UC_TABLE_ID_KEY]] - * 3) [[Protocol.readerAndWriterFeatureNames]] contains [[CatalogOwnedTableFeature.name]] + * 3) [[Protocol.readerAndWriterFeatureNames]] contains [[CatalogManagedTableFeature.name]] * and its dependent features. * * @param tableName The name of the table to validate. @@ -62,7 +62,7 @@ class CatalogOwnedPropertySuite extends QueryTest expectedMinReaderVersion = 3, expectedMinWriterVersion = 7) // Check dependent features as well. - CatalogOwnedTableFeature.requiredFeatures.foreach { feature => + CatalogManagedTableFeature.requiredFeatures.foreach { feature => assert(snapshot.protocol.readerAndWriterFeatureNames.contains(feature.name), s"Table $tableName should have ${feature.name} in protocol.") } @@ -74,7 +74,7 @@ class CatalogOwnedPropertySuite extends QueryTest withCatalogOwned: Boolean): Unit = { val createTableSQLStr = if (withCatalogOwned) { s"CREATE TABLE $tableName (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')" + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')" } else { s"CREATE TABLE $tableName (id LONG) USING delta" } @@ -211,7 +211,7 @@ class CatalogOwnedPropertySuite extends QueryTest val error = intercept[DeltaUnsupportedOperationException] { sql("REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") } checkError( exception = error, @@ -233,7 +233,7 @@ class CatalogOwnedPropertySuite extends QueryTest // Specifying CatalogManaged on an already CatalogManaged table should succeed. // The CatalogManaged properties are treated as a no-op. sql("REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") // Validate the table is still CatalogManaged with the same ucTableId. validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) @@ -255,7 +255,7 @@ class CatalogOwnedPropertySuite extends QueryTest val error = intercept[DeltaUnsupportedOperationException] { sql("REPLACE TABLE t1 USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported') " + + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported') " + s"AS SELECT * FROM t2") } checkError( @@ -281,7 +281,7 @@ class CatalogOwnedPropertySuite extends QueryTest // Specifying CatalogManaged on an already CatalogManaged table should succeed. sql("REPLACE TABLE t1 USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported') " + + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported') " + s"AS SELECT * FROM t2") // Validate the table is still CatalogManaged with the same ucTableId. @@ -338,7 +338,7 @@ class CatalogOwnedPropertySuite extends QueryTest withTable("t1") { // CREATE OR REPLACE on non-existing table with CatalogManaged should create a CC table. sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") // Mock UC integration behavior by inserting UC_TABLE_ID. addUCTableIdToTable(tableSource = Right("t1")) @@ -359,7 +359,7 @@ class CatalogOwnedPropertySuite extends QueryTest // CREATE OR REPLACE with CatalogManaged on existing CatalogManaged table should succeed. sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") // Validate the table is still CatalogManaged with the same ucTableId. validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) @@ -377,7 +377,7 @@ class CatalogOwnedPropertySuite extends QueryTest val versionBefore = getSnapshotVersion(tableName = "t1") sql("CREATE OR REPLACE TABLE t1 USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported') AS " + + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported') AS " + "SELECT 2 AS id") validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) @@ -413,7 +413,7 @@ class CatalogOwnedPropertySuite extends QueryTest val error = intercept[DeltaUnsupportedOperationException] { sql("CREATE OR REPLACE TABLE t1 USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported', " + + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported', " + s"'${UCCommitCoordinatorClient.UC_TABLE_ID_KEY}' = '${UUID.randomUUID().toString}') " + "AS SELECT 2 AS id") } @@ -437,7 +437,7 @@ class CatalogOwnedPropertySuite extends QueryTest // CREATE OR REPLACE with CatalogManaged on existing non-CatalogManaged table should fail. val error = intercept[DeltaUnsupportedOperationException] { sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") } checkError( exception = error, @@ -457,7 +457,7 @@ class CatalogOwnedPropertySuite extends QueryTest withTable("t1") { // First CREATE OR REPLACE creates the table. sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") // Mock UC integration behavior by inserting UC_TABLE_ID. addUCTableIdToTable(tableSource = Right("t1")) validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) @@ -467,14 +467,14 @@ class CatalogOwnedPropertySuite extends QueryTest // Second CREATE OR REPLACE should succeed as a no-op for CC properties. sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) val ucTableIdSecond = getUCTableIdFromTable(tableName = "t1") assert(ucTableIdFirst === ucTableIdSecond) // Third CREATE OR REPLACE should also succeed when the metadata is unchanged. sql("CREATE OR REPLACE TABLE t1 (id LONG) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") validateCatalogOwnedAndUCTableId(tableName = "t1", expected = true) val ucTableIdThird = getUCTableIdFromTable(tableName = "t1") assert(ucTableIdFirst === ucTableIdThird) @@ -530,14 +530,14 @@ class CatalogOwnedPropertySuite extends QueryTest val readerWriterFeatureNames = log.unsafeVolatileSnapshot.protocol.readerAndWriterFeatureNames assert(readerWriterFeatureNames.contains(ClusteringTableFeature.name) && - readerWriterFeatureNames.contains(CatalogOwnedTableFeature.name)) + readerWriterFeatureNames.contains(CatalogManagedTableFeature.name)) } } test("[REPLACE] ICT should not be present after replacing existing normal delta " + "table w/o ICT w/ default spark configuration") { withSQLConf( - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) -> "supported") { + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature) -> "supported") { withTable("t1", "t2") { withoutDefaultCCTableFeature { sql("CREATE TABLE t1 (id LONG) USING delta") @@ -564,7 +564,7 @@ class CatalogOwnedPropertySuite extends QueryTest test("[REPLACE] ICT-related properties should not be present after replacing existing " + "normal delta table w/ ICT w/ default spark configuration") { withSQLConf( - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) -> "supported") { + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature) -> "supported") { withTable("t1", "t2", "t3") { withoutDefaultCCTableFeature { sql("CREATE TABLE t1 (id LONG) USING delta") @@ -614,7 +614,7 @@ class CatalogOwnedPropertySuite extends QueryTest test("[REPLACE] ICT should be present after replacing existing normal delta " + "table w/o ICT w/ default spark configuration w/ explicitly overrides") { withSQLConf( - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) -> "supported") { + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature) -> "supported") { withTable("t1", "t2", "t3") { withoutDefaultCCTableFeature { sql("CREATE TABLE t1 (id LONG) USING delta") @@ -668,7 +668,7 @@ class CatalogOwnedPropertySuite extends QueryTest // w/ default CO enabled withSQLConf( - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) -> "supported", + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature) -> "supported", DeltaConfigs.IN_COMMIT_TIMESTAMPS_ENABLED.defaultTablePropertyKey -> "true") { sql("REPLACE TABLE t2 USING delta AS SELECT * FROM t1") validateInCommitTimestampPresent( @@ -714,7 +714,7 @@ class CatalogOwnedPropertySuite extends QueryTest expectedMinReaderVersion = 1, expectedMinWriterVersion = 2) validateCatalogOwnedAndUCTableId(tableName = "t1", expected = false) - CatalogOwnedTableFeature.requiredFeatures.foreach { feature => + CatalogManagedTableFeature.requiredFeatures.foreach { feature => assert(!featuresBeforeReplaceT1.contains(feature.name)) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala index 36fdd5dbc77..a3e85ce8c4f 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/coordinatedcommits/CoordinatedCommitsTestUtils.scala @@ -22,7 +22,7 @@ import java.util.UUID import java.util.concurrent.atomic.AtomicInteger import scala.collection.mutable import scala.util.control.NonFatal -import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, CheckpointPolicy, DeltaColumnMappingMode, DeltaConfig, DeltaConfigs, DeltaLog, DeltaTestUtilsBase, DomainMetadataTableFeature, MaterializedRowCommitVersion, MaterializedRowId, RowTrackingFeature, Snapshot, TableFeature} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, CheckpointPolicy, DeltaColumnMappingMode, DeltaConfig, DeltaConfigs, DeltaLog, DeltaTestUtilsBase, DomainMetadataTableFeature, MaterializedRowCommitVersion, MaterializedRowId, RowTrackingFeature, Snapshot, TableFeature} import org.apache.spark.sql.delta.DeltaOperations._ import org.apache.spark.sql.delta.actions.{CommitInfo, Metadata, Protocol, TableFeatureProtocolUtils} import org.apache.spark.sql.delta.catalog.DeltaTableV2 @@ -95,7 +95,7 @@ trait CatalogOwnedTestBaseSuite with SharedSparkSession { val defaultCatalogOwnedFeatureEnabledKey: String = - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature) + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature) // If this config is not overridden, newly created table is not CatalogManaged by default. def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = None @@ -130,7 +130,7 @@ trait CatalogOwnedTestBaseSuite } override def propertiesString: String = - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')" + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')" override protected def beforeEach(): Unit = { super.beforeEach() diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/rowtracking/RowTrackingConflictResolutionSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/rowtracking/RowTrackingConflictResolutionSuite.scala index 1ffcf24d8af..72fcd730d57 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/rowtracking/RowTrackingConflictResolutionSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/rowtracking/RowTrackingConflictResolutionSuite.scala @@ -190,7 +190,7 @@ class RowTrackingConflictResolutionSuite extends QueryTest Action.supportedProtocolVersion( // The AMT features are WIP; don't enable them by default in test tables. featuresToExclude = - Seq(CatalogOwnedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) + Seq(CatalogManagedTableFeature) ++ AdaptiveMetadataTableFeatureBase.features) .withFeature(RowTrackingFeature) ) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala index b6cdf8082d1..50cc85c3fde 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ClusteredTableDDLSuite.scala @@ -20,7 +20,7 @@ import java.io.File import com.databricks.spark.util.{Log4jUsageLogger, MetricDefinitions} import org.apache.spark.sql.delta.skipping.ClusteredTableTestUtils -import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, DeltaAnalysisException, DeltaColumnMappingEnableIdMode, DeltaColumnMappingEnableNameMode, DeltaConfigs, DeltaLog, DeltaUnsupportedOperationException, NoMapping} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, DeltaAnalysisException, DeltaColumnMappingEnableIdMode, DeltaColumnMappingEnableNameMode, DeltaConfigs, DeltaLog, DeltaUnsupportedOperationException, NoMapping} import org.apache.spark.sql.delta.actions.TableFeatureProtocolUtils import org.apache.spark.sql.delta.clustering.ClusteringMetadataDomain import org.apache.spark.sql.delta.coordinatedcommits.CatalogOwnedTestBaseSuite diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala index 492ee2c12ea..9a1e1390c8c 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaSQLTestUtils.scala @@ -21,7 +21,7 @@ import java.util.UUID import scala.util.Random -import org.apache.spark.sql.delta.{CatalogOwnedTableFeature, DeltaColumnMappingTestUtilsBase, DeltaLog, DeltaTable, Snapshot, TableFeature} +import org.apache.spark.sql.delta.{CatalogManagedTableFeature, DeltaColumnMappingTestUtilsBase, DeltaLog, DeltaTable, Snapshot, TableFeature} import org.apache.spark.sql.delta.actions.Protocol import org.apache.spark.sql.delta.coordinatedcommits.{CatalogManagedCommitCoordinatorProvider, CatalogOwnedTableUtils, TrackingInMemoryCommitCoordinatorBuilder} import org.apache.spark.sql.delta.stats.{DeltaStatistics, PreparedDeltaFileIndex} @@ -108,7 +108,7 @@ trait DeltaSQLTestUtils extends SQLTestUtils { /** * Creates a Catalog-Managed Delta table for tests. * - * @param createTable Whether to create the table with CatalogOwnedTableFeature enabled. + * @param createTable Whether to create the table with CatalogManagedTableFeature enabled. * @param f The function to execute with the generated table name. */ protected def withCatalogManagedTable(createTable: Boolean = true)(f: String => Unit): Unit = { @@ -119,7 +119,7 @@ trait DeltaSQLTestUtils extends SQLTestUtils { withTempTable(createTable = false) { tableName => if (createTable) { spark.sql(s"CREATE TABLE $tableName (id INT) USING delta TBLPROPERTIES " + - s"('delta.feature.${CatalogOwnedTableFeature.name}' = 'supported')") + s"('delta.feature.${CatalogManagedTableFeature.name}' = 'supported')") } f(tableName) } diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaTestImplicits.scala b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaTestImplicits.scala index 407d9b6665d..4b35410bf58 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaTestImplicits.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/test/DeltaTestImplicits.scala @@ -21,7 +21,7 @@ import java.sql.Timestamp import scala.collection.mutable.ArrayBuffer -import org.apache.spark.sql.delta.{AdaptiveMetadataTableFeatureBase, CatalogOwnedTableFeature, DeltaHistoryManager, DeltaLog, OptimisticTransaction, Snapshot, TableFeature} +import org.apache.spark.sql.delta.{AdaptiveMetadataTableFeatureBase, CatalogManagedTableFeature, DeltaHistoryManager, DeltaLog, OptimisticTransaction, Snapshot, TableFeature} import org.apache.spark.sql.delta.DeltaOperations.{ManualUpdate, Operation, Write} import org.apache.spark.sql.delta.SnapshotDescriptor import org.apache.spark.sql.delta.actions.{Action, AddFile, Metadata, Protocol, TableFeatureProtocolUtils} @@ -76,12 +76,12 @@ object DeltaTestImplicits { val featuresToExclude = ArrayBuffer[TableFeature](AdaptiveMetadataTableFeatureBase.features: _*) val enableCatalogOwnedByDefault = SparkSession.active.conf.getOption( - TableFeatureProtocolUtils.defaultPropertyKey(CatalogOwnedTableFeature)) + TableFeatureProtocolUtils.defaultPropertyKey(CatalogManagedTableFeature)) .contains("supported") if (!enableCatalogOwnedByDefault) { - // CatalogOwnedTableFeature is enabled by protocol only without metadata, and should + // CatalogManagedTableFeature is enabled by protocol only without metadata, and should // not be enabled by default. - featuresToExclude += CatalogOwnedTableFeature + featuresToExclude += CatalogManagedTableFeature } txn.updateProtocol( Action.supportedProtocolVersion(featuresToExclude = featuresToExclude.toSeq)) From febd8a47eb307ddc9ede5ccd5e2c7a172ffb231a Mon Sep 17 00:00:00 2001 From: Timothy Wang Date: Tue, 17 Nov 2026 20:43:59 -0800 Subject: [PATCH 35/44] [Flink] Preserve transaction identity when restoring checkpoints (#8203) #### Which Delta project/connector is this regarding? - [ ] Spark - [ ] Standalone - [x] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description When a Flink job is resubmitted from a checkpoint with a new job ID, the committer uses the new ID to replay work created by the old job. Delta treats the replay as a new transaction. For example, if OPTIMIZE has replaced an old file, replay can add that file back to the active table. If VACUUM has deleted it, the table can then reference a missing file. Use the job ID saved in each committable to identify its transaction. Group work by that saved job ID before sorting it by checkpoint number, so recovered work and new work stay separate even when their checkpoint numbers match. The checkpoint serialization format stays unchanged. The committer builder no longer needs a job ID; `withJobId()` remains as a deprecated no-op for compatibility. Upgrade caveat: if an older connector first committed checkpoint work under a replacement job ID, and there is no transaction record for its original job ID, restoring that checkpoint after upgrading can replay it once more. This change does not repair transaction history written by older versions. ## How was this patch tested? local and CI tests. ## Does this PR introduce _any_ user-facing changes? Restores the intended behavior when resubmitting a job from a checkpoint with a new job ID: already committed work is skipped, files removed by later transactions stay removed, and new work still commits. --------- Signed-off-by: Timothy Wang <31230953+timothyw553@users.noreply.github.com> --- .../io/delta/flink/sink/DeltaCommitter.java | 30 +++-- .../java/io/delta/flink/sink/DeltaSink.java | 1 - .../delta/flink/sink/DeltaCommitterTest.java | 119 ++++++++++++++++++ 3 files changed, 136 insertions(+), 14 deletions(-) diff --git a/flink/src/main/java/io/delta/flink/sink/DeltaCommitter.java b/flink/src/main/java/io/delta/flink/sink/DeltaCommitter.java index e0322c69a02..fd1548737a3 100644 --- a/flink/src/main/java/io/delta/flink/sink/DeltaCommitter.java +++ b/flink/src/main/java/io/delta/flink/sink/DeltaCommitter.java @@ -61,13 +61,8 @@ public class DeltaCommitter implements Committer { private static final Logger LOG = LoggerFactory.getLogger(DeltaCommitter.class); - // All committables should have the same job id as the committer. - // For simplicity, we get the job id from constructor. - private final String jobId; // The task prefix attached to checkpoint id when multiple sink instances presents private final int taskIndex; - // Uniquely identify the committer in DeltaLog transaction identifier - private final String committerId; private final DeltaTable deltaTable; private final DeltaSinkConf conf; @@ -76,14 +71,11 @@ public class DeltaCommitter implements Committer { private volatile long lastCommitDurationMs; private DeltaCommitter( - String jobId, int taskIndex, DeltaTable deltaTable, DeltaSinkConf conf, SinkCommitterMetricGroup metricGroup) { - this.jobId = jobId; this.taskIndex = taskIndex; - this.committerId = String.format("%s-%d", jobId, taskIndex); this.deltaTable = deltaTable; this.conf = conf; @@ -96,7 +88,17 @@ private DeltaCommitter( public void commit(Collection> committables) throws IOException, InterruptedException { LOG.debug("Starting commit"); - sortCommittablesByCheckpointId(committables).forEach(this::commitForSingleCheckpointId); + committables.stream() + .collect( + Collectors.groupingBy( + request -> request.getCommittable().getJobId(), + LinkedHashMap::new, + Collectors.toList())) + .values() + .forEach( + requests -> + sortCommittablesByCheckpointId(requests) + .forEach(this::commitForSingleCheckpointId)); } @Override @@ -111,6 +113,9 @@ private void commitForSingleCheckpointId( if (committables.isEmpty()) { return; } + // Restored work must keep the transaction identity of the job that created it. + String committerId = + String.format("%s-%d", committables.get(0).getCommittable().getJobId(), taskIndex); LOG.debug("Committing {} committables on checkpoint {}", committables.size(), checkpointId); metricGroup.getNumCommittablesTotalCounter().inc(committables.size()); @@ -203,7 +208,6 @@ private TreeMap>> sortCommittablesByC } public static final class Builder { - private String jobId; private int taskIndex; private DeltaTable deltaTable; private DeltaSinkConf conf; @@ -211,8 +215,9 @@ public static final class Builder { public Builder() {} + /** @deprecated The job ID is read from each committable. This method has no effect. */ + @Deprecated public Builder withJobId(String jobId) { - this.jobId = jobId; return this; } @@ -237,12 +242,11 @@ public Builder withMetricGroup(SinkCommitterMetricGroup metricGroup) { } public DeltaCommitter build() { - Objects.requireNonNull(jobId, "jobId must not be null"); Objects.requireNonNull(deltaTable, "deltaTable must not be null"); Objects.requireNonNull(metricGroup, "metricGroup must not be null"); Objects.requireNonNull(conf, "conf must not be null"); - return new DeltaCommitter(jobId, taskIndex, deltaTable, conf, metricGroup); + return new DeltaCommitter(taskIndex, deltaTable, conf, metricGroup); } } } diff --git a/flink/src/main/java/io/delta/flink/sink/DeltaSink.java b/flink/src/main/java/io/delta/flink/sink/DeltaSink.java index 19fa9e56aca..874ede4e967 100644 --- a/flink/src/main/java/io/delta/flink/sink/DeltaSink.java +++ b/flink/src/main/java/io/delta/flink/sink/DeltaSink.java @@ -118,7 +118,6 @@ public SinkWriter createWriter(WriterInitContext context) { public Committer createCommitter(CommitterInitContext context) { this.deltaTable.open(); return new DeltaCommitter.Builder() - .withJobId(context.getJobInfo().getJobId().toString()) .withTaskIndex(context.getTaskInfo().getIndexOfThisSubtask()) .withDeltaTable(deltaTable) .withConf(conf) diff --git a/flink/src/test/java/io/delta/flink/sink/DeltaCommitterTest.java b/flink/src/test/java/io/delta/flink/sink/DeltaCommitterTest.java index 09e35d8300a..3741e0a45b6 100644 --- a/flink/src/test/java/io/delta/flink/sink/DeltaCommitterTest.java +++ b/flink/src/test/java/io/delta/flink/sink/DeltaCommitterTest.java @@ -21,18 +21,27 @@ import io.delta.flink.TestHelper; import io.delta.flink.table.HadoopTable; import io.delta.flink.table.LocalFileSystemTable; +import io.delta.kernel.TableManager; +import io.delta.kernel.data.Row; import io.delta.kernel.defaults.engine.DefaultEngine; +import io.delta.kernel.internal.SnapshotImpl; import io.delta.kernel.internal.actions.AddFile; +import io.delta.kernel.internal.actions.SingleAction; +import io.delta.kernel.internal.util.Utils; import io.delta.kernel.types.*; +import io.delta.kernel.utils.CloseableIterable; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; +import java.util.stream.StreamSupport; import org.apache.flink.api.connector.sink2.Committer; import org.apache.flink.api.connector.sink2.mocks.MockCommitRequest; import org.apache.flink.runtime.metrics.groups.InternalSinkCommitterMetricGroup; import org.apache.flink.runtime.metrics.groups.UnregisteredMetricGroups; import org.apache.hadoop.conf.Configuration; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; /** JUnit test suite for {@link DeltaCommitter}. */ class DeltaCommitterTest extends TestHelper { @@ -102,6 +111,116 @@ void testCommitWithSingleCheckpointToAnEmptyTable() { }); } + @ParameterizedTest + @CsvSource({"false, false", "true, false", "true, true"}) + void testRestoreWithNewJobId(boolean alreadyCommitted, boolean removed) { + withTempDir( + dir -> { + StructType schema = new StructType().add("id", IntegerType.INTEGER); + HadoopTable table = new HadoopTable(dir.toURI(), Map.of(), schema, List.of()); + table.open(); + try { + DeltaSinkConf conf = new DeltaSinkConf(schema, Map.of()); + DeltaCommitter original = + new DeltaCommitter.Builder() + .withDeltaTable(table) + .withTaskIndex(3) + .withJobId("original-job") + .withMetricGroup(metricGroup) + .withConf(conf) + .build(); + DeltaCommittable pending = + new DeltaCommittable( + "original-job", + "test-operator", + 1L, + List.of(dummyAddFileRow(schema, 1, Map.of())), + new WriterResultContext()); + DeltaCommittable.Serializer serializer = new DeltaCommittable.Serializer(); + byte[] checkpoint = serializer.serialize(pending); + if (alreadyCommitted) { + original.commit(List.of(new MockCommitRequest<>(pending))); + } + if (removed) { + List removes = new ArrayList<>(); + verifyTableContent( + dir.toString(), + (version, files, props) -> + files.forEach( + file -> + removes.add( + SingleAction.createRemoveFileSingleAction( + file.toRemoveFileRow(true, Optional.empty()))))); + table.commit( + CloseableIterable.inMemoryIterable(Utils.toCloseableIterator(removes.iterator())), + "maintenance", + 1L, + Map.of()); + } + + DeltaCommitter restored = + new DeltaCommitter.Builder() + .withDeltaTable(table) + .withTaskIndex(3) + .withMetricGroup(metricGroup) + .withConf(conf) + .build(); + DeltaCommittable recovered = + serializer.deserialize(serializer.getVersion(), checkpoint); + restored.commit(List.of(new MockCommitRequest<>(recovered))); + SnapshotImpl snapshot = + (SnapshotImpl) TableManager.loadSnapshot(dir.toString()).build(table.getEngine()); + assertEquals( + Optional.of(1L), + snapshot.getLatestTransactionVersion(table.getEngine(), "original-job-3")); + assertEquals( + Optional.empty(), + snapshot.getLatestTransactionVersion(table.getEngine(), "restored-job-3")); + long expectedVersion = removed ? 2L : 1L; + int expectedFiles = removed ? 0 : 1; + verifyTableContent( + dir.toString(), + (version, files, props) -> { + assertEquals(expectedVersion, version); + assertEquals( + expectedFiles, StreamSupport.stream(files.spliterator(), false).count()); + }); + + // Defensive coverage: submit different job IDs with the same checkpoint number. + // Flink 2.3 normally commits each checkpoint manager separately. + DeltaCommittable fresh = + new DeltaCommittable( + "restored-job", + "test-operator", + 1L, + List.of(dummyAddFileRow(schema, 1, Map.of())), + new WriterResultContext()); + for (int attempt = 0; attempt < 2; attempt++) { + restored.commit( + List.of(new MockCommitRequest<>(recovered), new MockCommitRequest<>(fresh))); + snapshot = + (SnapshotImpl) TableManager.loadSnapshot(dir.toString()).build(table.getEngine()); + assertEquals( + Optional.of(1L), + snapshot.getLatestTransactionVersion(table.getEngine(), "original-job-3")); + assertEquals( + Optional.of(1L), + snapshot.getLatestTransactionVersion(table.getEngine(), "restored-job-3")); + verifyTableContent( + dir.toString(), + (version, files, props) -> { + assertEquals(expectedVersion + 1, version); + assertEquals( + expectedFiles + 1, + StreamSupport.stream(files.spliterator(), false).count()); + }); + } + } finally { + table.close(); + } + }); + } + @Test void testCommitWithMultipleCheckpoints() { withTempDir( From 832db36a4e8f097d214964c477d3c375ef68c8ac Mon Sep 17 00:00:00 2001 From: Tathagata Das Date: Tue, 17 Nov 2026 23:45:36 -0500 Subject: [PATCH 36/44] [Spark][DEDUP] Follow-up: cover metadata schema conversion (#8215) [AI-assisted] #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description This test-only follow-up to #8105 exercises the production metadata schema conversion path with the converter's former test inputs. It also adds a smoke test for UTF8_BINARY string schemas, including array and nested-struct shapes. ## How was this patch tested? ```shell build/sbt "sparkV2/Test/javafmtCheck" "sparkV2/javafmtCheck" build/sbt "sparkV2/testOnly org.apache.spark.sql.delta.v2.utils.SchemaUtilsTest" ``` `SchemaUtilsTest` passes all 44 test cases. ## Does this PR introduce _any_ user-facing changes? No. --------- Signed-off-by: tdas Co-authored-by: omnigent --- .../sql/delta/v2/utils/SchemaUtilsTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java index b3037c6c60c..0a8b1549d9c 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/SchemaUtilsTest.java @@ -21,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.delta.kernel.internal.actions.Format; +import io.delta.kernel.internal.util.VectorUtils; import io.delta.kernel.types.ArrayType; import io.delta.kernel.types.BinaryType; import io.delta.kernel.types.BooleanType; @@ -40,6 +42,8 @@ import io.delta.kernel.types.TimestampNTZType; import io.delta.kernel.types.TimestampType; import io.delta.kernel.types.VariantType; +import java.util.Collections; +import java.util.Optional; import java.util.stream.Stream; import org.apache.spark.sql.AnalysisException; import org.apache.spark.sql.types.DataTypes; @@ -217,6 +221,31 @@ public void testConvertSparkSchemaToKernelSchema() { assertEquals(expectedKernelSchema, actualKernelSchema); } + @Test + public void testConvertKernelMetadataToSparkSchema() { + StructType kernelSchema = + new StructType().add("a", IntegerType.INTEGER, true).add("b", StringType.STRING, false); + + org.apache.spark.sql.types.StructType expectedSparkSchema = + DataTypes.createStructType( + new org.apache.spark.sql.types.StructField[] { + DataTypes.createStructField("a", DataTypes.IntegerType, true), + DataTypes.createStructField("b", DataTypes.StringType, false) + }); + + assertEquals(expectedSparkSchema, convertKernelSchemaThroughMetadata(kernelSchema)); + } + + @Test + public void testUtf8BinaryCollatedStringSchemasConvertThroughMetadata() { + StringType kernelString = new StringType("SPARK.UTF8_BINARY"); + Stream.of( + new StructType().add("s", kernelString), + new StructType().add("a", new ArrayType(kernelString, true)), + new StructType().add("outer", new StructType().add("s", kernelString))) + .forEach(SchemaUtilsTest::convertKernelSchemaThroughMetadata); + } + @Test public void testSchemaRoundTripWithFieldMetadata() { // Schema with field metadata (e.g., column mapping) @@ -245,12 +274,34 @@ public void testSchemaRoundTripWithFieldMetadata() { // Verify Spark → Kernel conversion StructType actualKernelSchema = SchemaUtils.convertSparkSchemaToKernelSchema(sparkSchema); assertEquals(expectedKernelSchema, actualKernelSchema); + + // Verify Kernel -> Spark conversion through the table schema string + assertEquals(sparkSchema, convertKernelSchemaThroughMetadata(actualKernelSchema)); } private void checkConversion( org.apache.spark.sql.types.DataType sparkDataType, DataType kernelDataType) { DataType toKernel = SchemaUtils.convertSparkDataTypeToKernelDataType(sparkDataType); assertEquals(kernelDataType, toKernel); + assertEquals( + new org.apache.spark.sql.types.StructType().add("c", sparkDataType), + convertKernelSchemaThroughMetadata(new StructType().add("c", kernelDataType))); + } + + /** Converts {@code kernelSchema} the way V2 reads a table schema: from its log schema string. */ + private static org.apache.spark.sql.types.StructType convertKernelSchemaThroughMetadata( + StructType kernelSchema) { + return SchemaUtils.convertKernelMetadataToSparkSchema( + new io.delta.kernel.internal.actions.Metadata( + "id", + Optional.empty() /* name */, + Optional.empty() /* description */, + new Format(), + kernelSchema.toJson(), + kernelSchema, + VectorUtils.buildArrayValue(Collections.emptyList(), StringType.STRING), + Optional.empty() /* createdTime */, + VectorUtils.stringStringMapValue(Collections.emptyMap()))); } //////////////////////////////// @@ -377,6 +428,9 @@ public void testMetadataConversion( String typeName, Metadata sparkMetadata, FieldMetadata kernelMetadata) { assertEquals( kernelMetadata, SchemaUtils.convertSparkMetadataToKernelFieldMetadata(sparkMetadata)); + StructType kernelSchema = new StructType().add("c", IntegerType.INTEGER, true, kernelMetadata); + assertEquals( + sparkMetadata, convertKernelSchemaThroughMetadata(kernelSchema).apply("c").metadata()); } @Test From b8c6bbf897bc4d49b209a534ea147208c1c054fc Mon Sep 17 00:00:00 2001 From: Thinh Bui <26578143+thinh2@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:05:59 -0800 Subject: [PATCH 37/44] [Kernel] Make checkpoint search batch size configurable (#8201) #### Which Delta project/connector is this regarding? - [ ] Spark - [ ] Standalone - [ ] Flink - [x] Kernel - [ ] Other (fill in here) ## Description Java Kernel searches for checkpoints in fixed 1,000-version batches. On tables with frequent multipart checkpoints, a batch can contain many objects and make snapshot loading expensive. This PR adds `SnapshotBuilder.withCheckpointSearchBatchSize(int)` so callers can choose a positive batch width per snapshot. Kernel uses that width for both the initial search and stale-checkpoint fallback, and continues into older batches until it finds a complete checkpoint. The default remains 1,000 versions. The internal Checkpointer and full SnapshotManager calls require the width explicitly. Checkpoint search also closes each listing iterator and stops after checking the zero-start batch once. ## How was this patch tested? Added tests for a width of 5 across older batches and stale-checkpoint fallback, nonpositive width rejection, missing and incomplete checkpoints at the zero-start batch, and listing-iterator closure across batches and on return. From the repository root with JDK 17: ```bash sbt --java-home /usr/lib/jvm/java-17-openjdk-amd64 -batch -no-colors 'kernelApi/testOnly io.delta.kernel.*' ``` Passed: 2,985 tests, 0 failures, 0 errors. ## Does this PR introduce _any_ user-facing changes? Yes. `SnapshotBuilder` gains `withCheckpointSearchBatchSize(int)`. Previously, checkpoint discovery always searched 1,000 versions per batch. Callers can now set a positive width for a snapshot; callers that do not set it retain the 1,000-version default. --------- Signed-off-by: Thinh Bui <26578143+thinh2@users.noreply.github.com> --- .../java/io/delta/kernel/SnapshotBuilder.java | 13 ++++ .../internal/checkpoints/Checkpointer.java | 42 ++++++------ .../internal/snapshot/SnapshotManager.java | 24 ++++--- .../internal/table/SnapshotBuilderImpl.java | 9 +++ .../internal/table/SnapshotFactory.java | 6 +- .../internal/SnapshotManagerSuite.scala | 43 ++++++++---- .../catalogManaged/SnapshotBuilderSuite.scala | 31 ++++++++- .../checkpoints/CheckpointerSuite.scala | 66 ++++++++++++++++++- 8 files changed, 191 insertions(+), 43 deletions(-) diff --git a/kernel/kernel-api/src/main/java/io/delta/kernel/SnapshotBuilder.java b/kernel/kernel-api/src/main/java/io/delta/kernel/SnapshotBuilder.java index e266ead1199..9728ec7cc85 100644 --- a/kernel/kernel-api/src/main/java/io/delta/kernel/SnapshotBuilder.java +++ b/kernel/kernel-api/src/main/java/io/delta/kernel/SnapshotBuilder.java @@ -50,6 +50,19 @@ public interface SnapshotBuilder { */ SnapshotBuilder atVersion(long version); + /** + * Sets the number of versions searched per batch when finding a checkpoint for a snapshot. + * + *

Smaller batches can reduce listing work for tables with frequent or multipart checkpoints. + * Larger batches can avoid extra listing calls when checkpoints are sparse. If a batch has no + * complete checkpoint, Kernel continues searching older batches. The default batch size is 1000 + * versions. + * + * @param batchSize the number of versions per search batch; must be positive + * @return this builder configured with the search batch size + */ + SnapshotBuilder withCheckpointSearchBatchSize(int batchSize); + /** * Configures the builder to resolve the table at a specific timestamp. * diff --git a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/checkpoints/Checkpointer.java b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/checkpoints/Checkpointer.java index 57874ec6516..53ce51e441c 100644 --- a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/checkpoints/Checkpointer.java +++ b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/checkpoints/Checkpointer.java @@ -20,6 +20,7 @@ import static io.delta.kernel.internal.TableConfig.LOG_RETENTION; import static io.delta.kernel.internal.snapshot.MetadataCleanup.cleanupExpiredLogs; import static io.delta.kernel.internal.tablefeatures.TableFeatures.CHECKPOINT_PROTECTION_W_FEATURE; +import static io.delta.kernel.internal.util.Preconditions.checkArgument; import static io.delta.kernel.internal.util.Utils.singletonCloseableIterator; import com.fasterxml.jackson.core.JsonProcessingException; @@ -56,6 +57,9 @@ public class Checkpointer { private static final int READ_LAST_CHECKPOINT_FILE_MAX_RETRIES = 3; + /** Default number of versions searched per batch when finding a checkpoint. */ + public static final int DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE = 1000; + /** The name of the last checkpoint file */ public static final String LAST_CHECKPOINT_FILE_NAME = "_last_checkpoint"; @@ -173,8 +177,8 @@ public static Optional getLatestCompleteCheckpointFromList( /** Find the last complete checkpoint before (strictly less than) a given version. */ public static Optional findLastCompleteCheckpointBefore( - Engine engine, Path tableLogPath, long version) { - return findLastCompleteCheckpointBeforeHelper(engine, tableLogPath, version)._1; + Engine engine, Path tableLogPath, long version, int batchSize) { + return findLastCompleteCheckpointBeforeHelper(engine, tableLogPath, version, batchSize)._1; } /** @@ -182,7 +186,8 @@ public static Optional findLastCompleteCheckpointBefore( * searched. This helps in testing */ public static Tuple2, Long> findLastCompleteCheckpointBeforeHelper( - Engine engine, Path tableLogPath, long version) { + Engine engine, Path tableLogPath, long version, int batchSize) { + checkArgument(batchSize > 0, "checkpoint search batch size must be > 0"); CheckpointInstance upperBoundCheckpoint = new CheckpointInstance(version); logger.info("Try to find the last complete checkpoint before version {}", version); @@ -190,22 +195,18 @@ public static Tuple2, Long> findLastCompleteCheckpo long numberOfFilesSearched = 0; long currentVersion = version; - // Some cloud storage APIs make a calls to fetch 1000 at a time. - // To make use of that observation and to avoid making more listing calls than - // necessary, list 1000 at a time (backwards from the given version). Search - // within that list if a checkpoint is found. If found stop, otherwise list the previous - // 1000 entries. Repeat until a checkpoint is found or there are no more delta commits. + // Multipart checkpoints can add many files per version. Start each pass at most batchSize + // versions before currentVersion, and search earlier if no complete checkpoint is found. while (currentVersion >= 0) { - try { - long searchLowerBound = Math.max(0, currentVersion - 1000); - CloseableIterator deltaLogFileIter = - wrapEngineExceptionThrowsIO( - () -> - engine - .getFileSystemClient() - .listFrom(FileNames.listingPrefix(tableLogPath, searchLowerBound)), - "Listing from %s", - FileNames.listingPrefix(tableLogPath, searchLowerBound)); + long searchLowerBound = Math.max(0, currentVersion - batchSize); + try (CloseableIterator deltaLogFileIter = + wrapEngineExceptionThrowsIO( + () -> + engine + .getFileSystemClient() + .listFrom(FileNames.listingPrefix(tableLogPath, searchLowerBound)), + "Listing from %s", + FileNames.listingPrefix(tableLogPath, searchLowerBound))) { List checkpoints = new ArrayList<>(); while (deltaLogFileIter.hasNext()) { @@ -250,7 +251,10 @@ public static Tuple2, Long> findLastCompleteCheckpo latestCheckpoint.get()); return new Tuple2<>(latestCheckpoint, numberOfFilesSearched); } - currentVersion -= 1000; // search for checkpoint in previous 1000 entries + if (searchLowerBound == 0) { + break; + } + currentVersion -= batchSize; } catch (IOException e) { String msg = String.format( diff --git a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/snapshot/SnapshotManager.java b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/snapshot/SnapshotManager.java index cf5f8c44d90..d920a01ce19 100644 --- a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/snapshot/SnapshotManager.java +++ b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/snapshot/SnapshotManager.java @@ -204,7 +204,8 @@ public LogSegment getLogSegmentForVersion(Engine engine, Optional versionT engine, versionToLoadOpt, Collections.emptyList() /* parsedLogDatas */, - Optional.empty() /* maxCatalogVersionOpt */); + Optional.empty() /* maxCatalogVersionOpt */, + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE); } /** @@ -220,7 +221,8 @@ public LogSegment getLogSegmentForVersion( Engine engine, Optional timeTravelVersionOpt, List parsedLogDatas, - Optional maxCatalogVersionOpt) { + Optional maxCatalogVersionOpt, + int checkpointSearchBatchSize) { // This is the actual version we want to load. For "latest" (aka non-time-travel) queries for // catalogManaged tables we want to load the maxCatalogVersion final Optional versionToLoadOpt = @@ -236,7 +238,8 @@ public LogSegment getLogSegmentForVersion( /////////////////////////////////////////////////////////////////////////////////////////// final Optional startCheckpointVersionOpt = - getStartCheckpointVersion(engine, timeTravelVersionOpt, maxCatalogVersionOpt); + getStartCheckpointVersion( + engine, timeTravelVersionOpt, maxCatalogVersionOpt, checkpointSearchBatchSize); // Primary attempt to build the log segment Optional result = @@ -258,7 +261,8 @@ public LogSegment getLogSegmentForVersion( tablePath, startCheckpointVersionOpt.get()); Optional fallbackStart = - findFallbackCheckpointVersion(engine, startCheckpointVersionOpt.get()); + findFallbackCheckpointVersion( + engine, startCheckpointVersionOpt.get(), checkpointSearchBatchSize); try { Optional fallbackResult = buildLogSegmentFromStartCheckpointVersion( @@ -625,10 +629,10 @@ private Optional buildLogSegmentFromStartCheckpointVersion( * fallback when the primary checkpoint (from _last_checkpoint or backwards search) is stale. */ private Optional findFallbackCheckpointVersion( - Engine engine, long maxExclusiveCheckpointVersion) { + Engine engine, long maxExclusiveCheckpointVersion, int checkpointSearchBatchSize) { Optional fallbackVersion = Checkpointer.findLastCompleteCheckpointBefore( - engine, logPath, maxExclusiveCheckpointVersion) + engine, logPath, maxExclusiveCheckpointVersion, checkpointSearchBatchSize) .map(cp -> cp.version); logger.info( "{}: Fallback: Searched for earlier checkpoint before version {}. Found: {}.", @@ -700,7 +704,10 @@ private List getAllDeltasAfterCheckpointWithCatalogPriority( * backwards for a checkpoint). */ private Optional getStartCheckpointVersion( - Engine engine, Optional timeTravelVersionOpt, Optional maxCatalogVersionOpt) { + Engine engine, + Optional timeTravelVersionOpt, + Optional maxCatalogVersionOpt, + int checkpointSearchBatchSize) { // This is a "latest" query, let's try to use the _last_checkpoint file if possible if (!timeTravelVersionOpt.isPresent()) { logger.info("Reading the _last_checkpoint file for 'latest' query"); @@ -747,7 +754,8 @@ private Optional getStartCheckpointVersion( + "is empty we should always have returned earlier"))); logger.info("Finding last complete checkpoint at or before version {}", versionToLoad); final long startTimeMillis = System.currentTimeMillis(); - return Checkpointer.findLastCompleteCheckpointBefore(engine, logPath, versionToLoad + 1) + return Checkpointer.findLastCompleteCheckpointBefore( + engine, logPath, versionToLoad + 1, checkpointSearchBatchSize) .map(checkpointInstance -> checkpointInstance.version) .map( checkpointVersion -> { diff --git a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotBuilderImpl.java b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotBuilderImpl.java index 34d45c0c2f4..6eea435c19c 100644 --- a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotBuilderImpl.java +++ b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotBuilderImpl.java @@ -16,6 +16,7 @@ package io.delta.kernel.internal.table; +import static io.delta.kernel.internal.checkpoints.Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE; import static io.delta.kernel.internal.util.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; @@ -53,6 +54,7 @@ public static class Context { public List logDatas = Collections.emptyList(); public Optional> protocolAndMetadataOpt = Optional.empty(); public Optional maxCatalogVersion = Optional.empty(); + public int checkpointSearchBatchSize = DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE; public Context(String unresolvedPath) { this.unresolvedPath = requireNonNull(unresolvedPath, "unresolvedPath is null"); @@ -76,6 +78,13 @@ public SnapshotBuilderImpl atVersion(long version) { return this; } + @Override + public SnapshotBuilderImpl withCheckpointSearchBatchSize(int batchSize) { + checkArgument(batchSize > 0, "checkpoint search batch size must be > 0"); + ctx.checkpointSearchBatchSize = batchSize; + return this; + } + @Override public SnapshotBuilderImpl atTimestamp(long millisSinceEpochUTC, Snapshot latestSnapshot) { requireNonNull(latestSnapshot, "latestSnapshot is null"); diff --git a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotFactory.java b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotFactory.java index 34896775854..32df50af8ad 100644 --- a/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotFactory.java +++ b/kernel/kernel-api/src/main/java/io/delta/kernel/internal/table/SnapshotFactory.java @@ -250,7 +250,11 @@ private Lazy getLazyLogSegment( () -> new SnapshotManager(tablePath) .getLogSegmentForVersion( - engine, timeTravelVersion, ctx.logDatas, ctx.maxCatalogVersion)); + engine, + timeTravelVersion, + ctx.logDatas, + ctx.maxCatalogVersion, + ctx.checkpointSearchBatchSize)); snapshotCtx.setResolvedVersion(logSegment.getVersion()); snapshotCtx.setCheckpointVersion(logSegment.getCheckpointVersionOpt()); diff --git a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/SnapshotManagerSuite.scala b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/SnapshotManagerSuite.scala index 14a6bdece68..261dd3bb161 100644 --- a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/SnapshotManagerSuite.scala +++ b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/SnapshotManagerSuite.scala @@ -25,7 +25,7 @@ import io.delta.kernel.data.{ColumnarBatch, ColumnVector} import io.delta.kernel.engine.FileReadResult import io.delta.kernel.exceptions.{InvalidTableException, TableNotFoundException, VersionToLoadAfterLatestCommitException, VersionTruncatedException} import io.delta.kernel.expressions.Predicate -import io.delta.kernel.internal.checkpoints.{CheckpointInstance, CheckpointMetaData, SidecarFile} +import io.delta.kernel.internal.checkpoints.{Checkpointer, CheckpointInstance, CheckpointMetaData, SidecarFile} import io.delta.kernel.internal.fs.Path import io.delta.kernel.internal.snapshot.{LogSegment, SnapshotManager} import io.delta.kernel.internal.util.{FileNames, Utils} @@ -720,6 +720,27 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { expectedLastCommitTimestamp = 200L) } + test("getLogSegmentForVersion: stale checkpoint fallback uses checkpointSearchBatchSize") { + val files = deltaFileStatuses(0L until 25L) ++ singularCheckpointFileStatuses(Seq(10L)) + val fileSystemClient = new MockListFromFileSystemClient(listFromProvider(files)) + val engine = mockEngine( + fileSystemClient = fileSystemClient, + jsonHandler = new MockReadLastCheckpointFileJsonHandler( + s"$logPath/_last_checkpoint", + 20L)) + + val logSegment = snapshotManager.getLogSegmentForVersion( + engine, + Optional.empty(), + Collections.emptyList(), + Optional.empty(), + 5) + + assert(logSegment.getCheckpointVersionOpt.get() === 10L) + assert(fileSystemClient.getListFromCalls === Seq(20L, 15L, 10L, 10L) + .map(version => FileNames.listingPrefix(logPath, version))) + } + test("getLogSegmentForVersion: corrupted incomplete multi-part checkpoint with no" + "_last_checkpoint or a valid _last_checkpoint provided") { val cases: Seq[(Long, Seq[Long], Seq[Long], Optional[java.lang.Long])] = Seq( @@ -910,8 +931,8 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { createMockFSListFromEngine(deltas ++ checkpoints), Optional.empty(), // timeTravelVersionOpt Collections.emptyList(), // parsedLogDatas - Optional.of(15L) // maxCatalogVersionOpt - ) + Optional.of(15L), // maxCatalogVersionOpt + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) checkLogSegment( logSegment, @@ -931,8 +952,8 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { createMockFSListFromEngine(deltas ++ checkpoints), Optional.empty(), // timeTravelVersionOpt Collections.emptyList(), // parsedLogDatas - Optional.of(20L) // maxCatalogVersionOpt - ) + Optional.of(20L), // maxCatalogVersionOpt + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) // Should find checkpoint at version 10 by searching backwards from version 20 checkLogSegment( @@ -973,8 +994,8 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { mockedEngine, Optional.empty(), // timeTravelVersionOpt Collections.emptyList(), // parsedLogDatas - Optional.of(30L) // maxCatalogVersionOpt - ) + Optional.of(30L), // maxCatalogVersionOpt + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) checkLogSegment( logSegment, @@ -1003,8 +1024,8 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { fileSystemClient = new MockListFromFileSystemClient(listFromProvider(files))), Optional.empty(), // timeTravelVersionOpt Collections.emptyList(), // parsedLogDatas - Optional.of(24L) // maxCatalogVersionOpt is 24, which is < 25 - ) + Optional.of(24L), // maxCatalogVersionOpt is 24, which is < 25 + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) // Should use checkpoint at version 20 not 25, and should load maxCatalogVersion checkLogSegment( @@ -1046,8 +1067,8 @@ class SnapshotManagerSuite extends AnyFunSuite with MockFileSystemClientUtils { fileSystemClient = new MockListFromFileSystemClient(listFromProvider(files))), Optional.of(15L), // timeTravelVersionOpt = 15 Collections.emptyList(), // parsedLogDatas - Optional.of(30L) // maxCatalogVersionOpt - ) + Optional.of(30L), // maxCatalogVersionOpt + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) // Should use checkpoint at version 10 for time travel to version 15 checkLogSegment( diff --git a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/catalogManaged/SnapshotBuilderSuite.scala b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/catalogManaged/SnapshotBuilderSuite.scala index af951049a95..6111dca6e1b 100644 --- a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/catalogManaged/SnapshotBuilderSuite.scala +++ b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/catalogManaged/SnapshotBuilderSuite.scala @@ -29,7 +29,8 @@ import io.delta.kernel.internal.actions.Protocol import io.delta.kernel.internal.commit.DefaultFileSystemManagedTableOnlyCommitter import io.delta.kernel.internal.files.{ParsedCatalogCommitData, ParsedLogData, ParsedPublishedDeltaData} import io.delta.kernel.internal.table.SnapshotBuilderImpl -import io.delta.kernel.test.{ActionUtils, MockFileSystemClientUtils, MockSnapshotUtils, VectorTestUtils} +import io.delta.kernel.internal.util.FileNames +import io.delta.kernel.test.{ActionUtils, MockFileSystemClientUtils, MockListFromFileSystemClient, MockSnapshotUtils, VectorTestUtils} import io.delta.kernel.types.{IntegerType, StructType} import io.delta.kernel.utils.CloseableIterator @@ -67,6 +68,34 @@ class SnapshotBuilderSuite extends AnyFunSuite assert(exMsg === "version must be >= 0") } + test("withCheckpointSearchBatchSize: searches older batches with the supplied width") { + val files = deltaFileStatuses(Seq.range(0, 26)) ++ singularCheckpointFileStatuses(Seq(20)) + val fileSystemClient = new MockListFromFileSystemClient(listFromProvider(files)) + val engine = mockEngine(fileSystemClient = fileSystemClient) + + val snapshot = TableManager.loadSnapshot(dataPath.toString) + .asInstanceOf[SnapshotBuilderImpl] + .atVersion(25) + .withCheckpointSearchBatchSize(5) + .withProtocolAndMetadata(protocol, metadata) + .build(engine) + + assert(snapshot.getLogSegment.getCheckpointVersionOpt.get() === 20L) + assert(fileSystemClient.getListFromCalls === Seq(21L, 16L, 20L) + .map(version => FileNames.listingPrefix(logPath, version))) + } + + test("withCheckpointSearchBatchSize: rejects nonpositive values") { + Seq(0, -1).foreach { batchSize => + val exMsg = intercept[IllegalArgumentException] { + TableManager.loadSnapshot(dataPath.toString) + .withCheckpointSearchBatchSize(batchSize) + }.getMessage + + assert(exMsg === "checkpoint search batch size must be > 0") + } + } + // ===== Timestamp Tests ===== // test("atTimestamp: null latestSnapshot throws NullPointerException") { diff --git a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/checkpoints/CheckpointerSuite.scala b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/checkpoints/CheckpointerSuite.scala index 4a8651d7b52..7cf219b3eb9 100644 --- a/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/checkpoints/CheckpointerSuite.scala +++ b/kernel/kernel-api/src/test/scala/io/delta/kernel/internal/checkpoints/CheckpointerSuite.scala @@ -27,9 +27,10 @@ import io.delta.kernel.exceptions.KernelEngineException import io.delta.kernel.expressions.Predicate import io.delta.kernel.internal.checkpoints.Checkpointer.findLastCompleteCheckpointBeforeHelper import io.delta.kernel.internal.fs.Path +import io.delta.kernel.internal.util.FileNames import io.delta.kernel.internal.util.FileNames.checkpointFileSingular import io.delta.kernel.internal.util.Utils -import io.delta.kernel.test.{BaseMockFileSystemClient, BaseMockJsonHandler, MockFileSystemClientUtils, VectorTestUtils} +import io.delta.kernel.test.{BaseMockFileSystemClient, BaseMockJsonHandler, MockFileSystemClientUtils, MockListFromFileSystemClient, VectorTestUtils} import io.delta.kernel.types.StructType import io.delta.kernel.utils.{CloseableIterator, FileStatus} @@ -143,6 +144,57 @@ class CheckpointerSuite extends AnyFunSuite with MockFileSystemClientUtils { } } + test("findLastCompleteCheckpointBefore - small batches list zero prefix once") { + val deltas = deltaFileStatuses(0L until 25L) + val incompleteCheckpoint = multiCheckpointFileStatuses(Seq(10L), 3).take(2) + + Seq(Seq.empty[FileStatus], incompleteCheckpoint).foreach { checkpoints => + val fileSystemClient = new MockListFromFileSystemClient( + listFromProvider(deltas ++ checkpoints)) + val result = findLastCompleteCheckpointBeforeHelper( + mockEngine(fileSystemClient = fileSystemClient), + logPath, + 25L, + 5) + + assert(!result._1.isPresent) + assert(fileSystemClient.getListFromCalls === Seq(20L, 15L, 10L, 5L, 0L) + .map(version => FileNames.listingPrefix(logPath, version))) + } + } + + test("findLastCompleteCheckpointBefore - closes listing iterators across batches") { + val files = deltaFileStatuses(0L until 25L) ++ singularCheckpointFileStatuses(Seq(10L)) + var events = Seq.empty[String] + val fileSystemClient = new MockListFromFileSystemClient(listFromProvider(files)) { + override def listFrom(filePath: String): CloseableIterator[FileStatus] = { + events = events :+ s"open $filePath" + val delegate = super.listFrom(filePath) + new CloseableIterator[FileStatus] { + override def hasNext: Boolean = delegate.hasNext + override def next(): FileStatus = delegate.next() + override def close(): Unit = { + events = events :+ s"close $filePath" + delegate.close() + } + } + } + } + + val result = findLastCompleteCheckpointBeforeHelper( + mockEngine(fileSystemClient = fileSystemClient), + logPath, + 25L, + 5) + + assert(result._1.isPresent && result._1.get().version == 10L) + val expectedEvents = Seq(20L, 15L, 10L).flatMap { version => + val prefix = FileNames.listingPrefix(logPath, version) + Seq(s"open $prefix", s"close $prefix") + } + assert(events === expectedEvents) + } + test("findLastCompleteCheckpointBefore - single checkpoint") { // 25 delta files and 1 checkpoint file = total 26 files. val files = deltaFileStatuses(Seq.range(0, 25)) ++ singularCheckpointFileStatuses(Seq(10)) @@ -279,7 +331,11 @@ class CheckpointerSuite extends AnyFunSuite with MockFileSystemClientUtils { expCheckpointVersion: Long, expNumFilesListed: Long): Unit = { val engine = createMockFSListFromEngine(deltaLogFiles) - val result = findLastCompleteCheckpointBeforeHelper(engine, logPath, beforeVersion) + val result = findLastCompleteCheckpointBeforeHelper( + engine, + logPath, + beforeVersion, + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) assert(result._1.isPresent, s"Checkpoint should be found for version=$beforeVersion") assert( result._1.get().version === expCheckpointVersion, @@ -292,7 +348,11 @@ class CheckpointerSuite extends AnyFunSuite with MockFileSystemClientUtils { beforeVersion: Long, expNumFilesListed: Long): Unit = { val engine = createMockFSListFromEngine(deltaLogFiles) - val result = findLastCompleteCheckpointBeforeHelper(engine, logPath, beforeVersion) + val result = findLastCompleteCheckpointBeforeHelper( + engine, + logPath, + beforeVersion, + Checkpointer.DEFAULT_CHECKPOINT_SEARCH_BATCH_SIZE) assert(!result._1.isPresent, s"No checkpoint should be found for version=$beforeVersion") assert(result._2 == expNumFilesListed, s"Invalid number of files listed: $beforeVersion") } From d33d2f800b26eb3780f5c670fbae729437d9575e Mon Sep 17 00:00:00 2001 From: You Zhou <98635051+PorridgeSwim@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:10:46 -0800 Subject: [PATCH 38/44] [Spark] Preserve resolved partition names during V2 column pruning (#8218) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Match partition columns by their already-resolved names in `DeltaV2ScanBuilder.pruneColumns`, instead of lowercasing both sides. This preserves a metadata field named `__metadata` beside a partition column named `__Metadata`, while still excluding the partition column from the data-read schema. CDC column filtering remains case-insensitive. ## How was this patch tested? Added a regression test using a Delta table with a stored `_metadata` column and a `__Metadata` partition column. The test passes a resolved `__metadata` metadata field directly to the scan builder and verifies that pruning preserves it under both case-sensitivity settings. Local test execution is deferred to CI. `git diff --check` passed. ## Does this PR introduce _any_ user-facing changes? Yes. V2 column pruning preserves resolved metadata fields whose names differ from partition-column names only by case, instead of discarding them. Signed-off-by: You Zhou --- .../delta/v2/read/DeltaV2ScanBuilder.scala | 8 ++-- .../delta/v2/read/DeltaV2ScanBuilderTest.java | 38 +++++++++++++++++++ 2 files changed, 41 insertions(+), 5 deletions(-) diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala index de39a0fedaf..a3698faae79 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilder.scala @@ -16,7 +16,7 @@ package org.apache.spark.sql.delta.v2.read -import java.util.{Locale, Objects, OptionalInt} +import java.util.{Objects, OptionalInt} import scala.jdk.OptionConverters._ @@ -98,8 +98,7 @@ private[read] class DeltaV2ScanBuilder( Objects.requireNonNull(catalogStats, "catalogStats is null") Objects.requireNonNull(options, "options is null") - private val partitionColumnSet: Set[String] = - partitionSchema.fields.map(_.name.toLowerCase(Locale.ROOT)).toSet + private val partitionColumnNames: Set[String] = partitionSchema.names.toSet private var requiredDataSchema: StructType = dataSchema @@ -134,8 +133,7 @@ private[read] class DeltaV2ScanBuilder( // CDC columns are injected later by CDCReadFunction, so strip them here. requiredDataSchema = new StructType( requiredSchema.fields.filter { f => - val name = f.name.toLowerCase(Locale.ROOT) - !partitionColumnSet.contains(name) && !CDCSchemaContext.isCDCColumn(name) + !partitionColumnNames.contains(f.name) && !CDCSchemaContext.isCDCColumn(f.name) }) } diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java index b7f481b85c6..34b5baf7562 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2ScanBuilderTest.java @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.OptionalInt; import org.apache.spark.sql.catalyst.expressions.Expression; +import org.apache.spark.sql.catalyst.expressions.MetadataAttribute$; import org.apache.spark.sql.connector.read.Scan; import org.apache.spark.sql.connector.read.streaming.MicroBatchStream; import org.apache.spark.sql.delta.Snapshot; @@ -101,6 +102,43 @@ public void testBuild_returnsScanWithExpectedSchema(@TempDir File tempDir) { assertEquals(expectedSparkSchema, scan.readSchema()); } + @Test + public void testPruneColumns_preservesMetadataDifferingFromPartitionOnlyByCase( + @TempDir File tempDir) throws Exception { + String path = tempDir.getAbsolutePath(); + String tableName = "scan_builder_metadata_partition_case_test"; + spark.sql( + String.format( + "CREATE TABLE %s (_metadata STRING, __Metadata INT) " + + "USING delta PARTITIONED BY (__Metadata) LOCATION '%s'", + tableName, path)); + StructType dataSchema = new StructType().add("_metadata", DataTypes.StringType); + StructType partitionSchema = new StructType().add("__Metadata", DataTypes.IntegerType); + StructType tableSchema = dataSchema.add(partitionSchema.fields()[0]); + StructField metadataColumn = + DataTypes.createStructField( + "__metadata", + new StructType().add("file_path", DataTypes.StringType), + false, + MetadataAttribute$.MODULE$.metadata("_metadata")); + StructType expectedDataSchema = dataSchema.add(metadataColumn); + StructType requiredSchema = expectedDataSchema.add(partitionSchema.fields()[0]); + + // Names are already resolved before pruning, regardless of the current resolver setting. + for (String caseSensitive : new String[] {"true", "false"}) { + withSQLConf( + "spark.sql.caseSensitive", + caseSensitive, + () -> { + DeltaV2ScanBuilder builder = + newScanBuilder(tableName, path, dataSchema, partitionSchema, tableSchema); + builder.pruneColumns(requiredSchema); + + assertEquals(expectedDataSchema, getRequiredDataSchema(builder)); + }); + } + } + @Test public void testPruneColumns_filtersMixedCaseCDCColumn(@TempDir File tempDir) throws Exception { String path = tempDir.getAbsolutePath(); From 6e2494fd2a468c68c09184be9021bca824444650 Mon Sep 17 00:00:00 2001 From: Hao Sun Date: Tue, 17 Nov 2026 22:18:13 -0800 Subject: [PATCH 39/44] [Spark] Validate protocols while reading V2 streaming commits (#8219) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other ## Description V2 streaming reads commit JSON through LogStore. Validate each protocol action with the shared `Protocol.protocolRead` check before returning the commit's files or collecting metadata and protocol actions. This rejects an unsupported historical protocol even when the latest snapshot has a supported protocol. Pass the stream's Spark session and read snapshot to the action collectors. Add coverage for unsupported reader versions and reader features, supported writer-only features, lazy validation, and reader cleanup. Enable the existing historical-protocol streaming regression tests. ## How was this patch tested? - Four focused suites passed with Java 17 and Spark 4.2: **325 tests passed, 0 failures** (`StreamingHelperTest`, `DeltaV2MicroBatchStreamTest`, `MetadataEvolutionHandlerTest`, and `DeltaV2TableManagerImplSuite`). - `git diff --check` - Java formatting checks with Java 17 and Spark 4.2: ```sh ./build/sbt -java-home /usr/lib/jvm/java-17-openjdk-amd64 -DsparkVersion=4.2 \ 'sparkV2/javafmtCheckAll' ``` ## Does this PR introduce _any_ user-facing changes? On master, V2 streams now reject unsupported historical reader protocols with the standard Delta protocol-read errors before emitting files from that commit. Unknown writer-only features remain readable. No public API or table format changes. Signed-off-by: Hao Sun <86338940+HaoSun1993@users.noreply.github.com> --- .../DeltaV2SourceFastDropFeatureSuite.scala | 9 +- .../v2/read/MetadataEvolutionHandler.java | 17 ++- .../sql/delta/v2/utils/StreamingHelper.java | 33 ++++- .../v2/read/DeltaV2MicroBatchStream.scala | 9 +- .../v2/read/DeltaV2MicroBatchStreamTest.java | 111 +++++++++++++++ .../v2/read/MetadataEvolutionHandlerTest.java | 10 +- .../delta/v2/utils/StreamingHelperTest.java | 126 +++++++++++++++++- .../DeltaV2TableManagerImplSuite.scala | 8 +- 8 files changed, 288 insertions(+), 35 deletions(-) diff --git a/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceFastDropFeatureSuite.scala b/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceFastDropFeatureSuite.scala index cfe6d7e4300..ddd498bade2 100644 --- a/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceFastDropFeatureSuite.scala +++ b/spark-unified/src/test/scala/org/apache/spark/sql/delta/test/DeltaV2SourceFastDropFeatureSuite.scala @@ -32,7 +32,9 @@ class DeltaV2SourceFastDropFeatureSuite "Protocol check at startingVersion is skipped when config is disabled", "Protocol validations supress errors when snapshot cannot be reconstructed", "Protocol is checked when using startingVersion - useStartingTS: false.", - "Protocol is checked when using startingVersion - useStartingTS: true." + "Protocol is checked when using startingVersion - useStartingTS: true.", + "Protocol is checked when coming across an action with a protocol upgrade", + "Restart from checkpoint reads forward into an unsupported feature commit" ) override protected def shouldFailTests: Set[String] = Set( @@ -42,11 +44,6 @@ class DeltaV2SourceFastDropFeatureSuite // match. The feature is caught eagerly while building the snapshot at stream start. "Latest protocol is checked for unsupported features", - // Same missing translation, but the feature is only hit mid-stream: Kernel wraps its - // UnsupportedTableFeatureException in a RuntimeException while iterating commit actions, so the - // cause the assertion inspects carries no DELTA_UNSUPPORTED_FEATURES_FOR_READ error class. - "Protocol is checked when coming across an action with a protocol upgrade", - "Restart from checkpoint reads forward into an unsupported feature commit", // Builds its first stream while testUnsupportedReaderWriter is still at the latest version. // DSv1 gates that test-only feature on UNSUPPORTED_TESTING_FEATURES_ENABLED (off here) and diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandler.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandler.java index dac9f69f0e2..34a23e75393 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandler.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandler.java @@ -103,6 +103,7 @@ public class MetadataEvolutionHandler { private final Option metadataTrackingLog; // Read-time state captured at source initialization + private final SnapshotDescriptor readSnapshotAtSourceInit; private final Metadata readMetadataAtSourceInit; private final Protocol readProtocolAtSourceInit; private final String metadataPath; @@ -119,8 +120,7 @@ public MetadataEvolutionHandler( DeltaOptions options, DeltaStreamUtils.SchemaReadOptions schemaReadOptions, Option metadataTrackingLog, - Metadata readMetadataAtSourceInit, - Protocol readProtocolAtSourceInit, + SnapshotDescriptor readSnapshotAtSourceInit, String metadataPath) { this.spark = Objects.requireNonNull(spark); this.tableId = Objects.requireNonNull(tableId); @@ -130,8 +130,9 @@ public MetadataEvolutionHandler( this.options = Objects.requireNonNull(options); this.schemaReadOptions = Objects.requireNonNull(schemaReadOptions); this.metadataTrackingLog = Objects.requireNonNull(metadataTrackingLog); - this.readMetadataAtSourceInit = Objects.requireNonNull(readMetadataAtSourceInit); - this.readProtocolAtSourceInit = Objects.requireNonNull(readProtocolAtSourceInit); + this.readSnapshotAtSourceInit = Objects.requireNonNull(readSnapshotAtSourceInit); + this.readMetadataAtSourceInit = Objects.requireNonNull(readSnapshotAtSourceInit.metadata()); + this.readProtocolAtSourceInit = Objects.requireNonNull(readSnapshotAtSourceInit.protocol()); this.metadataPath = Objects.requireNonNull(metadataPath); this.persistedMetadataAtSourceInit = metadataTrackingLog.isDefined() @@ -391,7 +392,9 @@ private Map collectMetadataActions(long startVersion, long endVe Optional.of(endVersion), tableManager, originalStreamingQueryContext, - options.failOnDataLoss()); + options.failOnDataLoss(), + spark, + readSnapshotAtSourceInit); } /** Collect the protocol action at a specific version. Returns null if none. */ @@ -406,7 +409,9 @@ private Map collectProtocolActions(long startVersion, long endVe Optional.of(endVersion), tableManager, originalStreamingQueryContext, - options.failOnDataLoss()); + options.failOnDataLoss(), + spark, + readSnapshotAtSourceInit); } /** diff --git a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/StreamingHelper.java b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/StreamingHelper.java index 40f30a87c3a..0e1c534ff3f 100644 --- a/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/StreamingHelper.java +++ b/spark/v2/src/main/java/org/apache/spark/sql/delta/v2/utils/StreamingHelper.java @@ -31,11 +31,14 @@ import io.delta.kernel.internal.util.Preconditions; import java.util.*; import org.apache.spark.annotation.Experimental; +import org.apache.spark.sql.SparkSession; import org.apache.spark.sql.delta.DeltaSingleCommit; +import org.apache.spark.sql.delta.SnapshotDescriptor; import org.apache.spark.sql.delta.actions.Action; import org.apache.spark.sql.delta.actions.AddFile; import org.apache.spark.sql.delta.actions.Metadata; import org.apache.spark.sql.delta.actions.Protocol; +import org.apache.spark.sql.delta.actions.Protocol$; import org.apache.spark.sql.delta.storage.ClosableIterator; import org.apache.spark.sql.delta.v2.interop.DeltaV2QueryContext; import org.apache.spark.sql.delta.v2.kernel.KernelActionUtils$; @@ -215,13 +218,17 @@ public static Optional getCommitInfo(ColumnarBatch columnarBatch, in * @param originalStreamingQueryContext request-scoped catalog inputs used to load the commit * range * @param failOnDataLoss whether to fail when commits in the range are missing + * @param spark the stream's Spark session used to check protocol compatibility + * @param readSnapshot the stream's read-time snapshot used for protocol-read logging */ public static Map collectMetadataActions( long startVersion, Optional endVersionOpt, DeltaV2TableManager tableManager, DeltaV2QueryContext originalStreamingQueryContext, - boolean failOnDataLoss) { + boolean failOnDataLoss, + SparkSession spark, + SnapshotDescriptor readSnapshot) { return collectActions( startVersion, endVersionOpt, @@ -229,7 +236,9 @@ public static Map collectMetadataActions( originalStreamingQueryContext, failOnDataLoss, DeltaLogActionUtils.DeltaAction.METADATA, - Metadata.class); + Metadata.class, + spark, + readSnapshot); } /** @@ -250,13 +259,17 @@ public static Map collectMetadataActions( * @param originalStreamingQueryContext request-scoped catalog inputs used to load the commit * range * @param failOnDataLoss whether to fail when commits in the range are missing + * @param spark the stream's Spark session used to check protocol compatibility + * @param readSnapshot the stream's read-time snapshot used for protocol-read logging */ public static Map collectProtocolActions( long startVersion, Optional endVersionOpt, DeltaV2TableManager tableManager, DeltaV2QueryContext originalStreamingQueryContext, - boolean failOnDataLoss) { + boolean failOnDataLoss, + SparkSession spark, + SnapshotDescriptor readSnapshot) { return collectActions( startVersion, endVersionOpt, @@ -264,7 +277,9 @@ public static Map collectProtocolActions( originalStreamingQueryContext, failOnDataLoss, DeltaLogActionUtils.DeltaAction.PROTOCOL, - Protocol.class); + Protocol.class, + spark, + readSnapshot); } /** Walks the commit files and rejects commits with more than one matching action. */ @@ -275,7 +290,9 @@ private static Map collectActions( DeltaV2QueryContext originalStreamingQueryContext, boolean failOnDataLoss, DeltaLogActionUtils.DeltaAction actionType, - Class actionClass) { + Class actionClass, + SparkSession spark, + SnapshotDescriptor readSnapshot) { // LinkedHashMap to preserve insertion order Map versionToAction = new LinkedHashMap<>(); try (ClosableIterator commitsIter = @@ -291,6 +308,12 @@ private static Map collectActions( commit.getActionsIterator(/* maxInMemoryFileSizeBytes= */ 0L)) { while (actionsIter.hasNext()) { Action action = actionsIter.next(); + if (action instanceof Protocol) { + String tablePath = readSnapshot.dataPath().toString(); + // DeltaSingleCommit reads through LogStore without protocol validation, + // so validate protocol actions explicitly. + Protocol$.MODULE$.protocolRead(spark, (Protocol) action, tablePath, readSnapshot); + } if (actionClass.isInstance(action)) { T existing = versionToAction.putIfAbsent(version, actionClass.cast(action)); Preconditions.checkArgument( diff --git a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala index a26915200b5..7e361132a93 100644 --- a/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala +++ b/spark/v2/src/main/scala/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStream.scala @@ -265,8 +265,7 @@ private[read] class DeltaV2MicroBatchStream( options, schemaReadOptions, metadataTrackingLog, - readSnapshotDescriptor.metadata, - readSnapshotDescriptor.protocol, + readSnapshotDescriptor, metadataPath) override protected def trackingMetadataChange: Boolean = @@ -1260,6 +1259,8 @@ private[read] class DeltaV2MicroBatchStream( endOffsetOpt, verifyMetadataAction) } else if (action.isInstanceOf[Protocol]) { + Protocol.protocolRead( + spark, action.asInstanceOf[Protocol], tablePath, readSnapshotDescriptor) assert( protocolAction == null, s"Should not encounter two protocol actions in the same commit of version $version") @@ -1477,7 +1478,9 @@ private[read] class DeltaV2MicroBatchStream( Optional.of(Long.box(batchEndVersion.get)), tableManager, originalStreamingQueryContext, - options.failOnDataLoss) + options.failOnDataLoss, + spark, + readSnapshotDescriptor) .entrySet())) { val version: Long = entry.getKey() val metadata: Metadata = entry.getValue() diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStreamTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStreamTest.java index 5de4058a43a..4eeb45ce05d 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStreamTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/DeltaV2MicroBatchStreamTest.java @@ -16,9 +16,16 @@ package org.apache.spark.sql.delta.v2.read; import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import java.io.File; import java.nio.channels.ClosedByInterruptException; +import java.nio.file.Files; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Arrays; @@ -33,6 +40,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; @@ -45,6 +53,9 @@ import org.apache.spark.sql.connector.read.streaming.Offset; import org.apache.spark.sql.connector.read.streaming.ReadLimit; import org.apache.spark.sql.delta.*; +import org.apache.spark.sql.delta.actions.Action; +import org.apache.spark.sql.delta.actions.Protocol; +import org.apache.spark.sql.delta.actions.Protocol$; import org.apache.spark.sql.delta.amt.AMTTriggerMode; import org.apache.spark.sql.delta.files.DeltaSourceSnapshot; import org.apache.spark.sql.delta.sources.DeltaSQLConf; @@ -54,10 +65,12 @@ import org.apache.spark.sql.delta.sources.PersistedMetadata; import org.apache.spark.sql.delta.sources.ReadMaxBytes; import org.apache.spark.sql.delta.storage.ClosableIterator; +import org.apache.spark.sql.delta.storage.LogStore; import org.apache.spark.sql.delta.util.JsonUtils; import org.apache.spark.sql.delta.v2.DeltaV2TestBase; import org.apache.spark.sql.delta.v2.interop.DeltaV2QueryContext$; import org.apache.spark.sql.delta.v2.snapshot.PathBasedSnapshotManager; +import org.apache.spark.sql.delta.v2.tablemanager.DeltaV2TableManager; import org.apache.spark.sql.delta.v2.tablemanager.DeltaV2TableManagerCache$; import org.apache.spark.sql.delta.v2.utils.ScalaUtils; import org.apache.spark.sql.delta.v2.utils.SchemaUtils; @@ -68,6 +81,7 @@ import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import scala.Option; import scala.collection.JavaConverters; @@ -91,6 +105,103 @@ private DeltaOptions emptyDeltaOptions() { return new DeltaOptions(Map$.MODULE$.empty(), spark.sessionState().conf()); } + @ParameterizedTest + @CsvSource({"unsupportedVersion", "unsupportedReaderFeature", "writerOnlyFeature"}) + void fileChangesValidateProtocolsBeforeReturningFiles(String scenario, @TempDir File tempDir) + throws Exception { + String tablePath = tempDir.getAbsolutePath(); + createEmptyTestTable(tablePath, "stream_protocol_" + System.nanoTime()); + DeltaV2TableManager tableManager = + spy( + DeltaV2TableManagerCache$.MODULE$.forTable( + spark, tablePath, Collections.emptyMap(), Option.empty())); + Snapshot snapshot = tableManager.loadLatestSnapshot(DeltaV2QueryContext$.MODULE$.empty()); + String snapshotPath = snapshot.dataPath().toString(); + DeltaV2MicroBatchStream stream = + new DeltaV2MicroBatchStream( + tableManager, + snapshot, + spark.sessionState().newHadoopConf(), + spark, + emptyDeltaOptions(), + snapshotPath, + snapshot.schema(), + new StructType(), + new StructType(), + new StructType(), + new org.apache.spark.sql.sources.Filter[0], + Map$.MODULE$.empty(), + Option.empty(), + snapshotPath + "/_checkpoint", + DeltaV2QueryContext$.MODULE$.empty()); + Protocol protocol; + if (scenario.equals("unsupportedVersion")) { + protocol = Protocol$.MODULE$.apply(99, 7); + } else { + String readerFeatures = + scenario.equals("unsupportedReaderFeature") ? "[\"unknownFeature\"]" : "[]"; + protocol = + (Protocol) + Action.fromJson( + "{\"protocol\":{\"minReaderVersion\":3,\"minWriterVersion\":7,\"readerFeatures\":" + + readerFeatures + + ",\"writerFeatures\":[\"unknownFeature\"]}}"); + } + Files.writeString( + new File(tempDir, "_delta_log/00000000000000000001.json").toPath(), + "{\"add\":{\"path\":\"data.parquet\",\"partitionValues\":{},\"size\":1," + + "\"modificationTime\":0,\"dataChange\":true}}\n" + + protocol.json() + + "\n"); + // A readable latest snapshot ensures only the per-commit check can reject version 1. + Files.writeString( + new File(tempDir, "_delta_log/00000000000000000002.json").toPath(), + snapshot.protocol().json() + "\n"); + LogStore logStore = spy(tableManager.logStore()); + List> readers = new ArrayList<>(); + doAnswer( + invocation -> { + @SuppressWarnings("unchecked") + ClosableIterator reader = + spy((ClosableIterator) invocation.callRealMethod()); + readers.add(reader); + return reader; + }) + .when(logStore) + .readAsIterator(any(FileStatus.class), any(Configuration.class)); + doReturn(logStore).when(tableManager).logStore(); + + try { + try (ClosableIterator changes = + stream.getFileChanges(1L, DeltaSourceOffset.BASE_INDEX(), false, Optional.empty())) { + assertTrue(readers.isEmpty(), "Commit validation must wait for iteration"); + if (scenario.equals("unsupportedVersion")) { + InvalidProtocolVersionException error = + assertThrows(InvalidProtocolVersionException.class, changes::hasNext); + assertEquals(snapshotPath, error.tableNameOrPath()); + } else if (scenario.equals("unsupportedReaderFeature")) { + DeltaUnsupportedTableFeatureException error = + assertThrows(DeltaUnsupportedTableFeatureException.class, changes::hasNext); + assertEquals("DELTA_UNSUPPORTED_FEATURES_FOR_READ", error.getErrorClass()); + } else { + int files = 0; + while (changes.hasNext()) { + if (changes.next().hasFileAction()) { + files++; + } + } + assertEquals(1, files); + } + } + assertFalse(readers.isEmpty()); + for (ClosableIterator reader : readers) { + verify(reader, atLeastOnce()).close(); + } + } finally { + stream.stop(); + } + } + @Test public void testLatestOffset_throwsUnsupportedOperationException(@TempDir File tempDir) { DeltaV2MicroBatchStream microBatchStream = createTestStream(tempDir); diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandlerTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandlerTest.java index 891e1a11174..34a1484bc8f 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandlerTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/read/MetadataEvolutionHandlerTest.java @@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; import java.io.File; import java.util.*; @@ -123,6 +124,9 @@ private MetadataEvolutionHandler buildLightweightHandler( invocation -> { throw new UnsupportedOperationException("not expected in this test"); }); + SnapshotDescriptor readSnapshot = mock(SnapshotDescriptor.class); + when(readSnapshot.metadata()).thenReturn(DEFAULT_METADATA); + when(readSnapshot.protocol()).thenReturn(DEFAULT_PROTOCOL); return new MetadataEvolutionHandler( spark, "test-table-id", @@ -133,8 +137,7 @@ private MetadataEvolutionHandler buildLightweightHandler( emptyDeltaOptions(), readOptions, trackingLog, - DEFAULT_METADATA, - DEFAULT_PROTOCOL, + readSnapshot, "/tmp/fake-table/_delta_log/_streaming_metadata"); } @@ -192,8 +195,7 @@ private HandlerWithLog buildHandlerWithRealTable( emptyDeltaOptions(), schemaReadOptions(/* allowUnsafeColumnMappingRead= */ false), Option.apply(trackingLog), - tableMetadata, - tableProtocol, + snapshot, tablePath + "/_delta_log/_streaming_metadata"); return new HandlerWithLog(handler, trackingLog); diff --git a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/StreamingHelperTest.java b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/StreamingHelperTest.java index d8380210e73..e548cc68b5b 100644 --- a/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/StreamingHelperTest.java +++ b/spark/v2/src/test/java/org/apache/spark/sql/delta/v2/utils/StreamingHelperTest.java @@ -17,6 +17,7 @@ import static io.delta.kernel.internal.actions.AddFile.SCHEMA_WITHOUT_STATS; import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertSame; @@ -39,6 +40,7 @@ import io.delta.kernel.utils.CloseableIterator; import java.io.File; import java.io.IOException; +import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import java.util.Map; @@ -50,10 +52,15 @@ import org.apache.hadoop.fs.Path; import org.apache.spark.sql.delta.DeltaLog; import org.apache.spark.sql.delta.DeltaSingleCommit; +import org.apache.spark.sql.delta.DeltaUnsupportedTableFeatureException; +import org.apache.spark.sql.delta.InvalidProtocolVersionException; import org.apache.spark.sql.delta.Snapshot; +import org.apache.spark.sql.delta.SnapshotDescriptor; +import org.apache.spark.sql.delta.actions.Action; import org.apache.spark.sql.delta.actions.AddFile; import org.apache.spark.sql.delta.actions.Metadata; import org.apache.spark.sql.delta.actions.Protocol; +import org.apache.spark.sql.delta.actions.Protocol$; import org.apache.spark.sql.delta.storage.ClosableIterator; import org.apache.spark.sql.delta.storage.LogStore; import org.apache.spark.sql.delta.v2.DeltaV2TestBase; @@ -67,15 +74,18 @@ import org.apache.spark.sql.types.StructType; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.function.Executable; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.MethodSource; import scala.Option; public class StreamingHelperTest extends DeltaV2TestBase { private PathBasedSnapshotManager snapshotManager; + private final SnapshotDescriptor mockReadSnapshot = mock(SnapshotDescriptor.class); private final DeltaV2QueryContext queryContext = DeltaV2QueryContext$.MODULE$.empty(); @AfterEach @@ -243,7 +253,13 @@ public void testProtocolCollector_closesEmptyCommitIterator() throws IOException assertTrue( StreamingHelper.collectProtocolActions( - 7L, Optional.of(7L), mockTableManager(commits, true), queryContext, true) + 7L, + Optional.of(7L), + mockTableManager(commits, true), + queryContext, + true, + spark, + mockReadSnapshot) .isEmpty()); verify(commits).close(); @@ -267,7 +283,13 @@ public void testProtocolCollector_preservesIteratorReadFailureWhenClosureFails() RuntimeException.class, () -> StreamingHelper.collectProtocolActions( - 7L, Optional.of(7L), mockTableManager(commits, true), queryContext, true)); + 7L, + Optional.of(7L), + mockTableManager(commits, true), + queryContext, + true, + spark, + mockReadSnapshot)); assertEquals("Failed to process commits", error.getMessage()); assertSame(readFailure, error.getCause()); @@ -302,13 +324,79 @@ public void testProtocolCollector_closesFileIteratorWhenOpeningActionsFails() th Optional.of(7L), mockTableManager(commits, true, store, conf), queryContext, - true)); + true, + spark, + mockReadSnapshot)); assertEquals("Failed to process commits", error.getMessage()); assertSame(readFailure, error.getCause()); verify(commits).close(); } + @ParameterizedTest + @CsvSource({ + "metadata, unsupportedVersion", + "protocol, unsupportedVersion", + "metadata, unsupportedReaderFeature", + "protocol, unsupportedReaderFeature", + "metadata, writerOnlyFeature", + "protocol, writerOnlyFeature" + }) + void collectorsValidateHistoricalProtocols( + String actionType, String scenario, @TempDir File tempDir) throws Exception { + String tablePath = tempDir.getAbsolutePath(); + createEmptyTestTable(tablePath, "collector_protocol_" + System.nanoTime()); + DeltaV2TableManager manager = + DeltaV2TableManagerCache$.MODULE$.forTable( + spark, tablePath, Collections.emptyMap(), Option.empty()); + Snapshot snapshot = manager.loadLatestSnapshot(queryContext); + Protocol protocol; + if (scenario.equals("unsupportedVersion")) { + protocol = Protocol$.MODULE$.apply(99, 7); + } else { + String readerFeatures = + scenario.equals("unsupportedReaderFeature") ? "[\"unknownFeature\"]" : "[]"; + protocol = + (Protocol) + Action.fromJson( + "{\"protocol\":{\"minReaderVersion\":3,\"minWriterVersion\":7,\"readerFeatures\":" + + readerFeatures + + ",\"writerFeatures\":[\"unknownFeature\"]}}"); + } + Files.writeString( + new File(tempDir, "_delta_log/00000000000000000001.json").toPath(), protocol.json() + "\n"); + // Keep the latest snapshot readable: validation must inspect the historical commit. + Files.writeString( + new File(tempDir, "_delta_log/00000000000000000002.json").toPath(), + snapshot.protocol().json() + "\n"); + + Executable collect = + () -> { + if (actionType.equals("metadata")) { + Map result = + StreamingHelper.collectMetadataActions( + 1L, Optional.of(1L), manager, queryContext, true, spark, snapshot); + assertTrue(result.isEmpty()); + } else { + Map result = + StreamingHelper.collectProtocolActions( + 1L, Optional.of(1L), manager, queryContext, true, spark, snapshot); + assertEquals(protocol, result.get(1L)); + } + }; + if (scenario.equals("unsupportedVersion")) { + InvalidProtocolVersionException error = + assertThrows(InvalidProtocolVersionException.class, collect); + assertEquals(snapshot.dataPath().toString(), error.tableNameOrPath()); + } else if (scenario.equals("unsupportedReaderFeature")) { + DeltaUnsupportedTableFeatureException error = + assertThrows(DeltaUnsupportedTableFeatureException.class, collect); + assertEquals("DELTA_UNSUPPORTED_FEATURES_FOR_READ", error.getErrorClass()); + } else { + assertDoesNotThrow(collect); + } + } + // --------------------------------------------------------------------------- // collectMetadataActions // @@ -351,7 +439,13 @@ public void testCollectMetadataActions( Map result = StreamingHelper.collectMetadataActions( - startVersion, endVersionOpt, tableManager, queryContext, true); + startVersion, + endVersionOpt, + tableManager, + queryContext, + true, + spark, + tableManager.loadLatestSnapshot(queryContext)); assertArrayEquals(expectedVersions.stream().sorted().toArray(), result.keySet().toArray()); } @@ -368,7 +462,13 @@ public void testCollectMetadataActions_returnsCorrectMetadataPerVersion(@TempDir Map result = StreamingHelper.collectMetadataActions( - 0L, Optional.of(2L), tableManager, queryContext, true); + 0L, + Optional.of(2L), + tableManager, + queryContext, + true, + spark, + tableManager.loadLatestSnapshot(queryContext)); StructType expectedV0Schema = new StructType().add("id", DataTypes.IntegerType).add("name", DataTypes.StringType); @@ -425,7 +525,13 @@ public void testCollectProtocolActions( Map result = StreamingHelper.collectProtocolActions( - startVersion, endVersionOpt, tableManager, queryContext, true); + startVersion, + endVersionOpt, + tableManager, + queryContext, + true, + spark, + tableManager.loadLatestSnapshot(queryContext)); assertArrayEquals(expectedVersions.stream().sorted().toArray(), result.keySet().toArray()); } @@ -442,7 +548,13 @@ public void testCollectProtocolActions_returnsCorrectProtocolPerVersion(@TempDir Map result = StreamingHelper.collectProtocolActions( - 0L, Optional.of(2L), tableManager, queryContext, true); + 0L, + Optional.of(2L), + tableManager, + queryContext, + true, + spark, + tableManager.loadLatestSnapshot(queryContext)); // v0 default: reader=1, writer=2; v2 upgraded: reader=3, writer=7 assertEquals(1, result.get(0L).minReaderVersion()); diff --git a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImplSuite.scala b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImplSuite.scala index 0d4b77c5f1a..7b14db6385e 100644 --- a/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImplSuite.scala +++ b/spark/v2/src/test/scala/org/apache/spark/sql/delta/v2/tablemanager/DeltaV2TableManagerImplSuite.scala @@ -379,10 +379,10 @@ class DeltaV2TableManagerImplSuite val error = intercept[IllegalArgumentException] { if (actionName == "metaData") { StreamingHelper.collectMetadataActions( - 1L, Optional.of(Long.box(1L)), manager, queryContext, true) + 1L, Optional.of(Long.box(1L)), manager, queryContext, true, spark, snapshot) } else { StreamingHelper.collectProtocolActions( - 1L, Optional.of(Long.box(1L)), manager, queryContext, true) + 1L, Optional.of(Long.box(1L)), manager, queryContext, true, spark, snapshot) } } assert(error.getMessage === @@ -411,11 +411,11 @@ class DeltaV2TableManagerImplSuite forPathAndCatalogManagers(path) { (manager, catalogTableOpt) => val queryContext = DeltaV2QueryContext(catalogTableOpt) val metadataActions = StreamingHelper.collectMetadataActions( - 1L, Optional.of(Long.box(1L)), manager, queryContext, true) + 1L, Optional.of(Long.box(1L)), manager, queryContext, true, spark, snapshot) assert(metadataActions.size() === 1) assert(metadataActions.get(1L).schemaString === metadata.schemaString) val protocols = StreamingHelper.collectProtocolActions( - 1L, Optional.of(Long.box(1L)), manager, queryContext, true) + 1L, Optional.of(Long.box(1L)), manager, queryContext, true, spark, snapshot) assert(protocols.size() === 1) assert(protocols.get(1L) === snapshot.protocol) } From a3781e557ad8394352c93a0f0cbe41703656d4f5 Mon Sep 17 00:00:00 2001 From: Dhruv Arya Date: Tue, 17 Nov 2026 23:22:56 -0800 Subject: [PATCH 40/44] [Spark] Build the AMT content stats JSON from a typed stats struct (#8214) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description The stats JSON of AMT entries is now built from a single stats struct, assembled out of plain field accesses into the typed `content_stats` column, instead of rebuilding the nested shape path by path. Statistics are matched to Delta's stats schema by physical path, a matched statistic of a widened type is cast, and statistics the manifests do not persist read as null. The JSON itself is unchanged, including leaving out min/max groups that have no persisted values rather than writing `{}`. ## How was this patch tested? Existing AMT stats and state reconstruction suites, plus a new `AMTContentStatsSuite` test for a table where no column has persisted bounds. ## Does this PR introduce _any_ user-facing changes? No Co-authored-by: Murali Ramanujam --- .../spark/sql/delta/amt/AMTContentStats.scala | 159 ++++++++++-------- .../sql/delta/amt/AMTContentStatsSuite.scala | 24 +++ 2 files changed, 111 insertions(+), 72 deletions(-) diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTContentStats.scala b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTContentStats.scala index c792306400d..29b96f059d2 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTContentStats.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/amt/AMTContentStats.scala @@ -18,6 +18,7 @@ package org.apache.spark.sql.delta.amt import org.apache.spark.sql.delta.{DeltaColumnMapping, DeltaColumnMappingMode} import org.apache.spark.sql.delta.actions.{Metadata, Protocol} +import org.apache.spark.sql.delta.metering.DeltaLogging import org.apache.spark.sql.delta.stats.{DeltaStatistics, SkippingEligibleDataType, StatisticsCollection, StatsCollectionUtils} import org.apache.spark.sql.{Column, DataFrame, SparkSession} @@ -43,7 +44,7 @@ import org.apache.spark.sql.types.{BooleanType, ByteType, DataType, DateType, De * `upper_bound`. The remaining spec-optional statistics (`value_count`, `nan_value_count`, * `total_bytes`) are omitted. */ -private[amt] object AMTContentStats { +private[amt] object AMTContentStats extends DeltaLogging { /** Names of the [[AMTSingleAction]] fields this object shapes. */ private val CONTENT_STATS_FIELD = "content_stats" @@ -94,8 +95,6 @@ private[amt] object AMTContentStats { name: String, path: Seq[String], boundType: Option[DataType]) { - def hasBounds: Boolean = boundType.isDefined - /** * The sub-struct's field name in the persisted schema: the logical name with the (unique) * field id attached. Iceberg resolves content_stats entries by field id and treats the name as @@ -311,30 +310,97 @@ private[amt] object AMTContentStats { /** The persisted `content_stats` of an entry row as the JSON that [[forRead]] decodes it to. */ private def statsJson(spark: SparkSession, metadata: Metadata, protocol: Protocol): Column = { val stats = statisticsCollection(spark, metadata, protocol) - val columns = statsColumns(stats.statCollectionPhysicalSchema) - if (columns.isEmpty) { + if (statsColumns(stats.statCollectionPhysicalSchema).isEmpty) { // No per-column stats were persisted (`content_stats` was dropped from the schema); the // encoder decodes `None` and `toStatsJson` supplies the record count and `tightBounds`. lit(null).cast(StringType) } else { - val typedStats = col(CONTENT_STATS_FIELD) + // Delta's stats schema of the manifests' own metadata, so that every persisted statistic is + // matched; `to_json` leaves out the null ones, as Delta writes no stats it does not have. + val encoded = to_json(parsedStats(stats, stats.statsSchema, omitMissing = true)) + when(col(CONTENT_STATS_FIELD).isNull, lit(null).cast(StringType)).otherwise(encoded) + } + } + + /** + * The persisted stats of an entry row as Delta's parsed stats struct of type `statsSchema`, built + * out of plain field accesses into the typed `content_stats` struct. + * + * Statistics are matched by their physical path, so `statsSchema` may come from newer metadata + * than `stats` describes: statistics `content_stats` lacks, or that AMT does not persist (e.g. + * collation statistics), are null. A matched statistic of another type is cast: with column + * mapping in `id` mode, a column keeps its physical path only through a type widening, and Delta + * only allows widenings that up-cast. `numRecords` is the entry's `record_count` and + * `tightBounds` is [[tightBounds]], both set even when the entry has no `content_stats`. + * + * @param stats the stats the manifests were written with + * @param omitMissing whether a struct of statistics none of which `content_stats` persists, e.g. + * the `minValues` of columns AMT keeps no bounds for, is null rather than a + * struct of nulls, so that `to_json` leaves it out + */ + private def parsedStats( + stats: StatisticsCollection, + statsSchema: StructType, + omitMissing: Boolean): Column = { + val columns = statsColumns(stats.statCollectionPhysicalSchema) + // With no per-column stats, `content_stats` is dropped from the persisted schema. + val typedStatsOpt = if (columns.isEmpty) None else Some(col(CONTENT_STATS_FIELD)) + val columnByPath = columns.map(column => column.path -> column).toMap + + // The persisted `statName` of the column at `path` as a `dataType`, or None if AMT keeps none + // for it. Each column's stats are a sub-struct of `content_stats` keyed by its `fieldName`. + def persistedStat(statName: String, path: Seq[String], dataType: DataType): Option[Column] = + for { + typedStats <- typedStatsOpt + column <- columnByPath.get(path) + statType <- if (statName == NULL_VALUE_COUNT) Some(LongType) else column.boundType + } yield { + val stat = typedStats.getField(column.fieldName).getField(statName) + if (statType == dataType) stat else stat.cast(dataType) + } - // Rebuild the nested minValues/maxValues/nullCount shape from each column's recorded path, - // then serialize it back to the JSON string Delta expects. minValues/maxValues cover only the - // columns that carry bounds, matching the sub-schemas Delta itself builds. - val bounded = columns.filter(_.hasBounds) - val statsFields = - bounded.headOption.toSeq.flatMap { _ => - Seq( - nestByPath(bounded, statOf(typedStats, _, LOWER_BOUND)).as(DeltaStatistics.MIN), - nestByPath(bounded, statOf(typedStats, _, UPPER_BOUND)).as(DeltaStatistics.MAX)) - } ++ columns.headOption.toSeq.map { _ => - nestByPath(columns, statOf(typedStats, _, NULL_VALUE_COUNT)) - .as(DeltaStatistics.NULL_COUNT) - } :+ tightBounds - val encoded = to_json(struct(numRecords +: statsFields: _*)) - when(typedStats.isNull, lit(null).cast(StringType)).otherwise(encoded) + // The `statName` of every column of `schema`, nested like `schema`, or None if `omitMissing` + // and no column has a persisted value. + def perColumnStats(statName: String, schema: StructType, prefix: Seq[String]) + : Option[Column] = { + val values = schema.fields.toIndexedSeq.map { field => + val path = prefix :+ field.name + field -> (field.dataType match { + case nested: StructType if !columnByPath.contains(path) => + perColumnStats(statName, nested, path) + case dataType => persistedStat(statName, path, dataType) + }) + } + if (omitMissing && values.forall { case (_, value) => value.isEmpty }) { + None + } else { + Some(struct(values.map { case (field, value) => + value.getOrElse(lit(null).cast(field.dataType)).as(field.name) + }: _*)) + } } + + struct(statsSchema.fields.toIndexedSeq.map { field => + val value = (field.name, field.dataType) match { + case (DeltaStatistics.NUM_RECORDS, dataType) => col("record_count").cast(dataType) + case (DeltaStatistics.MIN, schema: StructType) => + perColumnStats(LOWER_BOUND, schema, Nil).getOrElse(lit(null).cast(schema)) + case (DeltaStatistics.MAX, schema: StructType) => + perColumnStats(UPPER_BOUND, schema, Nil).getOrElse(lit(null).cast(schema)) + case (DeltaStatistics.NULL_COUNT, schema: StructType) => + perColumnStats(NULL_VALUE_COUNT, schema, Nil).getOrElse(lit(null).cast(schema)) + case (DeltaStatistics.TIGHT_BOUNDS, dataType) => tightBounds.cast(dataType) + case (name, dataType) => + // Fails tests, so that a statistic Delta adds gets mapped here; null in production. + deltaAssert( + check = false, + name = "amt.unmappedStatistic", + msg = "The Delta statistic " + name + " is not mapped to AMT content stats; map it " + + "in AMTContentStats.parsedStats.") + lit(null).cast(dataType) + } + value.as(field.name) + }: _*) } /** @@ -354,57 +420,6 @@ private[amt] object AMTContentStats { private def statPath(parsed: Column, statName: String, path: Seq[String]): Column = path.foldLeft(parsed.getField(statName))((column, name) => column.getField(name)) - /** - * Reads one statistic out of a column's typed, flat `content_stats` sub-struct (used on read) -- - * the inverse shape of [[statPath]]. The sub-struct is keyed by the column's unique `fieldName`. - * - * Example: statOf(typed, column(fieldName="d_nested_inner_4"), "lower_bound") reads the - * `lower_bound` of the sub-struct field named "d_nested_inner_4". - */ - private def statOf(typed: Column, column: StatsColumn, statName: String): Column = - typed.getField(column.fieldName).getField(statName) - - /** - * Rebuilds Delta's nested stats shape from the flat columns, grouping by each column's recorded - * path so a struct column's per-field statistics land back under that struct. - * - * Example -- rebuilding `minValues` from the three bounded columns below, where `value` reads - * each column's `lower_bound` out of the typed `content_stats` sub-struct (e.g. value of id 1 - * = typed.`1`.lower_bound): - * - * StatsColumn(1, ["col-1"]) - * StatsColumn(2, ["col-2"]) - * StatsColumn(4, ["col-3","col-4"]) - * - * Group by the first path segment -> col-1, col-2, col-3. col-1 and col-2 have a length-1 path so - * they take their value directly; col-3 has no length-1 entry, so it recurses on the remaining - * path ["col-4"] and builds a sub-struct. The result is: - * - * struct( - * "col-1" -> typed.`1`.lower_bound, - * "col-2" -> typed.`2`.lower_bound, - * "col-3" -> struct("col-4" -> typed.`4`.lower_bound)) - * - * which `to_json`s to {"col-1":.., "col-2":.., "col-3":{"col-4":..}} -- the physical-keyed, - * nested shape Delta writes minValues/maxValues/nullCount in, with col-4 back under col-3. - */ - private def nestByPath(columns: Seq[StatsColumn], value: StatsColumn => Column): Column = { - def build(entries: Seq[(Seq[String], StatsColumn)]): Column = { - val fields = entries - .groupBy(_._1.head) - .toSeq - .sortBy { case (_, group) => group.map(_._2.fieldId).min } - .map { case (name, group) => - group.find(_._1.length == 1) match { - case Some((_, column)) => value(column).as(name) - case None => build(group.map { case (path, column) => (path.tail, column) }).as(name) - } - } - struct(fields: _*) - } - build(columns.map(column => (column.path, column))) - } - private def replaceContentStats(df: DataFrame, contentStats: Column): DataFrame = df.select(df.columns.map { name => if (name == CONTENT_STATS_FIELD) contentStats.as(name) else col(name) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala index 2249398e2fb..c8343d8f626 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTContentStatsSuite.scala @@ -356,6 +356,30 @@ class AMTContentStatsSuite extends AMTCheckpointTestBase { } } + test("forRead leaves out minValues and maxValues when no column has bounds") { + // Delta's stats schema has min/max for these columns, but AMT persists no bounds for them, so + // the groups (here, also the nested struct's) must be left out rather than written as {}. + val metadata = metadataWithColumnIds( + new StructType() + .add("ts", TimestampType) + .add("nested", new StructType().add("inner_ts", TimestampType))) + val ts = DeltaColumnMapping.getPhysicalName(metadata.dataSchema("ts")) + val nestedField = metadata.dataSchema("nested") + val nested = DeltaColumnMapping.getPhysicalName(nestedField) + val innerTs = DeltaColumnMapping.getPhysicalName( + nestedField.dataType.asInstanceOf[StructType]("inner_ts")) + val nullCount = s"""{"$ts":1,"$nested":{"$innerTs":2}}""" + val bounds = s"""{"$ts":"2020-01-01T00:00:00.000Z","$nested":""" + + s"""{"$innerTs":"2020-01-01T00:00:00.000Z"}}""" + val persisted = writeStats( + s"""{"numRecords":10,"minValues":$bounds,"maxValues":$bounds,""" + + s""""nullCount":$nullCount,"tightBounds":true}""", + metadata, amtProtocol) + assert(JsonUtils.mapper.readTree(readStats(persisted, metadata, amtProtocol)) == + JsonUtils.mapper.readTree( + s"""{"numRecords":10,"nullCount":$nullCount,"tightBounds":false}""")) + } + test("content stats adapter round-trips a table that collects no statistics") { // numIndexedCols = 0 means Delta collects only numRecords, so there are no per-column stats and // `content_stats` is dropped from the schema (an empty struct is not Parquet-writable). From a74e849f50cd066d6f250887a115b1aabc27095c Mon Sep 17 00:00:00 2001 From: Jiayuan Chen Date: Wed, 18 Nov 2026 03:07:39 -0800 Subject: [PATCH 41/44] [Spark] Test that a re-added column does not take a dropped column's AMT stats (#8223) #### Which Delta project/connector is this regarding? - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description Add an `AMTFieldSpecSuite` test that drops a column and re-adds a column with the same name, which gets a new column mapping id. In each AMT checkpoint scenario, it checks that: - the tree written before the drop holds min/max/null-count stats for the dropped column, - the files written before the drop carry no stats for the re-added column, with Parquet field-id reads on and off, and the new file keeps its stats, - an `IS NULL` filter on the re-added column returns every row of the old files. ## How was this patch tested? Test-only change. ## Does this PR introduce _any_ user-facing changes? No. --- .../sql/delta/amt/AMTFieldSpecSuite.scala | 73 ++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTFieldSpecSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTFieldSpecSuite.scala index 666e16ef4eb..de8e986b062 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTFieldSpecSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTFieldSpecSuite.scala @@ -24,6 +24,7 @@ import org.apache.spark.sql.delta.DeltaColumnMapping import org.apache.spark.sql.delta.DeltaLog import org.apache.spark.sql.delta.actions.{ContentRoot, Metadata} import org.apache.spark.sql.delta.util.JsonUtils +import com.fasterxml.jackson.databind.JsonNode import org.apache.hadoop.conf.Configuration import org.apache.hadoop.fs.Path import org.apache.parquet.format.converter.ParquetMetadataConverter @@ -31,7 +32,7 @@ import org.apache.parquet.hadoop.ParquetFileReader import org.apache.parquet.schema.{GroupType, LogicalTypeAnnotation, MessageType, PrimitiveType, Type} import org.apache.spark.SparkRuntimeException -import org.apache.spark.sql.DataFrame +import org.apache.spark.sql.{DataFrame, Row} import org.apache.spark.sql.execution.datasources.parquet.ParquetUtils import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.types.{StructField, StructType} @@ -402,6 +403,76 @@ class AMTFieldSpecSuite extends AMTCheckpointTestBase { s"the renamed partition value should read null without field-id read: $degraded") } + testAcrossAMTCheckpointScenarios( + "content stats of a dropped column do not apply to a re-added column of the same name", + "amt_drop_readd", + sqlConfs = leafPackingConfs, + tableSchema = "id INT, c INT")( + setup = name => { + appendRowsAsSeparateFiles( + name, + numFiles = leafPackedFiles, + columnExprs = Seq("CAST(id AS INT)", "CAST(100 + id AS INT)")) + commitCheckpoint(deltaLogForName(name), incremental = false) + sql(s"ALTER TABLE $name DROP COLUMN c") + sql(s"ALTER TABLE $name ADD COLUMN c INT") + }, + inlineCheckpointTriggerActionsOrSQL = Some(name => Right( + s"INSERT INTO $name VALUES ($leafPackedFiles, 5)"))) { context => + val deltaLog = context.postCheckpointSnapshot.deltaLog + // Reconstruct the live AddFiles of `provider` under `meta`, parsing the stats of each file. + def reconstructStats(provider: AMTCheckpointProvider, meta: Metadata): Seq[JsonNode] = + reconstructAddFiles(provider, deltaLog, meta) + .select("add.stats").collect().toSeq + .map(row => JsonUtils.mapper.readTree( + Option(row.getString(0)).getOrElse(fail("a live file has no stats")))) + + // The tree written before the drop holds the dropped `c`'s stats in its leaves. + val preDropTree = amtProvider(context.postSetupSnapshot).getOrElse( + fail("expected the tree written before the drop")) + assertLeafCount(preDropTree.leaves) + val preDropMetadata = preDropTree.checkpointAction.metaData + val droppedPhysicalName = DeltaColumnMapping.getPhysicalName(preDropMetadata.schema("c")) + val preDropStats = reconstructStats(preDropTree, preDropMetadata) + assert(preDropStats.size == leafPackedFiles, s"expected $leafPackedFiles files: $preDropStats") + preDropStats.foreach { stats => + Seq("minValues", "maxValues", "nullCount").foreach { statName => + assert(stats.path(statName).has(droppedPhysicalName), + s"a file written before the drop has no $statName for the dropped `c`: $stats") + } + } + + val metadata = context.postCheckpointSnapshot.metadata + val droppedColumnId = DeltaColumnMapping.getColumnId(preDropMetadata.schema("c")) + assert(DeltaColumnMapping.getColumnId(metadata.schema("c")) != droppedColumnId) + val idPhysicalName = DeltaColumnMapping.getPhysicalName(metadata.schema("id")) + val cPhysicalName = DeltaColumnMapping.getPhysicalName(metadata.schema("c")) + + BOOLEAN_DOMAIN.foreach { fieldIdRead => + withSQLConf(SQLConf.PARQUET_FIELD_ID_READ_ENABLED.key -> fieldIdRead.toString) { + val fileStats = reconstructStats(context.provider, metadata) + val (newFileStats, oldFileStats) = fileStats.partition( + _.path("minValues").path(idPhysicalName).asInt() == leafPackedFiles) + assert(oldFileStats.size == leafPackedFiles && newFileStats.size == 1, + s"expected $leafPackedFiles old files and 1 new file: $fileStats") + oldFileStats.foreach { stats => + Seq("minValues", "maxValues", "nullCount").foreach { statName => + assert(!stats.path(statName).has(cPhysicalName), + s"an old file has $statName for the re-added `c` (fieldIdRead=$fieldIdRead): $stats") + } + } + assert(newFileStats.head.path("minValues").path(cPhysicalName).asInt() == 5, + s"the new file lost its `c` stats (fieldIdRead=$fieldIdRead): $newFileStats") + } + } + + // The re-added `c` is null in every old file, so data skipping must keep them all. + checkAnswer( + spark.table(context.tableName).where("c IS NULL").select("id"), + (0 until leafPackedFiles).map(Row(_))) + checkAnswer(spark.table(context.tableName).where("c = 5"), Row(leafPackedFiles, 5)) + } + testAcrossAMTCheckpointScenarios( "manifest writes timestamps as int64 TIMESTAMP_MICROS, not INT96", "amt_ts", From fa86aa5b61f19bf985decd0d9540d99748e3216f Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Wed, 18 Nov 2026 15:52:26 +0100 Subject: [PATCH 42/44] [Spark] Consolidate AMT back-reference tests (#8195) #### Which Delta project/connector is this regarding? - [x] Spark ## Description Sharing checkpointed setup across compatible AMT back-reference checks avoids repeated fixture construction while keeping clone targets isolated. | Pre-export source-suite workload and timed scope | Before | After | Benefit | | --- | ---: | ---: | ---: | | Complete five-shard `AMTBackReferenceSuite`, mean command wall time | 463.26 s | 430.72 s | 7.0% lower | Two alternating pre-export runs per source revision compared `a3ac97a194a85815a3ec9572939e882e4f053aa0` with `19a2cde8bfd72b4087188595489f482eed6a2455`, including startup, fixtures and teardown. Later source cleanups and this public head were not timed. CPU and CI savings are unmeasured. ## How was this patch tested? The 75-case pre-export source suite retains all original obligations across three checkpoint modes, with deliberate back-reference faults and alternate-order checks. Rejected transactions preserve table version and live references. The generated patch was applied to public master. The cleanup preserves the shared helper assertions and was checked in all three Runtime checkpoint modes. The transformed public suite has not been run locally. All 53 public CI checks pass on `a9d933322ec58ebc3d3a39fa8dc397df711af3ae`. ## Does this PR introduce any user-facing changes? No.

Agent attribution Agent: Costly Tests - Orchestrator | Session: 01a1e505-448e-7d81-b315-7ef768b0399c Agent: Costly Tests - SQL | Session: 01a1e523-4d27-73b1-b47b-a8e576721388
--------- Signed-off-by: Cyrus Najmabadi Signed-off-by: cyrus.najmabadi Co-authored-by: Cyrus Najmabadi --- .../sql/delta/amt/AMTBackReferenceSuite.scala | 393 ++++++++---------- 1 file changed, 179 insertions(+), 214 deletions(-) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTBackReferenceSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTBackReferenceSuite.scala index 1f7676ba95c..f8754ad82ee 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTBackReferenceSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTBackReferenceSuite.scala @@ -89,8 +89,11 @@ class AMTBackReferenceSuite } /** The back references stamped on every live file reconstructed from an AMT checkpoint. */ - private def stampedBackRefs(snapshot: Snapshot): Map[String, Option[BackReference]] = { - val byPath = liveAddFiles(snapshot).map(add => add.path -> add.backReference).toMap + private def stampedBackRefs(snapshot: Snapshot): Map[String, Option[BackReference]] = + stampedBackRefs(liveAddFiles(snapshot)) + + private def stampedBackRefs(adds: Seq[AddFile]): Map[String, Option[BackReference]] = { + val byPath = adds.map(add => add.path -> add.backReference).toMap assert(byPath.nonEmpty && byPath.values.forall(_.isDefined), "all emitted files must be reconstructed from the leaves with a back reference.") byPath @@ -131,10 +134,13 @@ class AMTBackReferenceSuite } testAcrossAMTCheckpointScenarios( - "reconstructed AddFiles are stamped with a back reference matching the leaf layout", + "leaf back references match their positions and propagate through file mutations", "amt_back_ref_stamped", sqlConfs = leafPackingConfs)( - setup = name => appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 1), + setup = name => { + Seq(1, 2).toDF("id").coalesce(1).write.mode("append").insertInto(name) + appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 2, startId = 100) + }, inlineCheckpointTriggerActionsOrSQL = Some(name => Right( s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { context => val groundTruth = leafLocationByBackRef(context.postCheckpointSnapshot) @@ -154,6 +160,83 @@ class AMTBackReferenceSuite assert(groundTruth.get((br.manifest, br.pos.toLong)).contains(add.path), s"Back-ref (${br.manifest}, ${br.pos}) must resolve to the entry for ${add.path}.") } + + // A log-only file can be added and removed without changing the checkpointed files. + locally { + val stampedPaths = adds.map(_.path).toSet + + // This file is added off a checkpoint boundary, so it never enters a leaf. + sql(s"INSERT INTO ${context.tableName} VALUES ($leafPackedFiles)") + val deltaLog = context.postCheckpointSnapshot.deltaLog + val newFile = deltaLog.update().allFiles.collect() + .find(add => !stampedPaths.contains(add.path)) + .getOrElse(fail("expected a newly added, non-leaf file.")) + assert(newFile.backReference.isEmpty, + "A file added after the emit (not yet in a leaf) must not carry a back reference.") + + // Removing the unstamped file must produce an unstamped tombstone. + val vBefore = deltaLog.update().version + sql(s"DELETE FROM ${context.tableName} WHERE id = $leafPackedFiles") + val remove = actionsAfter(deltaLog, vBefore).collect { case r: RemoveFile => r } + .find(_.path == newFile.path) + .getOrElse(fail(s"expected a RemoveFile for the post-emit file ${newFile.path}.")) + assert(remove.backReference.isEmpty, + "Removing a file that never entered a leaf must produce an empty back reference.") + } + + val backRefByPath = stampedBackRefs(adds) + val twoRowFile = adds.find(_.numPhysicalRecords.contains(2L)) + .getOrElse(fail("expected the two-row file to be reconstructed from the leaves.")) + + // removeRows does not commit; the command below still reads the original file. + locally { + // Mark row 0 deleted via a persistent DV, exercising the removeRows narrow waist. + val dv = writeDV(context.postCheckpointSnapshot.deltaLog, RoaringBitmapArray(0L)) + val (supersedingAdd, removeFile) = + twoRowFile.removeRows( + deletionVector = dv, updateStats = false) + + assert(supersedingAdd.backReference.isEmpty, + "The superseding AddFile (new DV) is a net-new root entry and must carry " + + "no back reference.") + assert(removeFile.backReference == twoRowFile.backReference, + "The paired RemoveFile must inherit the source file's back reference.") + } + + withSQLConf(DeltaSQLConf.DELETE_USE_PERSISTENT_DELETION_VECTORS.key -> "true") { + // Deleting one of the two rows emits a superseding AddFile and paired RemoveFile. + val deltaLog = context.postCheckpointSnapshot.deltaLog + sql(s"DELETE FROM ${context.tableName} WHERE id = 1") + val actions = actionsAfter(deltaLog, context.manifestCommitVersion) + val supersedingAdd = actions.collectFirst { + case a: AddFile if a.path == twoRowFile.path => a + }.getOrElse(fail("expected a superseding AddFile (DV update) for the two-row file.")) + val removed = actions.collectFirst { + case r: RemoveFile if r.path == twoRowFile.path => r + }.getOrElse(fail("expected a paired RemoveFile for the two-row file.")) + assert(supersedingAdd.deletionVector != null, "the superseding AddFile must carry the DV.") + assert(supersedingAdd.backReference.isEmpty, + "the superseding AddFile must not claim the source file's leaf position.") + assert(removed.backReference == backRefByPath(twoRowFile.path), + "the paired RemoveFile must inherit the source file's back reference.") + } + + // A fresh version isolates this removal from the earlier DV and log-only removals. + locally { + val deltaLog = context.postCheckpointSnapshot.deltaLog + val vBefore = deltaLog.update().version + sql(s"DELETE FROM ${context.tableName} WHERE id = 100") + + val removes = actionsAfter(deltaLog, vBefore) + .collect { case r: RemoveFile => r } + assert(removes.size == 1, "The single-row file for id=100 must be removed whole.") + val remove = removes.head + val expected = backRefByPath.getOrElse(remove.path, + fail(s"Removed file ${remove.path} was not among the leaf-reconstructed files.")) + assert(expected.isDefined, "The removed file must have carried a back reference.") + assert(remove.backReference == expected, + s"RemoveFile back-ref ${remove.backReference} must equal the source AddFile's $expected.") + } } testAcrossAMTCheckpointScenarios( @@ -186,123 +269,6 @@ class AMTBackReferenceSuite s"but was ${removes.head.backReference}.") } - testAcrossAMTCheckpointScenarios( - "DELETE emits a RemoveFile carrying the removed file's back reference", - "amt_back_ref_delete", - sqlConfs = leafPackingConfs)( - setup = name => appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 1), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { context => - val backRefByPath = stampedBackRefs(context.postCheckpointSnapshot) - val deltaLog = context.postCheckpointSnapshot.deltaLog - sql(s"DELETE FROM ${context.tableName} WHERE id = 1") - - val removes = actionsAfter(deltaLog, context.manifestCommitVersion) - .collect { case r: RemoveFile => r } - assert(removes.size == 1, "The single-row file for id=1 must be removed whole.") - val remove = removes.head - val expected = backRefByPath.getOrElse(remove.path, - fail(s"Removed file ${remove.path} was not among the leaf-reconstructed files.")) - assert(expected.isDefined, "The removed file must have carried a back reference.") - assert(remove.backReference == expected, - s"RemoveFile back-ref ${remove.backReference} must equal the source AddFile's $expected.") - } - - testAcrossAMTCheckpointScenarios( - "a file added after the emit and removed before the next emit has no back reference", - "amt_back_ref_post_emit", - sqlConfs = leafPackingConfs)( - setup = name => appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 1), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { context => - val stamped = liveAddFiles(context.postCheckpointSnapshot) - val stampedPaths = stamped.map(_.path).toSet - assert(stamped.size == leafPackedFiles && stamped.forall(_.backReference.isDefined), - s"all $leafPackedFiles emitted files must be stamped from the leaves.") - - // This file is added off a checkpoint boundary, so it never enters a leaf. - sql(s"INSERT INTO ${context.tableName} VALUES ($leafPackedFiles)") - val deltaLog = context.postCheckpointSnapshot.deltaLog - val newFile = deltaLog.update().allFiles.collect() - .find(add => !stampedPaths.contains(add.path)) - .getOrElse(fail("expected a newly added, non-leaf file.")) - assert(newFile.backReference.isEmpty, - "A file added after the emit (not yet in a leaf) must not carry a back reference.") - - // Removing the unstamped file must produce an unstamped tombstone. - val vBefore = deltaLog.update().version - sql(s"DELETE FROM ${context.tableName} WHERE id = $leafPackedFiles") - val remove = actionsAfter(deltaLog, vBefore).collect { case r: RemoveFile => r } - .find(_.path == newFile.path) - .getOrElse(fail(s"expected a RemoveFile for the post-emit file ${newFile.path}.")) - assert(remove.backReference.isEmpty, - "Removing a file that never entered a leaf must produce an empty back reference.") - } - - testAcrossAMTCheckpointScenarios( - "removeRows keeps the back reference on the RemoveFile and drops it from the AddFile", - "amt_back_ref_remove_rows", - sqlConfs = leafPackingConfs)( - setup = name => { - // A single file holding two rows. - Seq(1, 2).toDF("id").coalesce(1).write.mode("append").insertInto(name) - appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 2, startId = 100) - }, - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { - context => - val twoRowFile = liveAddFiles(context.postCheckpointSnapshot) - .find(_.numPhysicalRecords.contains(2L)) - .getOrElse(fail("expected the two-row file to be reconstructed from the leaves.")) - assert(twoRowFile.backReference.isDefined) - - // Mark row 0 deleted via a persistent DV, exercising the removeRows narrow waist. - val dv = writeDV(context.postCheckpointSnapshot.deltaLog, RoaringBitmapArray(0L)) - val (supersedingAdd, removeFile) = - twoRowFile.removeRows( - deletionVector = dv, updateStats = false) - - assert(supersedingAdd.backReference.isEmpty, - "The superseding AddFile (new DV) is a net-new root entry and must carry no back reference.") - assert(removeFile.backReference == twoRowFile.backReference, - "The paired RemoveFile must inherit the source file's back reference.") - } - - testAcrossAMTCheckpointScenarios( - "DELETE via a persistent DV (removeRows) propagates through a real command", - "amt_back_ref_dv_delete", - sqlConfs = leafPackingConfs)( - setup = name => { - // A single file holding two rows. - Seq(1, 2).toDF("id").coalesce(1).write.mode("append").insertInto(name) - appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 2, startId = 100) - }, - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { - context => - val backRefByPath = - liveAddFiles(context.postCheckpointSnapshot).map(add => add.path -> add.backReference).toMap - val twoRowPath = liveAddFiles(context.postCheckpointSnapshot) - .find(_.numPhysicalRecords.contains(2L)) - .getOrElse(fail("expected the two-row file to be reconstructed from the leaves.")).path - - // Deleting one of the two rows emits a superseding AddFile and paired RemoveFile. - val deltaLog = context.postCheckpointSnapshot.deltaLog - sql(s"DELETE FROM ${context.tableName} WHERE id = 1") - val actions = actionsAfter(deltaLog, context.manifestCommitVersion) - val supersedingAdd = actions.collectFirst { - case a: AddFile if a.path == twoRowPath => a - }.getOrElse(fail("expected a superseding AddFile (DV update) for the two-row file.")) - val removed = actions.collectFirst { - case r: RemoveFile if r.path == twoRowPath => r - }.getOrElse(fail("expected a paired RemoveFile for the two-row file.")) - assert(supersedingAdd.deletionVector != null, "the superseding AddFile must carry the DV.") - assert(supersedingAdd.backReference.isEmpty, - "the superseding AddFile must not claim the source file's leaf position.") - assert(removed.backReference == backRefByPath(twoRowPath), - "the paired RemoveFile must inherit the source file's back reference.") - } - /** * Helper for commands that rewrite or remove leaf-derived files: emit two stamped files, * run the command, then assert every resulting tombstone / superseding AddFile inherited @@ -397,57 +363,57 @@ class AMTBackReferenceSuite log.startTransaction().commit(actions, DeltaOperations.ManualUpdate) } - test("commit accepts a RemoveFile carrying the correct back reference") { - withTable("amt_commit_ok") { - val adds = emitStampedAddFiles("amt_commit_ok") - // Tombstoning a leaf-derived file keeps its (correct) back reference: the commit must pass. - commitActions("amt_commit_ok", Seq(adds.head.removeWithTimestamp())) - } - } - - test("commit accepts a fresh file that carries no back reference") { - withTable("amt_commit_fresh") { - val adds = emitStampedAddFiles("amt_commit_fresh") - // A brand-new file not present in the tree legitimately carries no back reference. - val fresh = adds.head.copy(path = "brand-new-file.parquet", backReference = None) - commitActions("amt_commit_fresh", Seq(fresh)) - } - } + test("commit validates back references and rejects invalid actions atomically") { + withTable("amt_commit_validation") { + val name = "amt_commit_validation" + val adds = emitStampedAddFiles(name) + val deltaLog = deltaLogForName(name) + val initialVersion = deltaLog.update().version + val initialBackRefs = adds.map(add => add.path -> add.backReference).toMap + + def assertUnchanged(): Unit = { + val snapshot = deltaLog.update() + assert(snapshot.version == initialVersion, + "a rejected transaction must not advance the table version.") + assert(liveAddFiles(snapshot).map(add => add.path -> add.backReference).toMap == + initialBackRefs, "a rejected transaction must not change the live file references.") + } - test("commit fails when a leaf-derived file's tombstone is missing its back reference") { - withTable("amt_commit_missing") { - val adds = emitStampedAddFiles("amt_commit_missing") - // Strip the back reference off a tombstone for a file the tree says should carry one. - val stripped = adds.head.removeWithTimestamp().copy(backReference = None) - val ex = intercept[IllegalStateException] { - commitActions("amt_commit_missing", Seq(stripped)) + locally { + val stripped = adds.head.removeWithTimestamp().copy(backReference = None) + val ex = intercept[IllegalStateException] { + commitActions(name, Seq(stripped)) + } + assert(ex.getMessage.contains("does not match the AMT")) + assert(ex.getMessage.contains(stripped.path)) + assertUnchanged() } - assert(ex.getMessage.contains("does not match the AMT")) - assert(ex.getMessage.contains(stripped.path)) - } - } - test("commit fails when a fresh file carries a spurious back reference") { - withTable("amt_commit_spurious") { - val adds = emitStampedAddFiles("amt_commit_spurious") - // A file not in the tree must not carry a back reference. - val spurious = adds.head.copy(path = "brand-new-file.parquet") - val ex = intercept[IllegalStateException] { - commitActions("amt_commit_spurious", Seq(spurious)) + locally { + val spurious = adds.head.copy(path = "brand-new-file.parquet") + val ex = intercept[IllegalStateException] { + commitActions(name, Seq(spurious)) + } + assert(ex.getMessage.contains("not present in the AMT")) + assertUnchanged() } - assert(ex.getMessage.contains("not present in the AMT")) - } - } - test("commit fails when a present file's tombstone carries the wrong back reference") { - withTable("amt_commit_wrong") { - val adds = emitStampedAddFiles("amt_commit_wrong") - val wrongBr = adds.head.backReference.get.copy(pos = adds.head.backReference.get.pos + 1000) - val wrong = adds.head.removeWithTimestamp().copy(backReference = Some(wrongBr)) - val ex = intercept[IllegalStateException] { - commitActions("amt_commit_wrong", Seq(wrong)) + locally { + val wrongBr = adds.head.backReference.get.copy(pos = adds.head.backReference.get.pos + 1000) + val wrong = adds.head.removeWithTimestamp().copy(backReference = Some(wrongBr)) + val ex = intercept[IllegalStateException] { + commitActions(name, Seq(wrong)) + } + assert(ex.getMessage.contains("does not match the AMT")) + assertUnchanged() } - assert(ex.getMessage.contains("does not match the AMT")) + + // Fresh transactions must still accept valid actions after the rejected attempts. + commitActions(name, Seq(adds.head.removeWithTimestamp())) + val fresh = adds.head.copy(path = "brand-new-file.parquet", backReference = None) + commitActions(name, Seq(fresh)) + val expectedPaths = initialBackRefs.keySet - adds.head.path + fresh.path + assert(liveAddFiles(deltaLog.update()).map(_.path).toSet == expectedPaths) } } @@ -789,59 +755,58 @@ class AMTBackReferenceSuite assert(fs.exists(compactedDeltaPath), "Compaction must allow a content root within the window.") } - /** - * Builds an AMT source with stamped files, runs `clone(src, tgt)`, then asserts every AddFile - * committed to the target carries no back reference. - */ - private def testCloneDropsBackRefs( - testName: String)(clone: (String, String) => Unit): Unit = { - testAcrossAMTCheckpointScenarios( - testName, - "amt_clone_src", - sqlConfs = leafPackingConfs)( - setup = name => appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 1), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { context => - val src = context.tableName - // Derive the clone target from the scenario-unique source, so the scenarios do not share a - // table directory (see the naming note in `testAcrossAMTCheckpointScenarios`). - val tgt = s"${src}_clone_tgt" - val srcBackRefByPath = stampedBackRefs(context.postCheckpointSnapshot) - val srcSnapshotIds = liveAddFiles(context.postCheckpointSnapshot).flatMap(_.snapshotId).toSet - - withTable(tgt) { - clone(src, tgt) - - val tgtLog = deltaLogForName(tgt) - val latest = tgtLog.update().version - val addsBySnapshotId = (0L to latest) - .flatMap(v => actionsAt(tgtLog, v)) - .collect { case add: AddFile => add } - .groupBy(_.snapshotId) - val cloneGroups = addsBySnapshotId.collect { - case (Some(snapshotId), adds) if adds.size >= srcBackRefByPath.size => snapshotId -> adds - } - assert(cloneGroups.size == 1, - s"expected one CLONE snapshot with at least ${srcBackRefByPath.size} files, " + - s"got ${cloneGroups.map { case (id, adds) => id -> adds.size }}.") - val (cloneSnapshotId, clonedSourceAdds) = cloneGroups.head - clonedSourceAdds.foreach { a => - assert(a.backReference.isEmpty, - s"Cloned AddFile ${a.path} must not carry the source table's back reference.") - assert(!srcSnapshotIds.contains(cloneSnapshotId), - s"Cloned AddFile ${a.path} must start a new snapshot lifecycle.") - assert(a.modifiedSnapshotId.isEmpty) + testAcrossAMTCheckpointScenarios( + "CLONE variants drop the source table's back references", + "amt_clone_src", + sqlConfs = leafPackingConfs)( + setup = name => appendRowsAsSeparateFiles(name, numFiles = leafPackedFiles - 1), + inlineCheckpointTriggerActionsOrSQL = Some(name => Right( + s"INSERT INTO $name VALUES (${leafPackedFiles - 1})"))) { context => + val src = context.tableName + val srcBackRefByPath = stampedBackRefs(context.postCheckpointSnapshot) + val srcSnapshotIds = liveAddFiles(context.postCheckpointSnapshot).flatMap(_.snapshotId).toSet + val srcLog = context.postCheckpointSnapshot.deltaLog + val srcVersion = context.postCheckpointSnapshot.version + + // Each clone reads the same immutable source and owns a separate target and cleanup scope. + def checkClone(variant: String)(clone: (String, String) => Unit): Unit = { + val tgt = s"${src}_${variant}_tgt" + withClue(s"$variant: ") { + withTable(tgt) { + clone(src, tgt) + + val tgtLog = deltaLogForName(tgt) + val latest = tgtLog.update().version + val addsBySnapshotId = (0L to latest) + .flatMap(v => actionsAt(tgtLog, v)) + .collect { case add: AddFile => add } + .groupBy(_.snapshotId) + val cloneGroups = addsBySnapshotId.collect { + case (Some(snapshotId), adds) if adds.size >= srcBackRefByPath.size => + snapshotId -> adds + } + assert(cloneGroups.size == 1, + s"expected one CLONE snapshot with at least ${srcBackRefByPath.size} files, " + + s"got ${cloneGroups.map { case (id, adds) => id -> adds.size }}.") + val (cloneSnapshotId, clonedSourceAdds) = cloneGroups.head + clonedSourceAdds.foreach { a => + assert(a.backReference.isEmpty, + s"Cloned AddFile ${a.path} must not carry the source table's back reference.") + assert(!srcSnapshotIds.contains(cloneSnapshotId), + s"Cloned AddFile ${a.path} must start a new snapshot lifecycle.") + assert(a.modifiedSnapshotId.isEmpty) + } + assert(srcLog.update().version == srcVersion, "CLONE must leave its source unchanged.") } } } - } - Seq("SHALLOW").foreach { cloneType => - testCloneDropsBackRefs( - s"$cloneType CLONE drops the source table's back references") { (src, tgt) => - sql(s"CREATE TABLE $tgt $cloneType CLONE $src") - } + Seq("SHALLOW").foreach { cloneType => + checkClone(s"${cloneType}_create") { (src, tgt) => + sql(s"CREATE TABLE $tgt $cloneType CLONE $src") + } + } } testAcrossAMTCheckpointScenarios( From fbc776de2b510445b099030000f4286de10b0c47 Mon Sep 17 00:00:00 2001 From: Cyrus Najmabadi Date: Wed, 18 Nov 2026 15:52:36 +0100 Subject: [PATCH 43/44] [Spark] Share AMT snapshot test fixtures (#8196) #### Which Delta project/connector is this regarding? - [x] Spark ## Description Sharing checkpoints across compatible AMT snapshot checks avoids repeated fixture construction while keeping mutable histories isolated. | Pre-export source-suite workload and timed scope | Before | After | Benefit | | --- | ---: | ---: | ---: | | Complete five-shard `AMTSnapshotSuite`, mean first test-action start through last test-action finish | 371.740 s | 352.347 s | 5.22% lower | Two alternating pre-export runs per source revision compared `0af7c6e203e660d0073f25e2b0c261ecfa0e527d` with `408de8dba1118392ce5e6018424760af41cb7fa3`, including startup, fixtures and teardown. Later source cleanups and this public head were not timed. CPU and CI savings are unmeasured. ## How was this patch tested? The 87-case pre-export source suite retains all 99 original obligations across three checkpoint modes, with alternate-order and deliberate DELETE/manifest-deletion-vector faults. The final generated patch was applied to public master, and the resulting file matches the reviewed output blob. The transformed public suite has not been run locally. Public CI passes on `1849c03b526045aee1b42e7dd43c467ca159fcf3`. ## Does this PR introduce any user-facing changes? No.
Agent attribution Agent: Costly Tests - Orchestrator | Session: 01a1e505-448e-7d81-b315-7ef768b0399c
Signed-off-by: Cyrus Najmabadi Co-authored-by: Cyrus Najmabadi --- .../sql/delta/amt/AMTSnapshotSuite.scala | 241 ++++++++---------- 1 file changed, 103 insertions(+), 138 deletions(-) diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotSuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotSuite.scala index 8f1cf015a24..74f5d15d7f2 100644 --- a/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotSuite.scala +++ b/spark/src/test/scala/org/apache/spark/sql/delta/amt/AMTSnapshotSuite.scala @@ -44,7 +44,7 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti /////////////////////////// testAcrossAMTCheckpointScenarios( - "snapshot.allFiles reflects a DELETE on the checkpoint boundary", + "snapshot and filtered scans reflect a DELETE on the checkpoint boundary", "amt_delete_boundary")( setup = name => (1 to 3).foreach(i => sql(s"INSERT INTO $name VALUES ($i)")), inlineCheckpointTriggerActionsOrSQL = Some(name => Right( @@ -54,55 +54,16 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti // The manifest tree captures exactly the post-DELETE live files (computePostCommitState applied // the RemoveFile), i.e. it matches snapshot.allFiles. assertLiveAddFilesRoundTrip(context) - } - - testAcrossAMTCheckpointScenarios( - "plain AMT tables reconstruct AddFiles with snapshot provenance", - "amt_passthrough_roundtrip")( - setup = name => sql(s"INSERT INTO $name VALUES (1)"), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (2)"))) { context => - // Both INSERTs create plain data files. Reconstruction must retain each file's creation SID, - // while modifiedSnapshotId stays empty because neither file has modification metadata. - val files = context.postCheckpointSnapshot.allFiles.collect() - assert(files.nonEmpty) - assert(files.forall(_.snapshotId.isDefined), - s"every AMT file must carry snapshot provenance; got " + - s"${files.map(file => (file.snapshotId, file.modifiedSnapshotId)).mkString(", ")}") - assert(files.forall(_.modifiedSnapshotId.isEmpty)) - } - - testAcrossAMTCheckpointScenarios( - "snapshot provenance tracks the first DV update", - "amt_snapshot_id_first_dv")( - setup = name => - Seq(1, 2).toDF("id").coalesce(1).write.mode("append").insertInto(name), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"DELETE FROM $name WHERE id = 1"))) { context => - // The first DELETE terminates the no-DV tuple and adds a DV to the same data file. The old - // tuple's removal and the new DV are created in the same snapshot. - val actions = actionsAt( - context.postCheckpointSnapshot.deltaLog, - context.checkpoint.version) - val add = actions.collectFirst { - case action: AddFile if action.deletionVector != null => action - }.getOrElse(fail("expected a superseding AddFile with a deletion vector.")) - val remove = actions.collectFirst { - case action: RemoveFile if action.path == add.path => action - }.getOrElse(fail("expected a paired RemoveFile for the DV update.")) - - assert(add.snapshotId.isDefined) - assert(remove.snapshotId.isDefined) - assert(add.modifiedSnapshotId == remove.snapshotId) - assert(remove.modifiedSnapshotId.isEmpty) - // Verify that the top-level IDs survive the AddFile -> DataEntry -> AddFile round-trip. - val reconstructed = context.postCheckpointSnapshot.allFiles.collect() - .find(_.path == add.path) - .getOrElse(fail("the DV-bearing AddFile must reconstruct from the AMT.")) - assert(reconstructed.snapshotId == add.snapshotId) - assert(reconstructed.modifiedSnapshotId == add.modifiedSnapshotId) - assert(reconstructed.amtPassthrough == add.amtPassthrough) + // SQL data-skipping reconstruction is disabled for AMT tables, so reads go through the + // allFiles-based reconstruction: the leaves supply state up to the checkpoint and the + // trimmed deltas supply the rest. Each row must appear exactly once -- a double-count would + // surface as duplicate rows or wrong counts. + val table = spark.read.table(context.tableName) + val expectedRows = Seq(Row(2), Row(3)) + checkAnswer(table.filter("id >= 2"), expectedRows) + checkAnswer( + table.groupBy().count(), Seq(Row(expectedRows.size.toLong))) } testAcrossAMTCheckpointScenarios( @@ -141,12 +102,37 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti } testAcrossAMTCheckpointScenarios( - "metadata-only re-add assigns missing snapshot IDs without emitting CDF", + "first DV provenance and metadata-only re-add without CDF", "amt_snapshot_id_metadata_readd")( setup = name => Seq(1, 2).toDF("id").coalesce(1).write.mode("append").insertInto(name), inlineCheckpointTriggerActionsOrSQL = Some(name => Right( s"DELETE FROM $name WHERE id = 1"))) { context => + // The first DELETE terminates the no-DV tuple and adds a DV to the same data file. The old + // tuple's removal and the new DV are created in the same snapshot. + val actions = actionsAt( + context.postCheckpointSnapshot.deltaLog, + context.checkpoint.version) + val add = actions.collectFirst { + case action: AddFile if action.deletionVector != null => action + }.getOrElse(fail("expected a superseding AddFile with a deletion vector.")) + val remove = actions.collectFirst { + case action: RemoveFile if action.path == add.path => action + }.getOrElse(fail("expected a paired RemoveFile for the DV update.")) + + assert(add.snapshotId.isDefined) + assert(remove.snapshotId.isDefined) + assert(add.modifiedSnapshotId == remove.snapshotId) + assert(remove.modifiedSnapshotId.isEmpty) + + // Verify that the top-level IDs survive the AddFile -> DataEntry -> AddFile round-trip. + val reconstructed = context.postCheckpointSnapshot.allFiles.collect() + .find(_.path == add.path) + .getOrElse(fail("the DV-bearing AddFile must reconstruct from the AMT.")) + assert(reconstructed.snapshotId == add.snapshotId) + assert(reconstructed.modifiedSnapshotId == add.modifiedSnapshotId) + assert(reconstructed.amtPassthrough == add.amtPassthrough) + val deltaLog = context.postCheckpointSnapshot.deltaLog val current = context.postCheckpointSnapshot.allFiles.collect() .find(_.deletionVector != null) @@ -513,12 +499,21 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti } testAcrossAMTCheckpointScenarios( - "snapshot replays trailing append after an AMT checkpoint", + "snapshot provenance and trailing append after an AMT checkpoint", "amt_tail_append")( setup = name => sql(s"INSERT INTO $name VALUES (1)"), inlineCheckpointTriggerActionsOrSQL = Some(name => Right( s"INSERT INTO $name VALUES (2)"))) { context => - val addFilesAtCheckpointVersion = context.postCheckpointSnapshot.allFiles.collect() + // Both INSERTs create plain data files. Reconstruction must retain each file's creation SID, + // while modifiedSnapshotId stays empty because neither file has modification metadata. + val files = context.postCheckpointSnapshot.allFiles.collect() + assert(files.nonEmpty) + assert(files.forall(_.snapshotId.isDefined), + s"every AMT file must carry snapshot provenance; got " + + s"${files.map(file => (file.snapshotId, file.modifiedSnapshotId)).mkString(", ")}") + assert(files.forall(_.modifiedSnapshotId.isEmpty)) + + val addFilesAtCheckpointVersion = files val addFilePathsAtCheckpointVersion = addFilesAtCheckpointVersion.map(_.path).toSet assert(addFilePathsAtCheckpointVersion.size == 2) @@ -804,24 +799,6 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti assert(live.head.amtPassthrough.contains(fullPassthrough)) } - testAcrossAMTCheckpointScenarios( - "filtered scan is correct after emission (trimmed deltas + leaves)", - "amt_filtered_scan")( - setup = name => (1 to 3).foreach(i => sql(s"INSERT INTO $name VALUES ($i)")), - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"DELETE FROM $name WHERE id = 1"))) { context => - // SQL data-skipping reconstruction is disabled for AMT tables, so reads go through the - // allFiles-based reconstruction: the leaves supply state up to the checkpoint and the - // trimmed deltas supply the rest. Each row must appear exactly once -- a double-count would - // surface as duplicate rows or wrong counts. - val table = spark.read.table(context.tableName) - val expectedRows = Seq(Row(2), Row(3)) - checkAnswer(table.filter("id >= 2"), expectedRows) - checkAnswer( - table.groupBy().count(), Seq(Row(expectedRows.size.toLong))) - checkAnswer(table, expectedRows) - } - testAcrossAMTCheckpointScenarios( "deletion vector round-trips through the leaves as a relative-path DV", "amt_dv", @@ -1104,7 +1081,7 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti } testAcrossAMTCheckpointScenarios( - "distributed reconstruction returns every action exactly once", + "distributed reconstruction and per-leaf manifest deletion vectors", "amt_dist_reconstruction", sqlConfs = leafPackingConfs)( setup = name => { @@ -1114,13 +1091,13 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti inlineCheckpointTriggerActionsOrSQL = Some(name => Right( s"INSERT INTO $name VALUES (${2 * leafPackedFiles - 1})"))) { context => val snapshot = context.postCheckpointSnapshot - val provider = context.provider + val base = context.provider val expectedRows = 0 until 2 * leafPackedFiles checkAnswer(spark.read.table(context.tableName), expectedRows.map(Row(_))) val committedPaths = snapshot.allFiles.select("path").as[String].collect().toSet assert(committedPaths.size == expectedRows.size) - assertLeafCount(provider.leaves, numFiles = 2 * leafPackedFiles) - val df = provider.loadActionsForStateReconstruction(spark, snapshot.deltaLog) + assertLeafCount(base.leaves, numFiles = 2 * leafPackedFiles) + val df = base.loadActionsForStateReconstruction(spark, snapshot.deltaLog) .getOrElse(fail("AMT provider must contribute leaf-derived actions.")) // The leaves must be read through a distributed parquet scan, not a driver-side collected @@ -1139,6 +1116,58 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti "Reconstruction must carry the inline protocol action.") assert(df.where("metaData.id is not null").count() == 1, "Reconstruction must carry the inline metadata action.") + + val full = reconstructedPaths(base, snapshot.deltaLog) + assert(full.size == 2 * leafPackedFiles) + + // The leaf-local row-index -> entry-location map for each observed leaf. + val locs = base.leaves.map(leafPosToLoc(_, base.tableRoot)) + def withMdv(idx: Int, positions: Seq[Long]): DataManifestEntry = { + val leaf = base.leaves(idx) + leaf.copy(manifest_info = leaf.manifest_info.copy( + dv = Some(mdvBytesFor(positions: _*)))) + } + // Exercise every MDV shape in one tree (positions are leaf-local row indices): + // - one leaf: drop a single position (pos 0), + // - one leaf: drop all its positions (whole leaf), + // - one leaf: drop two positions (its 2nd and 4th, i.e. sorted indices 1 and 3), + // - one leaf: an empty MDV (no-op), + // - the remaining leaves: no MDV. + // The clustered rewrite does not guarantee a fixed leaf order/size, so the shapes are bound + // to leaves chosen by observed size (largest first); the two-position shape needs >= 4 + // entries. + val bySizeDesc = locs.indices.sortBy(i => -locs(i).size) + val twoLeaf = bySizeDesc(0) + val wholeLeaf = bySizeDesc(1) + val singleLeaf = bySizeDesc(2) + val emptyLeaf = bySizeDesc(3) + def sortedPos(idx: Int): Seq[Long] = locs(idx).keys.toSeq.sorted + assert(sortedPos(twoLeaf).size >= 4, + s"the largest leaf must hold >= 4 entries for the two-position MDV; " + + s"got ${sortedPos(twoLeaf).size}.") + val twoPositions = Seq(sortedPos(twoLeaf)(1), sortedPos(twoLeaf)(3)) + val patched = base.leaves.zipWithIndex.map { case (leaf, idx) => + idx match { + case `twoLeaf` => withMdv(idx, twoPositions) + case `wholeLeaf` => withMdv(idx, sortedPos(idx)) + case `singleLeaf` => withMdv(idx, Seq(sortedPos(idx).head)) + case `emptyLeaf` => withMdv(idx, Seq.empty) + case _ => leaf + } + } + val provider = AMTCheckpointProvider( + spark, base.manifestCommitVersion, base.checkpointAction, patched, base.tableRoot) + + val dropped = + twoPositions.map(locs(twoLeaf)).toSet ++ + locs(wholeLeaf).values.toSet + + locs(singleLeaf)(sortedPos(singleLeaf).head) + val reconstructed = reconstructedPaths(provider, snapshot.deltaLog) + assert(reconstructed == full -- dropped, + "Each MDV must drop exactly its marked positions from its own leaf, and nothing else.") + assert(reconstructed.size == full.size - dropped.size) + assert(reconstructedPaths(base, snapshot.deltaLog) == full, + "Reading an MDV-patched provider must not change the original reconstruction.") } // The large multi-leaf tree is covered above; this is the small deterministic case, where the @@ -1333,70 +1362,6 @@ class AMTSnapshotSuite extends AMTCheckpointTestBase with DeletionVectorsTestUti "Only the MDV-marked entry may be dropped; all other live files must survive.") } - testAcrossAMTCheckpointScenarios( - "manifest deletion vectors apply per leaf across a multi-leaf tree", - "amt_mdv_multi", - sqlConfs = leafPackingConfs)( - setup = name => { - appendRowsAsSeparateFiles(name, leafPackedFiles) - appendRowsAsSeparateFiles(name, leafPackedFiles - 1, startId = leafPackedFiles) - }, - inlineCheckpointTriggerActionsOrSQL = Some(name => Right( - s"INSERT INTO $name VALUES (${2 * leafPackedFiles - 1})"))) { context => - val base = context.provider - assertLeafCount(base.leaves, numFiles = 2 * leafPackedFiles) - val deltaLog = context.postCheckpointSnapshot.deltaLog - val full = reconstructedPaths(base, deltaLog) - assert(full.size == 2 * leafPackedFiles) - - // The leaf-local row-index -> entry-location map for each observed leaf. - val locs = base.leaves.map(leafPosToLoc(_, base.tableRoot)) - def withMdv(idx: Int, positions: Seq[Long]): DataManifestEntry = { - val leaf = base.leaves(idx) - leaf.copy(manifest_info = leaf.manifest_info.copy( - dv = Some(mdvBytesFor(positions: _*)))) - } - // Exercise every MDV shape in one tree (positions are leaf-local row indices): - // - one leaf: drop a single position (pos 0), - // - one leaf: drop all its positions (whole leaf), - // - one leaf: drop two positions (its 2nd and 4th, i.e. sorted indices 1 and 3), - // - one leaf: an empty MDV (no-op), - // - the remaining leaves: no MDV. - // The clustered rewrite does not guarantee a fixed leaf order/size, so the shapes are bound - // to leaves chosen by observed size (largest first); the two-position shape needs >= 4 - // entries. - val bySizeDesc = locs.indices.sortBy(i => -locs(i).size) - val twoLeaf = bySizeDesc(0) - val wholeLeaf = bySizeDesc(1) - val singleLeaf = bySizeDesc(2) - val emptyLeaf = bySizeDesc(3) - def sortedPos(idx: Int): Seq[Long] = locs(idx).keys.toSeq.sorted - assert(sortedPos(twoLeaf).size >= 4, - s"the largest leaf must hold >= 4 entries for the two-position MDV; " + - s"got ${sortedPos(twoLeaf).size}.") - val twoPositions = Seq(sortedPos(twoLeaf)(1), sortedPos(twoLeaf)(3)) - val patched = base.leaves.zipWithIndex.map { case (leaf, idx) => - idx match { - case `twoLeaf` => withMdv(idx, twoPositions) - case `wholeLeaf` => withMdv(idx, sortedPos(idx)) - case `singleLeaf` => withMdv(idx, Seq(sortedPos(idx).head)) - case `emptyLeaf` => withMdv(idx, Seq.empty) - case _ => leaf - } - } - val provider = AMTCheckpointProvider( - spark, base.manifestCommitVersion, base.checkpointAction, patched, base.tableRoot) - - val dropped = - twoPositions.map(locs(twoLeaf)).toSet ++ - locs(wholeLeaf).values.toSet + - locs(singleLeaf)(sortedPos(singleLeaf).head) - val reconstructed = reconstructedPaths(provider, deltaLog) - assert(reconstructed == full -- dropped, - "Each MDV must drop exactly its marked positions from its own leaf, and nothing else.") - assert(reconstructed.size == full.size - dropped.size) - } - testAcrossAMTCheckpointScenarios( "surviving entries keep their DV and stats when an MDV drops a sibling", "amt_mdv_sibling", From 685eec209c48b57a5b8c84ad352baf528b313fca Mon Sep 17 00:00:00 2001 From: Eunjin Song Date: Wed, 18 Nov 2026 08:59:15 -0800 Subject: [PATCH 44/44] [Spark] Support ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY Adds a metadata-only command that removes the partitioning of a Delta table without rewriting data files: ALTER TABLE t REPLACE PARTITIONED BY WITH CLUSTER BY ALTER TABLE t REPLACE PARTITIONED BY WITH CLUSTER BY (c1, c2) ALTER TABLE t REPLACE PARTITIONED BY WITH CLUSTER BY NONE Without columns, the partition columns become the clustering columns; with NONE the table becomes a plain unpartitioned table. The command verifies that every data file physically stores the partition columns (written when delta.writePartitionColumnsToParquet is enabled), then re-adds all files in a single commitLarge commit with empty partitionValues and dataChange=false. The stats of each file are extended with min/max/nullCount for the former partition columns, and delta.dataSkippingStatsColumns is set when they would otherwise lose stats, so data skipping on them keeps working. The existing stats are kept exactly. Tables with IcebergCompat, UniForm or adaptive metadata enabled are rejected. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 Signed-off-by: Eunjin Song --- .../io/delta/sql/parser/DeltaSqlBase.g4 | 5 + .../resources/error/delta-error-classes.json | 19 + .../io/delta/sql/parser/DeltaSqlParser.scala | 20 +- .../apache/spark/sql/delta/DeltaErrors.scala | 22 + .../spark/sql/delta/DeltaOperations.scala | 24 + .../delta/catalog/AbstractDeltaCatalog.scala | 15 +- ...rtitionedByWithClusterByDeltaCommand.scala | 381 +++++++++++ .../clustering/temp/AlterTableClusterBy.scala | 29 + ...placePartitionedByWithClusterBySuite.scala | 626 ++++++++++++++++++ 9 files changed, 1139 insertions(+), 2 deletions(-) create mode 100644 spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala create mode 100644 spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala diff --git a/spark/src/main/antlr4/io/delta/sql/parser/DeltaSqlBase.g4 b/spark/src/main/antlr4/io/delta/sql/parser/DeltaSqlBase.g4 index c176f06aab0..207f8599726 100644 --- a/spark/src/main/antlr4/io/delta/sql/parser/DeltaSqlBase.g4 +++ b/spark/src/main/antlr4/io/delta/sql/parser/DeltaSqlBase.g4 @@ -90,6 +90,9 @@ statement DROP FEATURE featureName=featureNameValue (TRUNCATE HISTORY)? #alterTableDropFeature | ALTER TABLE table=qualifiedName (clusterBySpec | CLUSTER BY NONE) #alterTableClusterBy + | ALTER TABLE table=qualifiedName + REPLACE PARTITIONED BY WITH + (clusterBySpec | CLUSTER BY NONE | CLUSTER BY) #alterTableReplacePartitionedBy | ALTER TABLE table=qualifiedName (ALTER | CHANGE) COLUMN? column=qualifiedName SYNC IDENTITY #alterTableSyncIdentity | OPTIMIZE (path=stringLit | table=qualifiedName) FULL? @@ -272,6 +275,7 @@ nonReserved | CLONE | SHALLOW | FEATURE | TRUNCATE | CLUSTER | NONE + | WITH ; // Define how the keywords above should appear in a user's SQL statement. @@ -345,6 +349,7 @@ USING: 'USING'; VACUUM: 'VACUUM'; VERSION: 'VERSION'; WHERE: 'WHERE'; +WITH: 'WITH'; ZORDER: 'ZORDER'; STATISTICS: 'STATISTICS'; diff --git a/spark/src/main/resources/error/delta-error-classes.json b/spark/src/main/resources/error/delta-error-classes.json index a222cbfd8a5..794a7564dd5 100644 --- a/spark/src/main/resources/error/delta-error-classes.json +++ b/spark/src/main/resources/error/delta-error-classes.json @@ -2821,6 +2821,25 @@ ], "sqlState" : "44000" }, + "DELTA_REPLACE_PARTITIONED_BY_ON_UNPARTITIONED_TABLE" : { + "message" : [ + "ALTER TABLE REPLACE PARTITIONED BY can only be applied to a partitioned table." + ], + "sqlState" : "42000" + }, + "DELTA_REPLACE_PARTITIONED_BY_PARTITION_COLUMNS_NOT_MATERIALIZED" : { + "message" : [ + "Cannot replace the partitioning of the table because the partition column(s) are not stored in data file(s), for example: .", + "ALTER TABLE REPLACE PARTITIONED BY requires every data file to store the partition columns. Delta stores them in the files it writes while the table property delta.writePartitionColumnsToParquet is enabled." + ], + "sqlState" : "55000" + }, + "DELTA_REPLACE_PARTITIONED_BY_UNSUPPORTED_TABLE_FEATURE" : { + "message" : [ + "ALTER TABLE REPLACE PARTITIONED BY is not supported on tables with enabled." + ], + "sqlState" : "0AKDC" + }, "DELTA_REPLACE_TABLE_WITH_CATALOG_MANAGED_NOT_SUPPORTED" : { "message" : [ "REPLACE TABLE cannot enable catalog-managed on the existing non-catalog-managed table . Upgrade or recreate the table instead." diff --git a/spark/src/main/scala/io/delta/sql/parser/DeltaSqlParser.scala b/spark/src/main/scala/io/delta/sql/parser/DeltaSqlParser.scala index fc85f46fa2c..19477296839 100644 --- a/spark/src/main/scala/io/delta/sql/parser/DeltaSqlParser.scala +++ b/spark/src/main/scala/io/delta/sql/parser/DeltaSqlParser.scala @@ -43,7 +43,7 @@ import java.util.Locale import scala.collection.JavaConverters._ import org.apache.spark.sql.catalyst.TimeTravel -import org.apache.spark.sql.delta.skipping.clustering.temp.{AlterTableClusterBy, ClusterByParserUtils, ClusterByPlan, ClusterBySpec} +import org.apache.spark.sql.delta.skipping.clustering.temp.{AlterTableClusterBy, AlterTableReplacePartitionedByWithClusterBy, ClusterByParserUtils, ClusterByPlan, ClusterBySpec} import org.apache.spark.sql.delta._ import org.apache.spark.sql.delta.commands._ @@ -639,6 +639,24 @@ class DeltaSqlAstBuilder extends DeltaSqlBaseBaseVisitor[AnyRef] { } } + /** + * Parse `ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY [(col1, ...) | NONE]`. + * Without columns or NONE, the partition columns become the clustering columns. + */ + override def visitAlterTableReplacePartitionedBy( + ctx: AlterTableReplacePartitionedByContext): LogicalPlan = withOrigin(ctx) { + val table = UnresolvedTable( + ctx.table.identifier.asScala.map(_.getText).toSeq, + "ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY") + val clusterBySpec = Option(ctx.clusterBySpec()).map { spec => + ClusterBySpec(spec.interleave.asScala.map(_.identifier.asScala.map(_.getText).toSeq).toSeq) + } + AlterTableReplacePartitionedByWithClusterBy( + table, + clusterBySpec, + clusterByPartitionColumns = clusterBySpec.isEmpty && ctx.NONE() == null) + } + protected def typedVisit[T](ctx: ParseTree): T = { ctx.accept(this).asInstanceOf[T] } diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala index 8527ee512b6..4dcf6bfe707 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaErrors.scala @@ -4356,6 +4356,28 @@ trait DeltaErrorsBase messageParameters = Array.empty) } + def replacePartitionedByOnUnpartitionedTableException(): Throwable = { + new DeltaAnalysisException( + errorClass = "DELTA_REPLACE_PARTITIONED_BY_ON_UNPARTITIONED_TABLE", + messageParameters = Array.empty) + } + + def replacePartitionedByUnsupportedTableFeatureException(feature: String): Throwable = { + new DeltaUnsupportedOperationException( + errorClass = "DELTA_REPLACE_PARTITIONED_BY_UNSUPPORTED_TABLE_FEATURE", + messageParameters = Array(feature)) + } + + def replacePartitionedByPartitionColumnsNotMaterializedException( + partitionColumns: Seq[String], + numFiles: Long, + examplePaths: Seq[String]): Throwable = { + new DeltaAnalysisException( + errorClass = "DELTA_REPLACE_PARTITIONED_BY_PARTITION_COLUMNS_NOT_MATERIALIZED", + messageParameters = Array( + partitionColumns.mkString(", "), numFiles.toString, examplePaths.mkString(", "))) + } + def createTableWithDifferentClusteringException( path: Path, specifiedClusterBySpec: Option[ClusterBySpec], diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaOperations.scala b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaOperations.scala index 02826577954..b9424217f1d 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/DeltaOperations.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/DeltaOperations.scala @@ -1082,6 +1082,30 @@ object DeltaOperations { override def canChangePartitionColumns: Boolean = false } + /** + * Recorded when the partitioning of a table is replaced with clustering (or no layout) via + * `ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY`. + */ + case class ReplacePartitionedByWithClusterBy( + oldPartitioningColumns: String, + newClusteringColumns: String) extends Operation("REPLACE PARTITIONED BY WITH CLUSTER BY") { + override val parameters: Map[String, Any] = Map( + "oldPartitioningColumns" -> oldPartitioningColumns, + "newClusteringColumns" -> newClusteringColumns) + + // Existing AddFiles are re-added with their DVs and stats copied over (plus synthesized + // stats for the former partition columns). Stats may have been recomputed as tight bounds + // by ComputeStats before, so this check should be disabled. + override def checkAddFileWithDeletionVectorStatsAreNotTightBounds: Boolean = false + + // Only partition values and stats of existing files are updated in place. + override val isInPlaceFileMetadataUpdate: Option[Boolean] = Some(true) + + override def expectedFileDataChange: Option[Boolean] = Some(false) + + override def canChangePartitionColumns: Boolean = true + } + /** Recorded when we backfill a Delta table's existing AddFiles with row tracking data. */ case class RowTrackingBackfill( batchId: Int = 0) extends Operation(ROW_TRACKING_BACKFILL_OPERATION_NAME) { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/catalog/AbstractDeltaCatalog.scala b/spark/src/main/scala/org/apache/spark/sql/delta/catalog/AbstractDeltaCatalog.scala index 48792dbb525..faffe4f6e3a 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/catalog/AbstractDeltaCatalog.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/catalog/AbstractDeltaCatalog.scala @@ -28,7 +28,7 @@ import scala.collection.mutable import io.delta.storage.commit.uccommitcoordinator.UCCommitCoordinatorClient.UC_TABLE_ID_KEY import io.delta.storage.commit.uccommitcoordinator.UCCommitCoordinatorClient.UC_TABLE_ID_KEY_OLD import org.apache.spark.sql.delta.skipping.clustering.ClusteredTableUtils -import org.apache.spark.sql.delta.skipping.clustering.temp.{ClusterBy, ClusterBySpec} +import org.apache.spark.sql.delta.skipping.clustering.temp.{ClusterBy, ClusterBySpec, ReplacePartitionedByWithClusterBy} import org.apache.spark.sql.delta.skipping.clustering.temp.{ClusterByTransform => TempClusterByTransform} import org.apache.spark.sql.delta.{ColumnWithDefaultExprUtils, DeltaConfigs, DeltaErrors, DeltaTableUtils} import org.apache.spark.sql.delta.{DeltaOptions, IdentityColumn} @@ -1201,6 +1201,8 @@ class AbstractDeltaCatalog extends DelegatingCatalogExtension case deltaTable: DeltaTableV2 => deltaTable case _ if changes.exists(_.isInstanceOf[ClusterBy]) => throw DeltaErrors.alterClusterByNotOnDeltaTableException() + case _ if changes.exists(_.isInstanceOf[ReplacePartitionedByWithClusterBy]) => + throw DeltaErrors.alterClusterByNotOnDeltaTableException() case _ if changes.exists(_.isInstanceOf[SyncIdentity]) => throw DeltaErrors.identityColumnAlterNonDeltaFormatError() case _ => return super.alterTable(ident, changes: _*) @@ -1423,6 +1425,17 @@ class AbstractDeltaCatalog extends DelegatingCatalogExtension AlterTableClusterByDeltaCommand( table, c.clusteringColumns.map(_.fieldNames().toSeq).toSeq).run(spark) } + + case (t, replace) if t == classOf[ReplacePartitionedByWithClusterBy] => + replace.asInstanceOf[Seq[ReplacePartitionedByWithClusterBy]].foreach { r => + if (r.clusteringColumns.nonEmpty) { + validateClusterBySpec(Some(ClusterBySpec(r.clusteringColumns.toSeq)), table.schema()) + } + AlterTableReplacePartitionedByWithClusterByDeltaCommand( + table, + r.clusteringColumns.map(_.fieldNames().toSeq).toSeq, + r.clusterByPartitionColumns).run(spark) + } } if (columnUpdates.nonEmpty) { diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala b/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala new file mode 100644 index 00000000000..f2d55da2d93 --- /dev/null +++ b/spark/src/main/scala/org/apache/spark/sql/delta/commands/AlterTableReplacePartitionedByWithClusterByDeltaCommand.scala @@ -0,0 +1,381 @@ +/* + * 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.commands + +import java.util.Locale + +import scala.collection.JavaConverters._ + +import org.apache.spark.sql.delta.skipping.clustering.ClusteredTableUtils +import org.apache.spark.sql.delta.skipping.clustering.temp.ClusterBySpec +import org.apache.spark.sql.delta._ +import org.apache.spark.sql.delta.actions.{Action, Metadata} +import org.apache.spark.sql.delta.amt.AMTUtils +import org.apache.spark.sql.delta.catalog.DeltaTableV2 +import org.apache.spark.sql.delta.schema.SchemaMergingUtils +import org.apache.spark.sql.delta.sources.DeltaSQLConf +import org.apache.spark.sql.delta.stats.{DeltaStatistics, SkippingEligibleDataType, StatisticsCollection} +import org.apache.spark.sql.delta.util.{DeltaFileOperations, JsonUtils} +import com.fasterxml.jackson.core.JsonProcessingException +import com.fasterxml.jackson.databind.{DeserializationFeature, JsonNode} +import com.fasterxml.jackson.databind.cfg.JsonNodeFeature +import com.fasterxml.jackson.databind.node.{DecimalNode, LongNode, ObjectNode, TextNode} +import org.apache.parquet.format.converter.ParquetMetadataConverter + +import org.apache.spark.sql.{Row, SparkSession} +import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute +import org.apache.spark.sql.catalyst.expressions.{Cast, Literal} +import org.apache.spark.sql.connector.expressions.FieldReference +import org.apache.spark.sql.execution.command.LeafRunnableCommand +import org.apache.spark.sql.execution.datasources.parquet.ParquetFooterReaderShims +import org.apache.spark.sql.types._ +import org.apache.spark.unsafe.types.UTF8String +import org.apache.spark.util.SerializableConfiguration + +/** + * Command that replaces the partitioning of a Delta table with clustering, without rewriting + * any data file: + * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY (col1, col2, ...) + * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY NONE + * - ALTER TABLE .. REPLACE PARTITIONED BY WITH CLUSTER BY, which clusters the table by its + * partition columns (`clusterByPartitionColumns`) + * + * The conversion is a single metadata-only commit which + * 1. clears the partition columns in the table metadata, + * 2. re-adds every active file with empty `partitionValues` and `dataChange = false`, keeping its + * path, deletion vector and row tracking fields. Per-file min/max/nullCount statistics are + * synthesized for the former partition columns from the (constant) partition values so that + * data skipping on these columns keeps working, and + * 3. when clustering columns are given, enables clustering and records the clustering columns. + * + * After the conversion the former partition columns are read from the data files, so they must be + * physically stored in every data file (see `delta.writePartitionColumnsToParquet` and the + * `materializePartitionColumns` table feature). This is verified by reading the Parquet footers + * before committing. + * + * When a former partition column would not get statistics anymore, because it is after the first + * `delta.dataSkippingNumIndexedCols` columns or not in `delta.dataSkippingStatsColumns`, the + * conversion sets `delta.dataSkippingStatsColumns` so that the columns that had statistics before + * and the former partition columns keep them. + * + * As for any change of the partitioning, streaming queries reading the table fail when they reach + * the conversion. A query with a `schemaTrackingLocation` continues after a restart; other queries + * must be restarted with a new checkpoint. + * + * The commit is done with [[OptimisticTransaction.commitLarge]], which fails if any other commit + * happened since the transaction started. Hence no file can be added concurrently between the + * verification and the commit. + */ +case class AlterTableReplacePartitionedByWithClusterByDeltaCommand( + table: DeltaTableV2, + requestedClusteringColumns: Seq[Seq[String]], + clusterByPartitionColumns: Boolean = false) + extends LeafRunnableCommand with AlterDeltaTableCommand { + + override def run(sparkSession: SparkSession): Seq[Row] = { + val deltaLog = table.deltaLog + recordDeltaOperation(deltaLog, "delta.ddl.alter.replacePartitionedByWithClusterBy") { + val txn = startTransaction() + val snapshot = txn.snapshot + val oldMetadata = txn.metadata + if (oldMetadata.partitionColumns.isEmpty) { + throw DeltaErrors.replacePartitionedByOnUnpartitionedTableException() + } + // The commit below neither runs the IcebergCompat checks (which do not allow changing the + // partition columns) nor converts the table to Iceberg or Hudi, and the adaptive metadata + // manifest of the files records their partitioning. + IcebergCompat.anyEnabled(oldMetadata).foreach { compat => + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException(compat.config.key) + } + if (UniversalFormat.icebergEnabled(oldMetadata) || UniversalFormat.hudiEnabled(oldMetadata)) { + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( + DeltaConfigs.UNIVERSAL_FORMAT_ENABLED_FORMATS.key) + } + if (AMTUtils.amtEnabled(snapshot, isPreviewCompatible = true)) { + throw DeltaErrors.replacePartitionedByUnsupportedTableFeatureException( + AdaptiveMetadataTableFeatureBase.supportedBy(snapshot.protocol) + .getOrElse(AdaptiveMetadataTableFeature).name) + } + val clusteringColumns = if (clusterByPartitionColumns) { + oldMetadata.partitionColumns.map(Seq(_)) + } else { + requestedClusteringColumns + } + ClusteredTableUtils.validateNumClusteringColumns(clusteringColumns, Some(deltaLog)) + + val physicalPartitionSchema = oldMetadata.physicalPartitionSchema + val conf = sparkSession.sessionState.conf + + // Update the metadata and validate the clustering columns before reading the footers of all + // data files below, so that invalid commands fail fast. + val newLogicalClusteringColumns = clusteringColumns.map(FieldReference(_).toString) + val baseConfiguration = oldMetadata.configuration + val clusteringConfiguration = + if (clusteringColumns.nonEmpty && !ClusteredTableUtils.isSupported(txn.protocol)) { + ClusteredTableUtils.getTableFeatureProperties(baseConfiguration) + } else { + Map.empty[String, String] + } + val unpartitionedMetadata = oldMetadata.copy( + partitionColumns = Nil, configuration = baseConfiguration ++ clusteringConfiguration) + val statsColumnsConfiguration = + ReplacePartitionedByUtils.statsColumnsConfiguration(oldMetadata, unpartitionedMetadata) + txn.updateMetadata(unpartitionedMetadata.copy( + configuration = unpartitionedMetadata.configuration ++ statsColumnsConfiguration)) + + val domainMetadata = if (clusteringColumns.nonEmpty) { + ClusteredTableUtils.validateClusteringColumnsInStatsSchema( + txn.protocol, txn.metadata, ClusterBySpec(clusteringColumns)) + ClusteredTableUtils.getClusteringDomainMetadataForAlterTableClusterBy( + newLogicalClusteringColumns, txn) + } else { + Nil + } + + ReplacePartitionedByUtils.verifyPartitionColumnsMaterialized( + sparkSession, deltaLog, snapshot, oldMetadata.partitionColumns, + physicalPartitionSchema.fieldNames.toSeq) + + val stringPrefixLength = conf.getConf(DeltaSQLConf.DATA_SKIPPING_STRING_PREFIX_LENGTH) + val timeZoneId = conf.sessionLocalTimeZone + val partitionFields = physicalPartitionSchema.fields.toSeq + import org.apache.spark.sql.delta.implicits._ + val newAddFiles = snapshot.allFiles.mapPartitions { files => + files.map { file => + file.copy( + partitionValues = Map.empty, + dataChange = false, + stats = ReplacePartitionedByUtils.addPartitionValuesToStats( + file.stats, file.partitionValues, partitionFields, stringPrefixLength, timeZoneId)) + } + } + + val actions: Iterator[Action] = + newAddFiles.toLocalIterator().asScala ++ domainMetadata.iterator + val newProtocolOpt = + if (txn.protocol != snapshot.protocol) Some(txn.protocol) else None + txn.commitLarge( + sparkSession, + actions, + newProtocolOpt, + DeltaOperations.ReplacePartitionedByWithClusterBy( + oldMetadata.partitionColumns.mkString(","), + newLogicalClusteringColumns.mkString(",")), + context = Map.empty, + metrics = Map.empty, + dataChange = false) + } + Seq.empty[Row] + } +} + +object ReplacePartitionedByUtils { + + private val NUM_EXAMPLE_FILES = 5 + + /** + * Verifies that every active data file of the snapshot physically stores all the given + * partition columns, by reading the Parquet footers of the files. + */ + def verifyPartitionColumnsMaterialized( + spark: SparkSession, + deltaLog: DeltaLog, + snapshot: Snapshot, + logicalPartitionColumns: Seq[String], + physicalPartitionColumns: Seq[String]): Unit = { + val broadcastConf = spark.sparkContext.broadcast( + new SerializableConfiguration(deltaLog.newDeltaHadoopConf())) + val dataRootDir = deltaLog.dataPath.toString + val requiredColumns = physicalPartitionColumns.map(_.toLowerCase(Locale.ROOT)) + + import org.apache.spark.sql.delta.implicits._ + val filesMissingColumns = snapshot.allFiles.select("path").as[String].mapPartitions { paths => + val conf = broadcastConf.value.value + paths.filter { relativePath => + val path = DeltaFileOperations.absolutePath(dataRootDir, relativePath) + val status = path.getFileSystem(conf).getFileStatus(path) + val footer = ParquetFooterReaderShims.readParquetFooter( + conf, status, ParquetMetadataConverter.SKIP_ROW_GROUPS) + val fileColumns = footer.getFileMetaData.getSchema.getFields.asScala + .map(_.getName.toLowerCase(Locale.ROOT)).toSet + !requiredColumns.forall(fileColumns.contains) + } + } + + val examples = filesMissingColumns.take(NUM_EXAMPLE_FILES) + if (examples.nonEmpty) { + throw DeltaErrors.replacePartitionedByPartitionColumnsNotMaterializedException( + logicalPartitionColumns, filesMissingColumns.count(), examples.toSeq) + } + } + + /** + * Returns the table configuration that keeps statistics on the former partition columns, and on + * all the columns that had statistics before, once the partitioning is dropped. + * + * Partition columns are not data columns, so they do not count towards + * `delta.dataSkippingNumIndexedCols` and cannot be listed in `delta.dataSkippingStatsColumns`. + * Once they become data columns, a former partition column after the first indexed columns + * would get no statistics (the synthesized ones would be ignored too), and a former partition + * column before the last indexed column would push that column out of the indexed columns. In + * these cases `delta.dataSkippingStatsColumns` is set to the columns that had statistics before + * followed by the former partition columns. Top-level columns of a type that does not support + * data skipping cannot be listed and are left out. + */ + def statsColumnsConfiguration( + partitionedMetadata: Metadata, + unpartitionedMetadata: Metadata): Map[String, String] = { + def isListable(field: StructField): Boolean = + field.dataType.isInstanceOf[StructType] || SkippingEligibleDataType(field.dataType) + def key(path: Seq[String]): Seq[String] = path.map(_.toLowerCase(Locale.ROOT)) + + val formerPartitionColumns = partitionedMetadata.partitionSchema.fields.toSeq + .filter(isListable).map(field => Seq(field.name)) + val indexedBefore = StructType(indexedColumns(partitionedMetadata).fields.filter(isListable)) + val indexedAfter = leafPaths(indexedColumns(unpartitionedMetadata)).map(key).toSet + val required = leafPaths(indexedBefore) ++ formerPartitionColumns + if (required.forall(path => indexedAfter.contains(key(path)))) return Map.empty + + val formerPartitionColumnNames = formerPartitionColumns.map(UnresolvedAttribute(_).sql) + val statsColumns = + DeltaConfigs.DATA_SKIPPING_STATS_COLUMNS.fromMetaData(partitionedMetadata) match { + case Some(configured) => configured.trim +: formerPartitionColumnNames + case None => + statsColumnNames(indexedBefore, partitionedMetadata.dataSchema) + .map(UnresolvedAttribute(_).sql) ++ formerPartitionColumnNames + } + Map(DeltaConfigs.DATA_SKIPPING_STATS_COLUMNS.key -> + statsColumns.filter(_.nonEmpty).mkString(",")) + } + + /** The logical data schema pruned to the columns that statistics are collected on. */ + private def indexedColumns(metadata: Metadata): StructType = { + val dataSchema = metadata.dataSchema + StatisticsCollection.getIndexedColumns( + SchemaMergingUtils.explodeNestedFieldNames(dataSchema), + StatisticsCollection.configuredDeltaStatsColumnSpec(metadata), + dataSchema, + NoMapping) + } + + private def leafPaths(schema: StructType, prefix: Seq[String] = Nil): Seq[Seq[String]] = + schema.fields.toSeq.flatMap { field => + field.dataType match { + case struct: StructType => leafPaths(struct, prefix :+ field.name) + case _ => Seq(prefix :+ field.name) + } + } + + /** + * Returns the names to list in `delta.dataSkippingStatsColumns` to collect statistics on the + * columns of `indexed`, a pruned version of `schema`. A struct is listed by its name when none of + * its fields are pruned. + */ + private def statsColumnNames( + indexed: StructType, + schema: StructType, + prefix: Seq[String] = Nil): Seq[Seq[String]] = + indexed.fields.toSeq.flatMap { field => + (field.dataType, schema(field.name).dataType) match { + case (struct: StructType, fullStruct: StructType) if struct != fullStruct => + statsColumnNames(struct, fullStruct, prefix :+ field.name) + case _ => Seq(prefix :+ field.name) + } + } + + /** + * Adds min/max/nullCount statistics for the given partition columns to the stats JSON of a + * file, using the file's partition values. Every row in a file has the same value for a + * partition column, so these statistics are exact. Statistics that already exist are kept, and + * no statistics are added if the file has none. + * + * A partition value is parsed the same way as when it is read as a partition value. No + * statistics are added for a column whose value is an empty string or cannot be cast to the + * column type, because the value stored in the data file for it is not known. Min/max values are + * only synthesized for string, integral, decimal and date columns; other types only get a null + * count. + */ + // Reads the numbers of the statistics exactly, so that the decimal min/max values of the other + // columns are not rounded through Double when the statistics are written back. + private lazy val exactStatsReader = JsonUtils.mapper.reader() + .`with`(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + .without(JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES) + + def addPartitionValuesToStats( + stats: String, + partitionValues: Map[String, String], + partitionFields: Seq[StructField], + stringPrefixLength: Int, + timeZoneId: String): String = { + if (stats == null || stats.isEmpty) return stats + val root = try { + exactStatsReader.readTree(stats) match { + case o: ObjectNode => o + case _ => return stats + } + } catch { + case _: JsonProcessingException => return stats + } + val numRecords = root.get(DeltaStatistics.NUM_RECORDS) + if (numRecords == null || !numRecords.canConvertToLong) return stats + + def objectField(name: String): Option[ObjectNode] = root.get(name) match { + case null => Some(root.putObject(name)) + case o: ObjectNode => Some(o) + case _ => None + } + val minValues = objectField(DeltaStatistics.MIN) + val maxValues = objectField(DeltaStatistics.MAX) + val nullCounts = objectField(DeltaStatistics.NULL_COUNT) + + partitionFields.foreach { field => + val name = field.name + partitionValues.getOrElse(name, null) match { + case null => + nullCounts.filterNot(_.has(name)).foreach(_.put(name, numRecords.asLong)) + case "" => + // The protocol defines an empty string as a null partition value, but Delta reads it as + // an empty string for string columns, so the file may store either. + case value => + val parsed = Cast(Literal(value), field.dataType, Option(timeZoneId), ansiEnabled = false) + .eval() + if (parsed != null) { + nullCounts.filterNot(_.has(name)).foreach(_.put(name, 0L)) + toStatsValue(parsed, field.dataType, stringPrefixLength).foreach { v => + minValues.filterNot(_.has(name)).foreach(_.set[JsonNode](name, v)) + maxValues.filterNot(_.has(name)).foreach(_.set[JsonNode](name, v)) + } + } + } + } + JsonUtils.mapper.writeValueAsString(root) + } + + /** Converts a value of the given type, as returned by [[Cast]], to its JSON stats value. */ + private def toStatsValue(value: Any, dataType: DataType, stringPrefixLength: Int) + : Option[JsonNode] = (dataType, value) match { + // Longer strings would need to be truncated the same way as collected stats. + case (StringType, s: UTF8String) if s.numChars <= stringPrefixLength => + Some(TextNode.valueOf(s.toString)) + case (ByteType | ShortType | IntegerType | LongType, n: java.lang.Number) => + Some(LongNode.valueOf(n.longValue)) + case (_: DecimalType, d: Decimal) => Some(DecimalNode.valueOf(d.toJavaBigDecimal)) + case (DateType, days: Int) => + Some(TextNode.valueOf(java.time.LocalDate.ofEpochDay(days.toLong).toString)) + case _ => None + } +} diff --git a/spark/src/main/scala/org/apache/spark/sql/delta/skipping/clustering/temp/AlterTableClusterBy.scala b/spark/src/main/scala/org/apache/spark/sql/delta/skipping/clustering/temp/AlterTableClusterBy.scala index 405446d41b6..75862791e03 100644 --- a/spark/src/main/scala/org/apache/spark/sql/delta/skipping/clustering/temp/AlterTableClusterBy.scala +++ b/spark/src/main/scala/org/apache/spark/sql/delta/skipping/clustering/temp/AlterTableClusterBy.scala @@ -37,3 +37,32 @@ case class AlterTableClusterBy( /** A TableChange to alter clustering columns for a table. */ case class ClusterBy(clusteringColumns: Seq[NamedReference]) extends TableChange {} + +/** + * The logical plan of the following commands: + * - ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY (col1, col2, ...) + * - ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY NONE + * - ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY + * + * Converts a partitioned table into a clustered table (or an unpartitioned, unclustered table + * with NONE) without rewriting data files. Without columns or NONE + * (`clusterByPartitionColumns`), the partition columns become the clustering columns. + */ +case class AlterTableReplacePartitionedByWithClusterBy( + table: LogicalPlan, + clusterBySpec: Option[ClusterBySpec], + clusterByPartitionColumns: Boolean = false) extends AlterTableCommand { + override def changes: Seq[TableChange] = + Seq(ReplacePartitionedByWithClusterBy( + clusterBySpec.map(_.columnNames).getOrElse(Seq.empty), clusterByPartitionColumns)) + + protected def withNewChildInternal(newChild: LogicalPlan): LogicalPlan = copy(table = newChild) +} + +/** + * A TableChange to replace the partitioning of a table with the given clustering columns, or + * with the partition columns if `clusterByPartitionColumns` is set. + */ +case class ReplacePartitionedByWithClusterBy( + clusteringColumns: Seq[NamedReference], + clusterByPartitionColumns: Boolean = false) extends TableChange {} diff --git a/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala new file mode 100644 index 00000000000..363fb516a5c --- /dev/null +++ b/spark/src/test/scala/org/apache/spark/sql/delta/skipping/clustering/ReplacePartitionedByWithClusterBySuite.scala @@ -0,0 +1,626 @@ +/* + * 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.skipping.clustering + +import java.io.File + +import org.apache.spark.sql.delta.skipping.ClusteredTableTestUtils +import org.apache.spark.sql.delta.skipping.clustering.temp.{AlterTableReplacePartitionedByWithClusterBy, ClusterBySpec} +import org.apache.spark.sql.delta.{AdaptiveMetadataPreviewTableFeature, DeltaAnalysisException, DeltaConfigs, DeltaLog, DeltaOperations, DeltaUnsupportedOperationException} +import org.apache.spark.sql.delta.actions.{AddFile, TableFeatureProtocolUtils} +import org.apache.spark.sql.delta.commands.ReplacePartitionedByUtils +import org.apache.spark.sql.delta.coordinatedcommits.CatalogOwnedTestBaseSuite +import org.apache.spark.sql.delta.sources.DeltaSQLConf +import org.apache.spark.sql.delta.stats.DataSkippingDeltaTestsUtils +import org.apache.spark.sql.delta.test.DeltaSQLCommandTest +import org.apache.spark.sql.delta.util.JsonUtils + +import com.fasterxml.jackson.databind.DeserializationFeature + +import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.TableIdentifier +import org.apache.spark.sql.catalyst.analysis.UnresolvedTable +import org.apache.spark.sql.streaming.{StreamingQueryException, Trigger} +import org.apache.spark.sql.types.{ByteType, DateType, DecimalType, IntegerType, StringType, StructField, TimestampType} + +class ReplacePartitionedByWithClusterBySuite + extends QueryTest + with ClusteredTableTestUtils + with DeltaSQLCommandTest + with DataSkippingDeltaTestsUtils { + + private val opName = "REPLACE PARTITIONED BY WITH CLUSTER BY" + + private def createPartitionedTable(path: String, partitionColumns: String*): Unit = { + spark.range(0, 100, 1, 4) + .selectExpr("id", "cast(id % 5 as string) as p", "cast(id % 3 as int) as q", "id * 2 as v") + .write.format("delta").partitionBy(partitionColumns: _*).save(path) + } + + private def readTable(path: String) = spark.read.format("delta").load(path) + + private def statsOf(file: AddFile): Map[String, Any] = + JsonUtils.fromJson[Map[String, Any]](file.stats) + + test("parser") { + val parser = spark.sessionState.sqlParser + val none = parser.parsePlan("ALTER TABLE t REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + assert(none === AlterTableReplacePartitionedByWithClusterBy( + UnresolvedTable(Seq("t"), "ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY"), None)) + val cols = parser.parsePlan( + "ALTER TABLE a.t REPLACE PARTITIONED BY WITH CLUSTER BY (c1, s.c2)") + assert(cols === AlterTableReplacePartitionedByWithClusterBy( + UnresolvedTable(Seq("a", "t"), "ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY"), + Some(ClusterBySpec(Seq(Seq("c1"), Seq("s", "c2")))))) + val partitionColumns = parser.parsePlan("ALTER TABLE t REPLACE PARTITIONED BY WITH CLUSTER BY") + assert(partitionColumns === AlterTableReplacePartitionedByWithClusterBy( + UnresolvedTable(Seq("t"), "ALTER TABLE ... REPLACE PARTITIONED BY WITH CLUSTER BY"), None, + clusterByPartitionColumns = true)) + // `with` is not reserved. + parser.parsePlan("VACUUM with") + } + + test("CLUSTER BY NONE drops the partitioning without rewriting data files") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p", "q") + val deltaLog = DeltaLog.forTable(spark, path) + val before = deltaLog.update() + val expected = readTable(path).collect() + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + val after = deltaLog.update() + assert(after.version === before.version + 1) + assert(after.metadata.partitionColumns.isEmpty) + assert(after.schema === before.schema) + // No new table features, the table is a plain unpartitioned table. + assert(after.protocol === before.protocol) + assert(!ClusteredTableUtils.isSupported(after.protocol)) + assert(after.allFiles.collect().map(_.path).toSet === + before.allFiles.collect().map(_.path).toSet) + assert(after.allFiles.collect().forall(_.partitionValues.isEmpty)) + // All columns of a narrow table have statistics without listing them. + assert(statsColumnsOf(deltaLog).isEmpty) + checkAnswer(readTable(path), expected) + + val lastCommit = deltaLog.history.getHistory(Some(1)).head + assert(lastCommit.operation === opName) + assert(lastCommit.operationParameters("oldPartitioningColumns") === "p,q") + assert(lastCommit.operationParameters("newClusteringColumns") === "") + + val changes = deltaLog.getChanges(after.version).next()._2 + assert(changes.collect { case a: AddFile => a }.forall(!_.dataChange)) + + // Time travel to the partitioned version still works. + checkAnswer( + spark.read.format("delta").option("versionAsOf", before.version).load(path), expected) + } + } + + test("statistics are synthesized for the former partition columns") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p", "q") + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + val deltaLog = DeltaLog.forTable(spark, path) + deltaLog.update().allFiles.collect().foreach { f => + val stats = statsOf(f) + val p = stats("minValues").asInstanceOf[Map[String, Any]]("p") + assert(stats("maxValues").asInstanceOf[Map[String, Any]]("p") === p) + assert(stats("nullCount").asInstanceOf[Map[String, Any]]("p") === 0) + assert(stats("minValues").asInstanceOf[Map[String, Any]].contains("q")) + assert(stats("minValues").asInstanceOf[Map[String, Any]].contains("id")) + } + // Each former partition value is in its own set of files, which can be skipped. + val numFiles = deltaLog.update().numOfFiles + val numFilesForP3 = filesRead(spark, deltaLog, "p = '3'", checkEmptyUnusedFilters = false) + assert(numFilesForP3 > 0 && numFilesForP3 < numFiles) + checkAnswer( + readTable(path).where("p = '3'").selectExpr("count(*)"), Row(20L)) + val numFilesForQ1 = filesRead(spark, deltaLog, "q = 1", checkEmptyUnusedFilters = false) + assert(numFilesForQ1 > 0 && numFilesForQ1 < numFiles) + } + } + + test("writes, DML and OPTIMIZE after dropping the partitioning") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p") + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + val deltaLog = DeltaLog.forTable(spark, path) + val filesBefore = deltaLog.update().allFiles.collect().map(_.path).toSet + + spark.range(100, 110).selectExpr("id", "'9' as p", "cast(id % 3 as int) as q", "id * 2 as v") + .write.format("delta").mode("append").save(path) + val newFiles = deltaLog.update().allFiles.collect().filterNot(f => filesBefore(f.path)) + assert(newFiles.nonEmpty) + // New files are written at the root of the table. + assert(newFiles.forall(f => !f.path.contains("/") && f.partitionValues.isEmpty)) + + sql(s"UPDATE delta.`$path` SET v = -1 WHERE p = '1'") + sql(s"DELETE FROM delta.`$path` WHERE p = '2'") + sql(s"""MERGE INTO delta.`$path` t USING (SELECT 0L AS id, 'x' AS p) s ON t.id = s.id + |WHEN MATCHED THEN UPDATE SET t.p = s.p""".stripMargin) + checkAnswer(readTable(path).where("p = '1'").selectExpr("count(*)", "max(v)"), + Row(20L, -1L)) + checkAnswer(readTable(path).where("p = '2'").selectExpr("count(*)"), Row(0L)) + checkAnswer(readTable(path).where("id = 0").select("p"), Row("x")) + checkAnswer(readTable(path).selectExpr("count(*)"), Row(90L)) + + sql(s"OPTIMIZE delta.`$path`") + checkAnswer(readTable(path).selectExpr("count(*)"), Row(90L)) + assert(deltaLog.update().metadata.partitionColumns.isEmpty) + } + } + + test("CLUSTER BY columns converts a partitioned table into a clustered table") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p") + val expected = readTable(path).collect() + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY (p, id)") + val deltaLog = DeltaLog.forTable(spark, path) + val snapshot = deltaLog.update() + assert(snapshot.metadata.partitionColumns.isEmpty) + assert(ClusteredTableUtils.isSupported(snapshot.protocol)) + verifyClusteringColumnsInDomainMetadata(snapshot, Seq("p", "id")) + checkAnswer(readTable(path), expected) + val lastCommit = deltaLog.history.getHistory(Some(1)).head + assert(lastCommit.operation === opName) + assert(lastCommit.operationParameters("newClusteringColumns") === "p,id") + + // The table can be clustered and further altered like any clustered table. + sql(s"OPTIMIZE delta.`$path`") + checkAnswer(readTable(path), expected) + sql(s"ALTER TABLE delta.`$path` CLUSTER BY (id)") + verifyClusteringColumnsInDomainMetadata(deltaLog.update(), Seq("id")) + } + } + + test("CLUSTER BY without columns clusters the table by its partition columns") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p", "q") + val deltaLog = DeltaLog.forTable(spark, path) + val filesBefore = deltaLog.update().allFiles.collect().map(_.path).toSet + val expected = readTable(path).collect() + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY") + + val snapshot = deltaLog.update() + assert(snapshot.metadata.partitionColumns.isEmpty) + assert(ClusteredTableUtils.isSupported(snapshot.protocol)) + verifyClusteringColumnsInDomainMetadata(snapshot, Seq("p", "q")) + assert(snapshot.allFiles.collect().map(_.path).toSet === filesBefore) + checkAnswer(readTable(path), expected) + val lastCommit = deltaLog.history.getHistory(Some(1)).head + assert(lastCommit.operation === opName) + assert(lastCommit.operationParameters("oldPartitioningColumns") === "p,q") + assert(lastCommit.operationParameters("newClusteringColumns") === "p,q") + } + } + + test("CLUSTER BY without columns fails with more partition columns than clustering columns") { + withTempDir { dir => + val path = dir.getCanonicalPath + spark.range(0, 10) + .selectExpr("id", "id % 2 as a", "id % 3 as b", "id % 4 as c", "id % 5 as d", "id % 6 as e") + .write.format("delta").partitionBy("a", "b", "c", "d", "e").save(path) + val deltaLog = DeltaLog.forTable(spark, path) + val versionBefore = deltaLog.update().version + checkError( + exception = intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY") + }, + condition = "DELTA_CLUSTER_BY_INVALID_NUM_COLUMNS", + parameters = Map("numColumnsLimit" -> "4", "actualNumColumns" -> "5")) + assert(deltaLog.update().version === versionBefore) + // The clustering columns can be given explicitly instead. + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY (a, b)") + verifyClusteringColumnsInDomainMetadata(deltaLog.update(), Seq("a", "b")) + } + } + + test("works with catalog tables") { + withTable("tbl") { + sql("CREATE TABLE tbl (id BIGINT, p STRING) USING delta PARTITIONED BY (p)") + sql("INSERT INTO tbl VALUES (1, 'a'), (2, 'b'), (3, null)") + sql("ALTER TABLE tbl REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + checkAnswer(sql("SELECT * FROM tbl"), Seq(Row(1L, "a"), Row(2L, "b"), Row(3L, null))) + checkAnswer(sql("SELECT id FROM tbl WHERE p IS NULL"), Row(3L)) + val detail = sql("DESCRIBE DETAIL tbl").select("partitionColumns").head() + assert(detail.getSeq[String](0).isEmpty) + } + } + + test("works with column mapping") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ('delta.columnMapping.mode' = 'name')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a'), (2, 'b')") + sql(s"ALTER TABLE delta.`$path` RENAME COLUMN p TO p2") + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + checkAnswer(readTable(path), Seq(Row(1L, "a"), Row(2L, "b"))) + checkAnswer(readTable(path).where("p2 = 'b'").select("id"), Row(2L)) + val deltaLog = DeltaLog.forTable(spark, path) + assert(filesRead(spark, deltaLog, "p2 = 'b'", checkEmptyUnusedFilters = false) === 1) + } + } + + test("works with deletion vectors and row tracking") { + withTempDir { dir => + val path = dir.getCanonicalPath + withSQLConf( + "spark.databricks.delta.properties.defaults.enableDeletionVectors" -> "true", + "spark.databricks.delta.properties.defaults.enableRowTracking" -> "true") { + createPartitionedTable(path, "p") + } + sql(s"DELETE FROM delta.`$path` WHERE id % 10 = 0") + val deltaLog = DeltaLog.forTable(spark, path) + val before = deltaLog.update() + assert(before.allFiles.collect().exists(_.deletionVector != null)) + val expected = readTable(path).selectExpr("*", "_metadata.row_id").collect() + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + val after = deltaLog.update() + val beforeByPath = before.allFiles.collect().map(f => f.path -> f).toMap + after.allFiles.collect().foreach { f => + val old = beforeByPath(f.path) + assert(f.deletionVector === old.deletionVector) + assert(f.baseRowId === old.baseRowId) + assert(f.defaultRowCommitVersion === old.defaultRowCommitVersion) + } + checkAnswer(readTable(path).selectExpr("*", "_metadata.row_id"), expected) + } + } + + test("fails on an unpartitioned table") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path) + val e = intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + } + assert(e.getErrorClass === "DELTA_REPLACE_PARTITIONED_BY_ON_UNPARTITIONED_TABLE") + } + } + + test("fails when data files do not store the partition columns") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ('delta.writePartitionColumnsToParquet' = 'false')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a'), (2, 'b')") + val deltaLog = DeltaLog.forTable(spark, path) + val versionBefore = deltaLog.update().version + val e = intercept[DeltaAnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + } + assert(e.getErrorClass === + "DELTA_REPLACE_PARTITIONED_BY_PARTITION_COLUMNS_NOT_MATERIALIZED") + assert(e.getMessage.contains("2 data file(s)")) + assert(deltaLog.update().version === versionBefore) + assert(deltaLog.update().metadata.partitionColumns === Seq("p")) + } + } + + test("fails on a table with IcebergCompatV2") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ('delta.columnMapping.mode' = 'name', + | 'delta.enableIcebergCompatV2' = 'true')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a')") + val deltaLog = DeltaLog.forTable(spark, path) + val versionBefore = deltaLog.update().version + checkError( + exception = intercept[DeltaUnsupportedOperationException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + }, + condition = "DELTA_REPLACE_PARTITIONED_BY_UNSUPPORTED_TABLE_FEATURE", + parameters = Map("feature" -> "delta.enableIcebergCompatV2")) + assert(deltaLog.update().version === versionBefore) + } + } + + test("fails on a non-existing clustering column") { + withTempDir { dir => + val path = dir.getCanonicalPath + createPartitionedTable(path, "p") + checkError( + exception = intercept[AnalysisException] { + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY (missing)") + }, + condition = "DELTA_COLUMN_NOT_FOUND_IN_SCHEMA", + matchPVals = true, + parameters = Map("columnName" -> "missing", "tableSchema" -> "(?s).*")) + assert(DeltaLog.forTable(spark, path).update().metadata.partitionColumns === Seq("p")) + } + } + + test("addPartitionValuesToStats") { + val fields = Seq( + StructField("s", StringType), StructField("i", IntegerType), + StructField("d", DateType), StructField("t", TimestampType), StructField("n", StringType), + StructField("dec", DecimalType(10, 2)), StructField("e", StringType), + StructField("ei", IntegerType), StructField("x", IntegerType), StructField("b", ByteType)) + val stats = + """{"numRecords":3,"minValues":{"id":1},"maxValues":{"id":3},"nullCount":{"id":0}}""" + val values = Map("s" -> "abc", "i" -> " 7", "d" -> "2024-01-02", + "t" -> "2024-01-02 03:04:05", "n" -> null, "dec" -> "1.5", + // Empty strings and values that cannot be cast to the column type get no statistics. + "e" -> "", "ei" -> "", "x" -> "abc", "b" -> "300") + def addStats(stats: String, values: Map[String, String], fields: Seq[StructField]): String = + ReplacePartitionedByUtils.addPartitionValuesToStats(stats, values, fields, 32, "UTC") + val result = JsonUtils.fromJson[Map[String, Map[String, Any]]]( + addStats(stats, values, fields).replace("\"numRecords\":3,", "")) + val expectedMinMax = Map("s" -> "abc", "i" -> 7, "d" -> "2024-01-02", "dec" -> 1.5) + assert(result("minValues") === Map("id" -> 1) ++ expectedMinMax) + assert(result("maxValues") === Map("id" -> 3) ++ expectedMinMax) + assert(result("nullCount") === + Map("id" -> 0, "s" -> 0, "i" -> 0, "d" -> 0, "t" -> 0, "n" -> 3, "dec" -> 0)) + // Long strings are not added since collected string stats would be truncated. + assert(!addStats(stats, Map("s" -> ("x" * 33)), fields.take(1)).contains("xxx")) + // Files without stats are left untouched. + assert(addStats(null, values, fields) === null) + assert(addStats("", values, fields) === "") + } + + test("an empty string partition value gets no statistics") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"CREATE TABLE delta.`$path` (id BIGINT, p STRING) USING delta PARTITIONED BY (p)") + sql(s"INSERT INTO delta.`$path` VALUES (1, 'a')") + // Delta writes null partition values as null, but the protocol also allows an empty + // string. Add such a file, which stores a null in the data. + val manualDir = new File(dir, "manual") + spark.range(2, 3).selectExpr("id", "cast(null as string) as p").coalesce(1) + .write.parquet(manualDir.getCanonicalPath) + val dataFile = manualDir.listFiles().filter(_.getName.endsWith(".parquet")).head + val deltaLog = DeltaLog.forTable(spark, path) + deltaLog.startTransaction().commit( + Seq(AddFile( + path = s"manual/${dataFile.getName}", + partitionValues = Map("p" -> ""), + size = dataFile.length(), + modificationTime = dataFile.lastModified(), + dataChange = true, + stats = """{"numRecords":1}""")), + DeltaOperations.ManualUpdate) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + val file = deltaLog.update().allFiles.collect().find(_.path.startsWith("manual/")).get + assert(!statsOf(file)("nullCount").asInstanceOf[Map[String, Any]].contains("p")) + assert(!statsOf(file)("minValues").asInstanceOf[Map[String, Any]].contains("p")) + // The file is not skipped. + checkAnswer(readTable(path).where("p IS NULL").select("id"), Row(2L)) + } + } + + private def statsColumnsOf(deltaLog: DeltaLog): Option[String] = + deltaLog.update().metadata.configuration.get(DeltaConfigs.DATA_SKIPPING_STATS_COLUMNS.key) + + test("keeps the statistics of a wide table") { + withTempDir { dir => + val path = dir.getCanonicalPath + // 40 data columns. Statistics are collected on the first 32 data columns, c0 to c31. + // Partition column p is before c31, q is after it. + val dataColumns = (0 until 40).map(i => s"id + $i as c$i") + val columns = dataColumns.take(5) ++ Seq("cast(id % 5 as string) as p") ++ + dataColumns.drop(5) ++ Seq("cast(id % 2 as int) as q") + spark.range(0, 100, 1, 4).selectExpr(columns: _*) + .write.format("delta").partitionBy("p", "q").save(path) + val deltaLog = DeltaLog.forTable(spark, path) + assert(statsColumnsOf(deltaLog).isEmpty) + val expected = readTable(path).collect() + + // Clustering by q requires statistics on q. + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY (q)") + + val indexedColumns = (0 until 32).map(i => s"c$i") ++ Seq("p", "q") + assert(statsColumnsOf(deltaLog) === Some(indexedColumns.mkString(","))) + checkAnswer(readTable(path), expected) + val numFiles = deltaLog.update().numOfFiles + for (predicate <- Seq("p = '3'", "q = 1", "c31 = 31")) { + assert(filesRead(spark, deltaLog, predicate, checkEmptyUnusedFilters = false) < numFiles, + predicate) + } + + // New files have statistics on the same columns. + val filesBefore = deltaLog.update().allFiles.collect().map(_.path).toSet + spark.range(100, 110).selectExpr(columns: _*) + .write.format("delta").mode("append").save(path) + val newFiles = deltaLog.update().allFiles.collect().filterNot(f => filesBefore(f.path)) + assert(newFiles.nonEmpty) + newFiles.foreach { f => + assert(statsOf(f)("minValues").asInstanceOf[Map[String, Any]].keySet === + indexedColumns.toSet) + } + } + } + + test("adds the former partition columns to delta.dataSkippingStatsColumns") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, v BIGINT, p STRING, flag BOOLEAN) + |USING delta PARTITIONED BY (p, flag) + |TBLPROPERTIES ('delta.dataSkippingStatsColumns' = 'id')""".stripMargin) + sql(s"INSERT INTO delta.`$path` VALUES (1, 1, 'a', true), (2, 2, 'b', false)") + val deltaLog = DeltaLog.forTable(spark, path) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + // Boolean columns cannot be listed. + assert(statsColumnsOf(deltaLog) === Some("id,p")) + assert(filesRead(spark, deltaLog, "p = 'b'", checkEmptyUnusedFilters = false) === 1) + checkAnswer(readTable(path).where("p = 'b'").select("id"), Row(2L)) + } + } + + test("streaming queries across the conversion") { + withTempDir { dir => + val path = new File(dir, "source").getCanonicalPath + createPartitionedTable(path, "p") + def runStream(name: String, schemaTracking: Boolean): DataFrame = { + val checkpoint = new File(dir, s"checkpoint-$name").getCanonicalPath + val sinkPath = new File(dir, s"sink-$name").getCanonicalPath + val reader = spark.readStream.format("delta") + val source = + if (schemaTracking) reader.option("schemaTrackingLocation", checkpoint) else reader + source.load(path).writeStream.format("delta") + .option("checkpointLocation", checkpoint) + .trigger(Trigger.AvailableNow()) + .start(sinkPath) + .awaitTermination() + spark.read.format("delta").load(sinkPath) + } + def assertStreamFails(name: String, schemaTracking: Boolean, errorClass: String): Unit = { + val e = intercept[StreamingQueryException] { runStream(name, schemaTracking) } + assert(e.getMessage.contains(errorClass)) + } + runStream("plain", schemaTracking = false) + runStream("tracking", schemaTracking = true) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + spark.range(100, 110).selectExpr("id", "'9' as p", "cast(id % 3 as int) as q", "id * 2 as v") + .write.format("delta").mode("append").save(path) + val expected = readTable(path).collect() + assert(expected.length === 110) + + // As for any change of the partitioning, a stream fails at the conversion, because the + // files added after it cannot be read with the partitioning the stream started with. + // Without schema tracking, the stream keeps failing when it is restarted. + for (_ <- 1 to 2) { + assertStreamFails("plain", schemaTracking = false, "DELTA_SCHEMA_CHANGED_WITH_VERSION") + } + // With schema tracking, the stream records the new metadata and continues after a restart. + assertStreamFails("tracking", schemaTracking = true, "DELTA_STREAMING_METADATA_EVOLUTION") + checkAnswer(runStream("tracking", schemaTracking = true), expected) + // A new stream reads the converted table. + checkAnswer(runStream("new", schemaTracking = false), expected) + } + } + + test("change data feed across the conversion") { + withTempDir { dir => + val path = dir.getCanonicalPath + withSQLConf(DeltaConfigs.CHANGE_DATA_FEED.defaultTablePropertyKey -> "true") { + createPartitionedTable(path, "p") + } + val deltaLog = DeltaLog.forTable(spark, path) + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + val conversionVersion = deltaLog.update().version + sql(s"DELETE FROM delta.`$path` WHERE p = '1' AND id < 50") + sql(s"INSERT INTO delta.`$path` VALUES (100, '9', 0, 200)") + val lastVersion = deltaLog.update().version + def changes(startingVersion: Long): DataFrame = spark.read.format("delta") + .option("readChangeFeed", "true") + .option("startingVersion", startingVersion) + .load(path) + .select("id", "p", "_change_type") + + // The conversion commit has no change rows. Rows deleted after it, from files written + // before it, have the values of the former partition column. + checkAnswer( + changes(conversionVersion), + (1L until 50L by 5L).map(Row(_, "1", "delete")) :+ Row(100L, "9", "insert")) + + // A read that starts before the conversion is blocked, as for any change of the + // partitioning of a non-empty table. + checkError( + exception = intercept[DeltaUnsupportedOperationException] { + changes(0).collect() + }, + condition = "DELTA_CHANGE_DATA_FEED_INCOMPATIBLE_SCHEMA_CHANGE", + sqlState = Some("0AKDC"), + matchPVals = true, + parameters = Map( + "start" -> "0", + "end" -> lastVersion.toString, + "readSchema" -> ".*", + "readVersion" -> lastVersion.toString, + "incompatibleVersion" -> "0")) + } + } + + test("keeps the precision of decimal statistics") { + withTempDir { dir => + val path = dir.getCanonicalPath + sql(s"""CREATE TABLE delta.`$path` (id BIGINT, amt DECIMAL(38, 18), p STRING) + |USING delta PARTITIONED BY (p)""".stripMargin) + sql(s"""INSERT INTO delta.`$path` VALUES + |(1, 1234567.123456789012345678, 'a'), + |(2, 1234567.123456789012345679, 'a')""".stripMargin) + val deltaLog = DeltaLog.forTable(spark, path) + // Reads the statistics without rounding decimals through Double. + val reader = JsonUtils.mapper.reader(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) + def amtStats(): Map[String, (BigDecimal, BigDecimal)] = + deltaLog.update().allFiles.collect().map { f => + val stats = reader.readTree(f.stats) + f.path -> (BigDecimal(stats.get("minValues").get("amt").decimalValue), + BigDecimal(stats.get("maxValues").get("amt").decimalValue)) + }.toMap + val statsBefore = amtStats() + assert(statsBefore.values.map(_._1).min === BigDecimal("1234567.123456789012345678")) + assert(statsBefore.values.map(_._2).max === BigDecimal("1234567.123456789012345679")) + + sql(s"ALTER TABLE delta.`$path` REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + + assert(amtStats() === statsBefore) + checkAnswer( + readTable(path).where("amt = 1234567.123456789012345678").select("id"), Row(1L)) + checkAnswer( + sql(s"SELECT MIN(amt), MAX(amt) FROM delta.`$path`"), + Row(BigDecimal("1234567.123456789012345678"), BigDecimal("1234567.123456789012345679"))) + } + } +} + +/** Adaptive metadata tables must be catalog-managed, so they need a commit coordinator. */ +class ReplacePartitionedByAdaptiveMetadataSuite + extends QueryTest + with CatalogOwnedTestBaseSuite + with DeltaSQLCommandTest { + + override def catalogOwnedCoordinatorBackfillBatchSize: Option[Int] = Some(3) + + test("fails on a table with adaptive metadata") { + val table = "replace_partitioned_by_amt" + withTable(table) { + sql(s"""CREATE TABLE $table (id BIGINT, p STRING) USING delta PARTITIONED BY (p) + |TBLPROPERTIES ( + | '${TableFeatureProtocolUtils.propertyKey(AdaptiveMetadataPreviewTableFeature)}' = + | 'supported', + | 'delta.columnMapping.mode' = 'id')""".stripMargin) + sql(s"INSERT INTO $table VALUES (1, 'a')") + val deltaLog = DeltaLog.forTable(spark, TableIdentifier(table)) + val versionBefore = deltaLog.update().version + checkError( + exception = intercept[DeltaUnsupportedOperationException] { + sql(s"ALTER TABLE $table REPLACE PARTITIONED BY WITH CLUSTER BY NONE") + }, + condition = "DELTA_REPLACE_PARTITIONED_BY_UNSUPPORTED_TABLE_FEATURE", + parameters = Map("feature" -> AdaptiveMetadataPreviewTableFeature.name)) + assert(deltaLog.update().version === versionBefore) + assert(deltaLog.update().metadata.partitionColumns === Seq("p")) + } + } +}