This is an automated email from the ASF dual-hosted git repository.

zhztheplayer pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gluten.git


The following commit(s) were added to refs/heads/main by this push:
     new 2011f60b96 [GLUTEN-12743][VL] Align Delta test parallelism and clean 
up aborted statistics (#13578)
2011f60b96 is described below

commit 2011f60b96bb54164d76092bb5d2df9c6c01e3ac
Author: Felipe Pessoto <[email protected]>
AuthorDate: Tue Nov 17 09:18:56 2026 -0800

    [GLUTEN-12743][VL] Align Delta test parallelism and clean up aborted 
statistics (#13578)
    
    * [GLUTEN-12743][VL] Align Delta Spark UT parallelism with upstream
    
    Remove the forced Spark default parallelism of one from the Delta UT JVM 
defaults. Preserve each upstream test context default so tiny fixture file 
layouts and DML data skipping match upstream. Keep native settings and the 
known-failures baseline unchanged for CI validation.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Clean up native Delta statistics on task completion
    
    Cancel and join statistics consumers before task input recyclers and native 
runtimes are released. Close aggregation and row-conversion resources on failed 
writes, balance retained batches, and clear the worker TaskContext. Add 
failed-write and multi-file lifecycle regressions and explicitly select 
statistics suites in CI.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Avoid Guava-specific statistics cleanup APIs
    
    Wait for statistics executor termination with the JDK API while preserving 
Spark cancellation interrupts. The Maven test runtime resolves a Guava 
implementation without the no-argument awaitTerminationUninterruptibly method 
used by the original cleanup patch.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Refresh Delta baseline after CI parallelism alignment
    
    Remove exactly 110 now-passing entries confirmed by complete eight-shard 
run 42446911120. All 22,571 tests executed with zero regressions; the 354 
retained entries exactly match observed failures. Preserve the baseline 
documentation, quarantine lists, and strict gates.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Scope Delta statistics lifecycle tests to Velox
    
    Move the Velox-only lifecycle suite out of shared gluten-ut sources into 
backends-velox/src-delta33 and share it with Delta 4 through a Git symlink. Use 
typed tracker/config references instead of reflection and runtime backend 
checks. Preserve the suite identity, native assertions, and all existing CI 
selectors so ClickHouse no longer compiles Velox-only dependencies.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Stop Delta statistics workers before resource release
    
    Run native tracker cleanup as a TaskContext completion listener registered 
after TaskResources. Reverse listener order joins the worker before the 
resource registry locks, avoiding a deadlock when worker output wrapping needs 
that same registry. Preserve native teardown ordering and cancellation 
interrupts in Delta 3.3 and 4.
    
    Add a bounded real-tracker cancellation regression: detect the lock cycle 
without wedging the test JVM, verify the worker can register a task resource 
during cancellation, and verify that resource is released. The regression fails 
the old cleanup and all three lifecycle tests pass on Spark 3.5 and 4.1.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [MINOR] Stabilize Delta duplicate-delete MERGE fixture
    
    Scope spark.sql.files.minPartitionNum=1 to the unpartitioned, CDF-disabled 
upstream metric fixture. Preserve native execution and all metric assertions, 
and document and verify the temporary patch.
    
    Co-authored-by: Copilot App <[email protected]>
    
    * [GLUTEN-12743][VL] Fix Delta test patch style and baseline
    
    Wrap the indented upstream comments within Delta scalastyle limits and 
document the style task omitted by testOnly. Remove only the four metric cases 
verified passing in full CI and the focused twelve-case run, retaining the 
strict gate and native execution.
    
    Co-authored-by: Copilot App <[email protected]>
    
    ---------
    
    Co-authored-by: Copilot App <[email protected]>
---
 .github/workflows/util/delta-spark-ut/README.md    |  30 ++-
 .../delta-spark-ut/apply-delta-test-patches.sh     |  30 +++
 .../util/delta-spark-ut/java-test-args.sh          |   4 +-
 .../util/delta-spark-ut/known-failures.txt         | 114 ----------
 .../merge-delete-duplicate-file-layout.patch       |  69 ++++++
 .github/workflows/velox_backend_x86.yml            |  10 +-
 .../delta/stats/GlutenDeltaJobStatsTracker.scala   |  85 +++++--
 .../sql/delta/GlutenDeltaStatsLifecycleSuite.scala | 247 +++++++++++++++++++++
 .../delta/stats/GlutenDeltaJobStatsTracker.scala   |  85 +++++--
 .../sql/delta/GlutenDeltaStatsLifecycleSuite.scala |   1 +
 10 files changed, 514 insertions(+), 161 deletions(-)

diff --git a/.github/workflows/util/delta-spark-ut/README.md 
b/.github/workflows/util/delta-spark-ut/README.md
index cecee7f3ea..f2dfc8180f 100644
--- a/.github/workflows/util/delta-spark-ut/README.md
+++ b/.github/workflows/util/delta-spark-ut/README.md
@@ -44,22 +44,41 @@ starts failing** (a regression).
 | `java-test-args.sh` | Shared Gluten Spark defaults and JVM flags 
(`--add-opens` + Netty property). Sourced by `run-delta-tests.sh` and by local 
runs. |
 | `setup-delta.sh` | Clones Delta, drops in the Gluten bundle, and applies 
temporary compatibility patches. Takes `<delta_ref> <delta_dir> 
<gluten_bundle_jar>`. |
 | `apply-delta-test-patches.sh` | Cherry-picks upstream scan fixes, applies 
the ordered local patch list, and verifies the resulting test sources. Called 
by `setup-delta.sh` with `<delta_ref> <delta_dir>`. |
-| `patches/*.patch` | Separate patches for CDF plan assertions, mock-S3 
fixture writes, the two Parquet row-group fixtures, and 2B-row DV fail-fast 
behavior. Each patch documents its rationale and removal condition. |
+| `patches/*.patch` | Separate patches for CDF plan assertions, mock-S3 
fixture writes, Parquet row-group and MERGE file-count fixtures, and 2B-row DV 
fail-fast behavior. Each patch documents its rationale and removal condition. |
 
 ## Temporary Delta test patches
 
 Local workarounds live in `patches/`, one file per purpose. The patcher applies
 an explicit ordered list with `git apply` after the upstream cherry-picks,
-then verifies the expected row-count-scope and fail-fast counts.
+then verifies the expected fixture scopes and fail-fast counts.
 Patch paths are resolved relative to the script, independent of the caller's
 working directory. Missing patches, incompatible source context, or unexpected
 counts fail setup explicitly. Run through `setup-delta.sh` to reset the Delta
 checkout before applying the patches again.
 
+Validate patched Scala sources with Delta's `spark/testScalastyle` task as well
+as targeted `spark/testOnly` runs. `spark/test` invokes this style gate, but
+`testOnly` does not.
+
 The `dv-2b-row-fail-fast.patch` keeps the two memory-hog DV tests failing
 immediately rather than skipping them. Their known-failure entries remain
 enforced until the underlying native-memory issue is fixed.
 
+## Temporary MERGE file-count fixture workaround
+
+`patches/merge-delete-duplicate-file-layout.patch` scopes
+`spark.sql.files.minPartitionNum=1` to the unpartitioned, CDF-disabled
+`merge-metrics: delete-only with duplicates` case in `MergeIntoMetricsBase`.
+Its three touched native-written files can have equal sizes; scan packing can
+then put the surviving rows in separate tasks and correctly produce two files,
+while the test expects one. For this small fixture, the scoped setting packs
+the touched files together. It is not a general guarantee of one output file.
+
+The patch leaves the explicit input partitions, global default parallelism,
+native execution, metric assertions, and other test variants unchanged. The
+failure remains enforced, not quarantined. Remove the patch when the upstream
+test no longer depends on incidental file-size ordering and scan packing.
+
 ## Temporary CDF plan-assertion workaround
 
 Gluten's native file scans currently display `PushedFilters` without Spark's
@@ -104,7 +123,6 @@ apply to every suite:
 
 | Setting | Default |
 |---|---|
-| `spark.default.parallelism` | `1` |
 | `spark.sql.shuffle.partitions` | `5` |
 | `spark.unsafe.exceptionOnMemoryLeak` | `true` |
 | `spark.sql.ansi.enabled` | `false` |
@@ -113,6 +131,12 @@ apply to every suite:
 | `spark.databricks.delta.snapshotPartitions` | `2` |
 | `spark.gluten.sql.fallbackUnexpectedMetadataParquet` | `true` |
 
+The shared defaults leave `spark.default.parallelism` unset, preserving each
+Delta test context's upstream Spark default (normally two in 
`TestSparkSession`).
+Forcing one changes small `LocalTableScan` fixtures from two one-row files to
+one two-row file. That changes Delta DML candidate-file skipping for swapped
+temp-view projections and can change UPDATE/DELETE results even without Gluten.
+
 Suites can still override these defaults through their Spark configuration.
 In particular, ANSI-specific tests can enable ANSI explicitly.
 
diff --git a/.github/workflows/util/delta-spark-ut/apply-delta-test-patches.sh 
b/.github/workflows/util/delta-spark-ut/apply-delta-test-patches.sh
index a000eced1b..81464739ce 100755
--- a/.github/workflows/util/delta-spark-ut/apply-delta-test-patches.sh
+++ b/.github/workflows/util/delta-spark-ut/apply-delta-test-patches.sh
@@ -91,6 +91,7 @@ for patch in \
   mock-s3-fixture-writer.patch \
   parquet-fixture-row-groups.patch \
   dv-predicate-pushdown-row-groups.patch \
+  merge-delete-duplicate-file-layout.patch \
   dv-2b-row-fail-fast.patch; do
   echo "Applying $patch"
   if ! git -C "$DELTA_DIR" apply "$PATCH_DIR/$patch"; then
@@ -148,6 +149,35 @@ git -C "$DELTA_DIR" --no-pager diff -- \
   
"spark/src/test/scala/org/apache/spark/sql/delta/deletionvectors/DeletionVectorsSuite.scala"
 || true
 echo "::endgroup::"
 
+echo "::group::Checking duplicate-delete MERGE fixture scan packing"
+MERGE_METRICS="$DELTA_DIR/spark/src/test/scala/org/apache/spark/sql/delta/MergeIntoMetricsBase.scala"
+if [ ! -f "$MERGE_METRICS" ]; then
+  echo "Expected file not found in Delta clone: $MERGE_METRICS" >&2
+  echo "The Delta directory layout for ref '${DELTA_REF}' may have changed." 
>&2
+  exit 1
+fi
+MERGE_SCAN_GUARDS=$(
+  grep -Fxc \
+    '    val scanConf = if (!testConfig.partitioned && !testConfig.cdfEnabled) 
{' \
+    "$MERGE_METRICS" || true
+)
+MERGE_SCAN_SETTINGS=$(
+  grep -Fxc '      Seq("spark.sql.files.minPartitionNum" -> "1")' 
"$MERGE_METRICS" || true
+)
+MERGE_SCAN_SCOPES=$(
+  grep -Fxc '    withSQLConf(scanConf: _*) {' "$MERGE_METRICS" || true
+)
+if [ "$MERGE_SCAN_GUARDS" -ne 1 ] || [ "$MERGE_SCAN_SETTINGS" -ne 1 ] || \
+   [ "$MERGE_SCAN_SCOPES" -ne 1 ]; then
+  echo "ERROR: expected one guarded duplicate-delete MERGE scan scope;" \
+    "found ${MERGE_SCAN_GUARDS} guards, ${MERGE_SCAN_SETTINGS} settings," \
+    "and ${MERGE_SCAN_SCOPES} scopes." >&2
+  echo "MergeIntoMetricsBase may have changed in Delta ref '${DELTA_REF}'." >&2
+  exit 1
+fi
+echo "Scoped the duplicate-delete scan setting to the unpartitioned, 
CDF-disabled case."
+echo "::endgroup::"
+
 echo "::group::Checking DeletionVectorsSuite 2B-row fail-fast guards"
 
DVS="$DELTA_DIR/spark/src/test/scala/org/apache/spark/sql/delta/deletionvectors/DeletionVectorsSuite.scala"
 if [ ! -f "$DVS" ]; then
diff --git a/.github/workflows/util/delta-spark-ut/java-test-args.sh 
b/.github/workflows/util/delta-spark-ut/java-test-args.sh
index a985dc1fa7..684e76650b 100755
--- a/.github/workflows/util/delta-spark-ut/java-test-args.sh
+++ b/.github/workflows/util/delta-spark-ut/java-test-args.sh
@@ -45,6 +45,9 @@
 # Keep Delta's extensions and catalog suite-specific: some tests deliberately
 # omit them to check Delta's configuration errors.
 #
+# Preserve upstream SparkContext parallelism defaults: overriding them changes
+# small fixture file layouts and Delta DML data skipping for projected views.
+#
 # NOTE: no -Xmx here on purpose. JAVA_TOOL_OPTIONS is processed BEFORE the JVM
 # command line, so Delta's own -Xmx (build.sbt) would win; run-delta-tests.sh 
bumps
 # the forked-test-JVM heap via `set spark / Test / javaOptions ++= ...` 
instead.
@@ -73,7 +76,6 @@ export JAVA_TOOL_OPTIONS="\
 -Dspark.shuffle.manager=org.apache.spark.shuffle.sort.ColumnarShuffleManager \
 -Dspark.memory.offHeap.enabled=true \
 -Dspark.memory.offHeap.size=2g \
--Dspark.default.parallelism=1 \
 -Dspark.sql.shuffle.partitions=5 \
 -Dspark.unsafe.exceptionOnMemoryLeak=true \
 -Dspark.sql.ansi.enabled=false \
diff --git a/.github/workflows/util/delta-spark-ut/known-failures.txt 
b/.github/workflows/util/delta-spark-ut/known-failures.txt
index 99b64398b1..b0928a729e 100644
--- a/.github/workflows/util/delta-spark-ut/known-failures.txt
+++ b/.github/workflows/util/delta-spark-ut/known-failures.txt
@@ -34,21 +34,6 @@ io.delta.tables.DeltaTableHadoopOptionsSuite#restoreTable - 
with filesystem opti
 io.delta.tables.DeltaTableHadoopOptionsSuite#update - with filesystem options
 io.delta.tables.DeltaTableHadoopOptionsSuite#updateExpr - with filesystem 
options
 io.delta.tables.DeltaTableHadoopOptionsSuite#vacuum - with filesystem options
-org.apache.spark.sql.delta.AutoCompactExecutionIdColumnMappingSuite#auto-compact-enabled-conf:
 auto compact should kick in when enabled - session config - column mapping id 
mode
-org.apache.spark.sql.delta.AutoCompactExecutionIdColumnMappingSuite#auto-compact-enabled-property:
 auto compact should kick in when enabled - table config - column mapping id 
mode
-org.apache.spark.sql.delta.AutoCompactExecutionIdColumnMappingSuite#auto-compact-enabled-property:
 auto compact should not kick in when session config is off - column mapping id 
mode
-org.apache.spark.sql.delta.AutoCompactExecutionIdColumnMappingSuite#variant 
auto compact kicks in when enabled - session config - column mapping id mode
-org.apache.spark.sql.delta.AutoCompactExecutionIdColumnMappingSuite#variant 
auto compact kicks in when enabled - table config - column mapping id mode
-org.apache.spark.sql.delta.AutoCompactExecutionNameColumnMappingSuite#auto-compact-enabled-conf:
 auto compact should kick in when enabled - session config - column mapping 
name mode
-org.apache.spark.sql.delta.AutoCompactExecutionNameColumnMappingSuite#auto-compact-enabled-property:
 auto compact should kick in when enabled - table config - column mapping name 
mode
-org.apache.spark.sql.delta.AutoCompactExecutionNameColumnMappingSuite#auto-compact-enabled-property:
 auto compact should not kick in when session config is off - column mapping 
name mode
-org.apache.spark.sql.delta.AutoCompactExecutionNameColumnMappingSuite#variant 
auto compact kicks in when enabled - session config - column mapping name mode
-org.apache.spark.sql.delta.AutoCompactExecutionNameColumnMappingSuite#variant 
auto compact kicks in when enabled - table config - column mapping name mode
-org.apache.spark.sql.delta.AutoCompactExecutionSuite#auto-compact-enabled-conf:
 auto compact should kick in when enabled - session config
-org.apache.spark.sql.delta.AutoCompactExecutionSuite#auto-compact-enabled-property:
 auto compact should kick in when enabled - table config
-org.apache.spark.sql.delta.AutoCompactExecutionSuite#auto-compact-enabled-property:
 auto compact should not kick in when session config is off
-org.apache.spark.sql.delta.AutoCompactExecutionSuite#variant auto compact 
kicks in when enabled - session config
-org.apache.spark.sql.delta.AutoCompactExecutionSuite#variant auto compact 
kicks in when enabled - table config
 org.apache.spark.sql.delta.CheckpointsSuite#SC-86940: writing a GCS checkpoint 
should happen in a new thread
 org.apache.spark.sql.delta.CheckpointsWithCatalogOwnedBatch100Suite#SC-86940: 
writing a GCS checkpoint should happen in a new thread
 org.apache.spark.sql.delta.CheckpointsWithCatalogOwnedBatch1Suite#SC-86940: 
writing a GCS checkpoint should happen in a new thread
@@ -61,8 +46,6 @@ 
org.apache.spark.sql.delta.CloneTableScalaDeletionVectorSuite#shallow clone acro
 org.apache.spark.sql.delta.CloneTableScalaSuite#shallow clone across file 
systems
 org.apache.spark.sql.delta.ConvertToDeltaSQLSuite#CONVERT keeps NaN rows for 
finite-threshold predicate (NaN-excluding writer)
 org.apache.spark.sql.delta.ConvertToDeltaScalaSuite#CONVERT keeps NaN rows for 
finite-threshold predicate (NaN-excluding writer)
-org.apache.spark.sql.delta.DeleteMetricsSuite#delete-metrics: delete one row 
per file - Partitioned = false, cdfEnabled = false
-org.apache.spark.sql.delta.DeleteMetricsSuite#delete-metrics: delete one row 
per file - Partitioned = false, cdfEnabled = true
 org.apache.spark.sql.delta.DeltaColumnMappingSuite#explicit id matching
 org.apache.spark.sql.delta.DeltaDataFrameHadoopOptionsSuite#SC-86916: Delta 
log cache should respect options
 org.apache.spark.sql.delta.DeltaDataFrameHadoopOptionsSuite#SC-86916: 
checkpoint should pick up Hadoop file system options
@@ -71,19 +54,10 @@ 
org.apache.spark.sql.delta.DeltaDataFrameHadoopOptionsSuite#SC-86916: read/write
 org.apache.spark.sql.delta.DeltaDataFrameHadoopOptionsSuite#all operations 
should propagate Hadoop file system options
 org.apache.spark.sql.delta.DeltaDataFrameHadoopOptionsSuite#operations without 
Hadoop options should fail for fake:// filesystem
 org.apache.spark.sql.delta.DeltaGenerateSymlinkManifestSuite#incremental 
manifest: failure to generate manifest throws exception
-org.apache.spark.sql.delta.DeltaGenerateSymlinkManifestSuite#special partition 
column values
-org.apache.spark.sql.delta.DeltaHistoryManagerSuite#data skipping still works 
with time travel
-org.apache.spark.sql.delta.DeltaHistoryManagerWithCatalogOwnedBatch100Suite#data
 skipping still works with time travel
-org.apache.spark.sql.delta.DeltaHistoryManagerWithCatalogOwnedBatch1Suite#data 
skipping still works with time travel
-org.apache.spark.sql.delta.DeltaHistoryManagerWithCatalogOwnedBatch2Suite#data 
skipping still works with time travel
 org.apache.spark.sql.delta.DeltaInsertIntoDataFrameByPathSuite#insertInto: 
timestamp partition values with different precisions
 org.apache.spark.sql.delta.DeltaInsertIntoDataFrameSuite#insertInto: timestamp 
partition values with different precisions
 org.apache.spark.sql.delta.DeltaInsertIntoSQLByPathSuite#insertInto: timestamp 
partition values with different precisions
 org.apache.spark.sql.delta.DeltaInsertIntoSQLSuite#insertInto: timestamp 
partition values with different precisions
-org.apache.spark.sql.delta.DeltaLimitPushDownV1Suite#non-deterministic 
predicates are incorrectly pushed down with limit (gate off, legacy)
-org.apache.spark.sql.delta.DeltaLimitPushDownWithCatalogOwnedBatch100Suite#non-deterministic
 predicates are incorrectly pushed down with limit (gate off, legacy)
-org.apache.spark.sql.delta.DeltaLimitPushDownWithCatalogOwnedBatch1Suite#non-deterministic
 predicates are incorrectly pushed down with limit (gate off, legacy)
-org.apache.spark.sql.delta.DeltaLimitPushDownWithCatalogOwnedBatch2Suite#non-deterministic
 predicates are incorrectly pushed down with limit (gate off, legacy)
 org.apache.spark.sql.delta.DeltaLiteVacuumSuite#vacuum for cdc - delete 
tombstones
 org.apache.spark.sql.delta.DeltaLiteVacuumSuite#vacuum for cdc - update/merge
 
org.apache.spark.sql.delta.DeltaParquetFileFormatWithPredicatePushdownSuite#read
 DV metadata columns: with rowIndexFilterType=IF_CONTAINED, with vectorized 
Parquet reader=false, with readColumnarBatchAsRows=true
@@ -94,27 +68,19 @@ 
org.apache.spark.sql.delta.DeltaParquetFileFormatWithPredicatePushdownSuite#read
 
org.apache.spark.sql.delta.DeltaParquetFileFormatWithPredicatePushdownSuite#read
 DV metadata columns: with rowIndexFilterType=IF_NOT_CONTAINED, with vectorized 
Parquet reader=true, with readColumnarBatchAsRows=true
 org.apache.spark.sql.delta.DeltaSinkIdColumnMappingSuite#partitioned writing 
and batch reading - column mapping id mode
 org.apache.spark.sql.delta.DeltaSinkNameColumnMappingSuite#partitioned writing 
and batch reading - column mapping name mode
-org.apache.spark.sql.delta.DeltaSuite#SC-8810: skip deleted file
 org.apache.spark.sql.delta.DeltaSuite#SC-8810: skipping deleted file still 
throws on corrupted file
 org.apache.spark.sql.delta.DeltaSuite#all operations with special characters 
in path
 org.apache.spark.sql.delta.DeltaSuite#deleted files cause failure by default
 org.apache.spark.sql.delta.DeltaTableCreationSuite#Default column values: 
CONVERT TO DELTA keeps EXISTS_DEFAULT
 org.apache.spark.sql.delta.DeltaVacuumSuite#vacuum for cdc - delete tombstones
 org.apache.spark.sql.delta.DeltaVacuumSuite#vacuum for cdc - update/merge
-org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch100Suite#SC-8810: skip 
deleted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch100Suite#SC-8810: 
skipping deleted file still throws on corrupted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch100Suite#deleted files 
cause failure by default
-org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch1Suite#SC-8810: skip 
deleted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch1Suite#SC-8810: skipping 
deleted file still throws on corrupted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch1Suite#deleted files 
cause failure by default
-org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch2Suite#SC-8810: skip 
deleted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch2Suite#SC-8810: skipping 
deleted file still throws on corrupted file
 org.apache.spark.sql.delta.DeltaWithCatalogOwnedBatch2Suite#deleted files 
cause failure by default
-org.apache.spark.sql.delta.DescribeDeltaHistorySuite#operation metrics - merge
-org.apache.spark.sql.delta.DescribeDeltaHistoryWithCatalogOwnedBatch100Suite#operation
 metrics - merge
 org.apache.spark.sql.delta.FeatureEnablementConcurrencySuite#Enable column 
mapping feature - txnInterleaved: true
-org.apache.spark.sql.delta.FileSizeHistogramSuite#check CommitStats with 
deletes
-org.apache.spark.sql.delta.FileSizeHistogramSuite#histogram is re-calculated 
when files are removed
 org.apache.spark.sql.delta.HDFSLogStoreSuite#No AbstractFileSystem - end to 
end test using data frame
 org.apache.spark.sql.delta.ImplicitMergeCastingSuite#MERGE overflow in WHEN 
MATCHED THEN UPDATE SET t.value = s.value sourceType: ARRAY<BIGINT>, 
targetType: ARRAY<INT> followAnsiEnabled: true, ansiEnabled: true, 
storeAssignmentPolicy: ANSI
 org.apache.spark.sql.delta.ImplicitMergeCastingSuite#MERGE overflow in WHEN 
MATCHED THEN UPDATE SET t.value = s.value sourceType: ARRAY<BIGINT>, 
targetType: ARRAY<INT> followAnsiEnabled: true, ansiEnabled: true, 
storeAssignmentPolicy: LEGACY
@@ -157,35 +123,6 @@ 
org.apache.spark.sql.delta.ImplicitStreamingMergeCastingSuite#Streaming MERGE ov
 org.apache.spark.sql.delta.ImplicitStreamingMergeCastingSuite#Streaming MERGE 
overflow sourceType: Struct<value:BIGINT>, targetType: Struct<value:INT> 
followAnsiEnabled: true, ansiEnabled: true, storeAssignmentPolicy: ANSI
 org.apache.spark.sql.delta.ImplicitStreamingMergeCastingSuite#Streaming MERGE 
overflow sourceType: Struct<value:BIGINT>, targetType: Struct<value:INT> 
followAnsiEnabled: true, ansiEnabled: true, storeAssignmentPolicy: LEGACY
 org.apache.spark.sql.delta.PublicHDFSLogStoreSuite#No AbstractFileSystem - end 
to end test using data frame
-org.apache.spark.sql.delta.RestoreTableSQLSuite#cdf + RESTORE
-org.apache.spark.sql.delta.RestoreTableSQLSuite#restore command output metrics
-org.apache.spark.sql.delta.RestoreTableSQLSuite#restore operation metrics in 
Delta table history
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch100Suite#restore
 command output metrics
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch100Suite#restore
 operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch1Suite#restore 
command output metrics
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch1Suite#restore 
operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch2Suite#restore 
command output metrics
-org.apache.spark.sql.delta.RestoreTableSQLWithCatalogOwnedBatch2Suite#restore 
operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableScalaDeletionVectorSuite#restore 
command output metrics
-org.apache.spark.sql.delta.RestoreTableScalaDeletionVectorSuite#restore 
operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableScalaSuite#cdf + RESTORE
-org.apache.spark.sql.delta.RestoreTableScalaSuite#restore command output 
metrics
-org.apache.spark.sql.delta.RestoreTableScalaSuite#restore operation metrics in 
Delta table history
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch100Suite#restore
 command output metrics
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch100Suite#restore
 operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch1Suite#restore
 command output metrics
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch1Suite#restore
 operation metrics in Delta table history
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch2Suite#restore
 command output metrics
-org.apache.spark.sql.delta.RestoreTableScalaWithCatalogOwnedBatch2Suite#restore
 operation metrics in Delta table history
-org.apache.spark.sql.delta.SnapshotManagementSuite#recover from a corrupt 
checkpoint: previous checkpoint doesn't exist
-org.apache.spark.sql.delta.SnapshotManagementSuite#should not recover when 
both the current and previous checkpoints are broken
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch100Suite#recover
 from a corrupt checkpoint: previous checkpoint doesn't exist
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch100Suite#should
 not recover when both the current and previous checkpoints are broken
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch1Suite#recover
 from a corrupt checkpoint: previous checkpoint doesn't exist
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch1Suite#should
 not recover when both the current and previous checkpoints are broken
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch2Suite#recover
 from a corrupt checkpoint: previous checkpoint doesn't exist
-org.apache.spark.sql.delta.SnapshotManagementWithCatalogManagedBatch2Suite#should
 not recover when both the current and previous checkpoints are broken
-org.apache.spark.sql.delta.UpdateMetricsSuite#update-metrics: update one row 
per file - Partitioned = false, cdfEnabled = false
 
org.apache.spark.sql.delta.coordinatedcommits.CoordinatedCommitsSuite#Incomplete
 backfills are handled properly by next commit after CC to FS conversion
 org.apache.spark.sql.delta.deletionvectors.DeletionVectorsSuite#huge table: 
delete a small number of rows from tables of 2B rows with DVs
 org.apache.spark.sql.delta.deletionvectors.DeletionVectorsSuite#huge table: 
read from tables of 2B rows with existing DV of many zeros
@@ -231,65 +168,14 @@ 
org.apache.spark.sql.delta.generatedsuites.dataskipping.DataSkippingDeltaV1WithC
 
org.apache.spark.sql.delta.generatedsuites.dataskipping.DataSkippingDeltaV1WithCatalogOwnedBatch1Suite#data
 skipping flags - old behavior with DataFrame schema
 
org.apache.spark.sql.delta.generatedsuites.dataskipping.DataSkippingDeltaV1WithCatalogOwnedBatch2Suite#data
 skipping flags
 
org.apache.spark.sql.delta.generatedsuites.dataskipping.DataSkippingDeltaV1WithCatalogOwnedBatch2Suite#data
 skipping flags - old behavior with DataFrame schema
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLNameBasedSuite#test
 delete on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLNameBasedSuite#test
 delete on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedCDCOnSuite#test
 delete on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedCDCOnSuite#test
 delete on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedDVPredPushOffSuite#test
 delete on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedDVPredPushOffSuite#test
 delete on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedDVPredPushOnSuite#test
 delete on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedDVPredPushOnSuite#test
 delete on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedSuite#test
 delete on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.delete.DeleteTempViewSQLPathBasedSuite#test
 delete on temp view - nontrivial projection - SQL TempView
 
org.apache.spark.sql.delta.generatedsuites.delete.RowTrackingDeleteSuiteBaseCDCOnDVOffSuite#DELETE
 with optimized writes preserves Row ID, isPartitioned=true
 
org.apache.spark.sql.delta.generatedsuites.delete.RowTrackingDeleteSuiteBaseDVOffSuite#DELETE
 with optimized writes preserves Row ID, isPartitioned=true
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOffSuite#Merge
 with DVs metrics - Incremental Updates
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOffSuite#Merge
 with DVs metrics - delete entire file
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOffSuite#Verify
 error is produced when paths are not joined correctly
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOnSuite#Merge
 with DVs metrics - Incremental Updates
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOnSuite#Merge
 with DVs metrics - delete entire file
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedCDCOnDVsPredPushOnSuite#Verify
 error is produced when paths are not joined correctly
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOffSuite#Merge
 with DVs metrics - Incremental Updates
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOffSuite#Merge
 with DVs metrics - delete entire file
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOffSuite#Verify
 error is produced when paths are not joined correctly
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOnSuite#Merge
 with DVs metrics - Incremental Updates
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOnSuite#Merge
 with DVs metrics - delete entire file
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoDVsSQLPathBasedDVsPredPushOnSuite#Verify
 error is produced when paths are not joined correctly
 
org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoExtendedSyntaxSQLInMemoryTableNameBasedSuite#extended
 syntax - conditional update + conditional delete + conditional insert with 
multiple matches
 
org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoExtendedSyntaxSQLInMemoryTableNameBasedSuite#extended
 syntax - conditional update + conditional delete with multiple matches
 
org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoExtendedSyntaxSQLInMemoryTableNameBasedSuite#extended
 syntax - only conditional delete with multiple matches
 
org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoExtendedSyntaxSQLInMemoryTableNameBasedSuite#extended
 syntax - only conditional update with multiple matches
 
org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoExtendedSyntaxSQLInMemoryTableNameBasedSuite#extended
 syntax - only update with multiple matches
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLNameBasedSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedCDCOnDVsPredPushOffSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedCDCOnDVsPredPushOffSuite#merge
 with repartition - partition on multiple columns
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedCDCOnDVsPredPushOnSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedCDCOnDVsPredPushOnSuite#merge
 with repartition - partition on multiple columns
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedCDCOnSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedDVsPredPushOffSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedDVsPredPushOffSuite#merge
 with repartition - partition on multiple columns
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedDVsPredPushOnSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedDVsPredPushOnSuite#merge
 with repartition - partition on multiple columns
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscSQLPathBasedSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.merge.MergeIntoSuiteBaseMiscScalaSuite#merge
 with repartition - insert only merge
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLNameBasedSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLNameBasedSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnDVSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnDVSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnRowTrackingOffSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnRowTrackingOffSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedCDCOnSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedDVPredPushOffSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedDVPredPushOffSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedDVPredPushOnSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedDVPredPushOnSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedRowTrackingOffSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedRowTrackingOffSuite#test
 update on temp view - nontrivial projection - SQL TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedSuite#test
 update on temp view - nontrivial projection - Dataset TempView
-org.apache.spark.sql.delta.generatedsuites.update.UpdateBaseTempViewSQLPathBasedSuite#test
 update on temp view - nontrivial projection - SQL TempView
 org.apache.spark.sql.delta.optimize.OptimizeMetricsSuite#optimize ZOrderBy 
operation metrics in Delta table history
-org.apache.spark.sql.delta.optimize.OptimizeMetricsSuite#optimize metrics on 
idempotent operations
 org.apache.spark.sql.delta.perf.OptimizeGeneratedColumnSuite#end-to-end test 
of behaviors of write/read null on partition column
 org.apache.spark.sql.delta.perf.OptimizeGeneratedColumnSuite#five digits year 
in a date_format yyyy-MM partition column
 org.apache.spark.sql.delta.perf.OptimizeGeneratedColumnSuite#five digits year 
in a date_format yyyy-MM-dd-HH partition column
diff --git 
a/.github/workflows/util/delta-spark-ut/patches/merge-delete-duplicate-file-layout.patch
 
b/.github/workflows/util/delta-spark-ut/patches/merge-delete-duplicate-file-layout.patch
new file mode 100644
index 0000000000..1d3ece3e64
--- /dev/null
+++ 
b/.github/workflows/util/delta-spark-ut/patches/merge-delete-duplicate-file-layout.patch
@@ -0,0 +1,69 @@
+Subject: [PATCH] Stabilize the unpartitioned duplicate-delete MERGE fixture
+
+The unpartitioned, CDF-disabled "delete-only with duplicates" metric test
+expects one output file. Its three touched native-written Parquet files can
+have equal sizes, so size-based scan packing can place the two surviving
+row ranges in different tasks and correctly produce two output files.
+
+Scope spark.sql.files.minPartitionNum=1 to this case's helper call. For this
+small fixture, the scan packs all three touched files together without
+changing the explicit input partitions, global default parallelism, native
+write path, or metric assertions. Partitioned and CDF-enabled cases retain
+their original configuration.
+
+Remove this workaround when the upstream test no longer assumes an output
+file count determined by incidental file-size ordering and scan packing.
+
+diff --git 
a/spark/src/test/scala/org/apache/spark/sql/delta/MergeIntoMetricsBase.scala 
b/spark/src/test/scala/org/apache/spark/sql/delta/MergeIntoMetricsBase.scala
+--- 
a/spark/src/test/scala/org/apache/spark/sql/delta/MergeIntoMetricsBase.scala
++++ 
b/spark/src/test/scala/org/apache/spark/sql/delta/MergeIntoMetricsBase.scala
+@@ -1025,23 +1025,32 @@ trait MergeIntoMetricsBase
+       "numTargetFilesAdded" -> 2,
+       "numTargetFilesRemoved" -> 3
+     )
+-    runMergeCmdAndTestMetrics(
+-      targetDf = targetDf,
+-      sourceDf = sourceDf,
+-      mergeCmdFn = mergeCmdFn,
+-      expectedOpMetrics = expectedOpMetrics,
+-      testConfig = testConfig,
+-      // When cdf=true in this test we hit the corner case where there are 
duplicate matches with a
+-      // delete clause and we generate duplicate cdc data. This is further 
detailed in
+-      // MergeIntoCommand at the definition of 
isDeleteWithDuplicateMatchesAndCdc. Our fix for this
+-      // scenario includes deduplicating the output data which reshuffles the 
output data.
+-      // Thus when the table is not partitioned, the data is rewritten into 1 
new file rather than 2
+-      overrideExpectedOpMetrics = Seq(
+-        ((false, true), ("numTargetFilesAdded", 1)),
+-        ((false, false), (
+-          "numTargetFilesAdded",
+-          1)
++    // Keep the one-file assertion independent of equal-sized native fixture 
files.
++    val scanConf = if (!testConfig.partitioned && !testConfig.cdfEnabled) {
++      Seq("spark.sql.files.minPartitionNum" -> "1")
++    } else {
++      Seq.empty[(String, String)]
++    }
++    withSQLConf(scanConf: _*) {
++      runMergeCmdAndTestMetrics(
++        targetDf = targetDf,
++        sourceDf = sourceDf,
++        mergeCmdFn = mergeCmdFn,
++        expectedOpMetrics = expectedOpMetrics,
++        testConfig = testConfig,
++        // When cdf=true in this test we hit the corner case where there are 
duplicate matches
++        // with a delete clause and we generate duplicate cdc data. This is 
further detailed in
++        // MergeIntoCommand at the definition of 
isDeleteWithDuplicateMatchesAndCdc. Our fix for
++        // this scenario includes deduplicating the output data which 
reshuffles the output data.
++        // Thus when the table is not partitioned, the data is rewritten into 
1 new file rather
++        // than 2
++        overrideExpectedOpMetrics = Seq(
++          ((false, true), ("numTargetFilesAdded", 1)),
++          ((false, false), (
++            "numTargetFilesAdded",
++            1)
++          )
+         )
+       )
+-    )
++    }
+   }}
diff --git a/.github/workflows/velox_backend_x86.yml 
b/.github/workflows/velox_backend_x86.yml
index f0cfd983b6..3f8c362cd1 100644
--- a/.github/workflows/velox_backend_x86.yml
+++ b/.github/workflows/velox_backend_x86.yml
@@ -1016,7 +1016,7 @@ jobs:
           else
             $PARALLEL_UT $MVN_CMD clean test -Pspark-3.5 -Pjava-17 
-Pbackends-velox -Piceberg -Pdelta -Phudi -Ppaimon -Pspark-ut \
             -DargLine="-Dspark.test.home=/opt/shims/spark35/spark_home/" 
-DtagsToExclude="$TAGS_EXCLUDE" \
-            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim"
+            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim,org.apache.spark.sql.delta.GlutenDeltaStats"
           fi
       - name: Upload test report
         if: always()
@@ -1091,7 +1091,7 @@ jobs:
           else
             $PARALLEL_UT $MVN_CMD clean test -Pspark-3.5 -Pscala-2.13 
-Pjava-17 -Pbackends-velox -Piceberg -Pdelta -Pspark-ut \
             
-DargLine="-Dspark.test.home=/opt/shims/spark35-scala-2.13/spark_home/" 
-DtagsToExclude="$TAGS_EXCLUDE" \
-            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim"
+            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim,org.apache.spark.sql.delta.GlutenDeltaStats"
           fi
       - name: Upload test report
         if: always()
@@ -1475,7 +1475,7 @@ jobs:
           else
             $PARALLEL_UT $MVN_CMD clean test -Pspark-4.0 -Pscala-2.13 
-Pjava-17 -Pbackends-velox -Pdelta -Ppaimon -Pspark-ut \
             -DargLine="-Dspark.test.home=/opt/shims/spark40/spark_home/" 
-DtagsToExclude="$TAGS_EXCLUDE" \
-            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim"
+            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim,org.apache.spark.sql.delta.GlutenDeltaStats"
           fi
       - name: Upload test report
         if: always()
@@ -1607,7 +1607,7 @@ jobs:
             # Group 3: top-level sql, connector, sources, hive and remaining 
tests (~205 classes)
             $PARALLEL_UT $MVN_CMD clean test -Pspark-4.1 -Pscala-2.13 
-Pjava-17 -Pbackends-velox -Pspark-ut -Pdelta \
             -DargLine="-Dspark.test.home=/opt/shims/spark41/spark_home/" 
-DtagsToExclude="$TAGS_EXCLUDE" \
-            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim"
+            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim,org.apache.spark.sql.delta.GlutenDeltaStats"
           fi
       - name: Upload test report
         if: always()
@@ -1743,7 +1743,7 @@ jobs:
             # Group 3: top-level sql, connector, sources, hive and remaining 
tests (~205 classes)
             $PARALLEL_UT $MVN_CMD clean test -Pspark-4.2 -Pscala-2.13 
-Pjava-17 -Pbackends-velox -Pspark-ut -Pdelta \
             -DargLine="-Dspark.test.home=/opt/shims/spark42/spark_home/" 
-DtagsToExclude="$TAGS_EXCLUDE" \
-            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim"
+            
-DwildcardSuites="org.apache.spark.sql.GlutenSQL,org.apache.spark.sql.Gluten,org.apache.spark.sql.connector,org.apache.spark.sql.sources,org.apache.spark.sql.hive,org.apache.spark.sql.gluten,org.apache.spark.sql.shim,org.apache.spark.sql.delta.GlutenDeltaStats"
           fi
       - name: Upload test report
         if: always()
diff --git 
a/backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
 
b/backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
index dd4baa5b3a..bc2fe303a7 100644
--- 
a/backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
+++ 
b/backends-velox/src-delta33/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
@@ -44,6 +44,7 @@ import 
org.apache.spark.sql.execution.aggregate.SortAggregateExec
 import org.apache.spark.sql.execution.datasources.{BasicWriteJobStatsTracker, 
WriteJobStatsTracker, WriteTaskStats, WriteTaskStatsTracker}
 import org.apache.spark.sql.execution.metric.SQLMetric
 import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.task.TaskResources
 import org.apache.spark.util.{SerializableConfiguration, SparkDirectoryUtil, 
Utils}
 
 import com.google.common.collect.Lists
@@ -51,7 +52,7 @@ import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.fs.Path
 
 import java.util.UUID
-import java.util.concurrent.{Callable, Executors, Future, SynchronousQueue}
+import java.util.concurrent.{Callable, Executors, Future, SynchronousQueue, 
TimeUnit}
 
 import scala.collection.JavaConverters._
 import scala.collection.mutable
@@ -223,6 +224,33 @@ object GlutenDeltaJobStatsTracker extends Logging {
     private var currentPath: String = _
     private var currentJsonFuture: Future[String] = _
 
+    // Registered after TaskResources, so Spark's reverse listener order stops 
the worker first.
+    // A recycler holds the registry lock, which the worker may need to wrap 
its output batch.
+    taskContext.addTaskCompletionListener[Unit] {
+      _ =>
+        Option(currentJsonFuture).foreach(_.cancel(true))
+        resultThreadRunner.shutdownNow()
+        var interrupted = false
+        try {
+          while (!resultThreadRunner.isTerminated) {
+            try {
+              resultThreadRunner.awaitTermination(Long.MaxValue, 
TimeUnit.NANOSECONDS)
+            } catch {
+              case _: InterruptedException => interrupted = true
+            }
+          }
+          try {
+            veloxAggTask.close()
+          } finally {
+            c2r.close()
+          }
+        } finally {
+          if (interrupted) {
+            Thread.currentThread().interrupt()
+          }
+        }
+    }
+
     override def newPartition(partitionValues: InternalRow): Unit = {}
 
     override def newFile(filePath: String): Unit = {
@@ -235,22 +263,28 @@ object GlutenDeltaJobStatsTracker extends Logging {
         override def call(): String = {
           Thread.currentThread().setName(resultThreadName)
           TaskContext.setTaskContext(taskContext)
-          val outBatches = veloxAggTask.asScala.toSeq
-          val row: InternalRow = if (outBatches.isEmpty) {
-            // No input was received. Returns the default aggregation values.
-            emptyRow
-          } else {
-            assert(outBatches.size == 1)
-            val batch = outBatches.head
-            val rows = c2r.toRowIterator(batch).toSeq
-            assert(
-              rows.size == 1,
-              "Only one single output row is expected from the global 
aggregation.")
-            batch.close()
-            rows.head
+          try {
+            val batch = if (veloxAggTask.hasNext) Some(veloxAggTask.next()) 
else None
+            try {
+              val row: InternalRow = batch match {
+                case None =>
+                  // No input was received. Returns the default aggregation 
values.
+                  emptyRow
+                case Some(output) =>
+                  assert(!veloxAggTask.hasNext)
+                  val rows = c2r.toRowIterator(output).toSeq
+                  assert(
+                    rows.size == 1,
+                    "Only one single output row is expected from the global 
aggregation.")
+                  rows.head
+              }
+              getStats(row).getString(0)
+            } finally {
+              batch.foreach(_.close())
+            }
+          } finally {
+            TaskContext.unset()
           }
-          val jsonStats = getStats(row).getString(0)
-          jsonStats
         }
         currentPath = filePath
       })
@@ -288,7 +322,15 @@ object GlutenDeltaJobStatsTracker extends Logging {
           // Counts up the reference count for the batch since it
           // will be consumed by Velox aggregation task asynchronously.
           ColumnarBatches.retain(batch)
-          inputBatchQueue.put(Some(batch))
+          var transferred = false
+          try {
+            inputBatchQueue.put(Some(batch))
+            transferred = true
+          } finally {
+            if (!transferred) {
+              batch.close()
+            }
+          }
       }
     }
 
@@ -299,12 +341,17 @@ object GlutenDeltaJobStatsTracker extends Logging {
     }
 
     private def newIteratorFromInputQueue(): ColumnarBatchInIterator = {
+      var batch: ColumnarBatch = null
+      TaskResources.addRecycler("GlutenDeltaStatsBufferedInput", 100) {
+        if (batch != null) {
+          batch.close()
+          batch = null
+        }
+      }
       val itr = new ColumnarBatchInIterator(
         BackendsApiManager.getBackendName,
         Iterators
           .wrap(new Iterator[ColumnarBatch] {
-            private var batch: ColumnarBatch = _
-
             override def hasNext: Boolean = {
               assert(batch == null)
               while (!Thread.currentThread().isInterrupted) {
diff --git 
a/backends-velox/src-delta33/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
 
b/backends-velox/src-delta33/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
new file mode 100644
index 0000000000..55a92b942b
--- /dev/null
+++ 
b/backends-velox/src-delta33/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
@@ -0,0 +1,247 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.spark.sql.delta
+
+import org.apache.gluten.config.{GlutenConfig, VeloxDeltaConfig}
+import org.apache.gluten.execution.HashAggregateExecTransformer
+
+import org.apache.spark.{SparkConf, TaskContext}
+import org.apache.spark.sql.{GlutenQueryTest, Row, SparkSession}
+import org.apache.spark.sql.catalyst.expressions.ScalaUDF
+import org.apache.spark.sql.catalyst.plans.logical.Aggregate
+import org.apache.spark.sql.delta.actions.Metadata
+import org.apache.spark.sql.delta.schema.InvariantViolationException
+import org.apache.spark.sql.delta.stats.{DeltaJobStatisticsTracker, 
GlutenDeltaJobStatsTracker}
+import org.apache.spark.sql.execution.SparkPlan
+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.task.{TaskResourceRegistry, TaskResources}
+
+import org.apache.hadoop.fs.Path
+
+import java.lang.management.ManagementFactory
+import java.util.concurrent.{ConcurrentLinkedQueue, CountDownLatch, TimeUnit}
+import java.util.concurrent.atomic.{AtomicBoolean, AtomicReference}
+
+import scala.collection.JavaConverters._
+import scala.concurrent.duration._
+import scala.util.control.NonFatal
+
+class GlutenDeltaStatsLifecycleSuite extends GlutenQueryTest with 
SharedSparkSession {
+  import testImplicits._
+
+  override protected def sparkConf: SparkConf = {
+    super.sparkConf
+      .set("spark.plugins", "org.apache.gluten.GlutenPlugin")
+      .set("spark.shuffle.manager", 
"org.apache.spark.shuffle.sort.ColumnarShuffleManager")
+      .set("spark.default.parallelism", "2")
+      .set("spark.memory.offHeap.enabled", "true")
+      .set("spark.memory.offHeap.size", "1024MB")
+      .set("spark.ui.enabled", "false")
+      .set(GlutenConfig.GLUTEN_UI_ENABLED.key, "false")
+      .set("spark.sql.extensions", "io.delta.sql.DeltaSparkSessionExtension")
+      .set("spark.sql.catalog.spark_catalog", 
"org.apache.spark.sql.delta.catalog.DeltaCatalog")
+      .set(VeloxDeltaConfig.ENABLE_NATIVE_WRITE.key, "true")
+      .set("spark.databricks.delta.stats.collect", "true")
+      .set("spark.databricks.delta.optimizeWrite.enabled", "false")
+      
.set("spark.databricks.delta.properties.defaults.writePartitionColumnsToParquet",
 "false")
+      .set("spark.databricks.delta.snapshotPartitions", "1")
+      .set("spark.sql.ansi.enabled", "false")
+      .set(GlutenConfig.GLUTEN_ANSI_FALLBACK_ENABLED.key, "false")
+  }
+
+  private def statisticsThreads: Set[Long] =
+    Thread.getAllStackTraces.keySet().asScala
+      .filter(_.getName.startsWith("Gluten Delta Statistics Writer - "))
+      .map(_.getId)
+      .toSet
+
+  private def withNativeStatistics(path: String)(write: => Unit): Unit = {
+    val before = statisticsThreads
+    val plans = new ConcurrentLinkedQueue[SparkPlan]()
+    val completionChecks = new ConcurrentLinkedQueue[() => Unit]()
+    val observer: (Path, SparkPlan) => Unit = (statsPath, plan) => {
+      if (statsPath.toUri.getPath == path) {
+        plans.add(plan)
+        val context = TaskContext.get()
+        val usage = TaskResources.getSharedUsage()
+        completionChecks.add(
+          () => {
+            assert(context.isCompleted())
+            assert(usage.current() == 0)
+          })
+      }
+    }
+    GlutenDeltaJobStatsTracker.withStatsPlanObserver(observer) {
+      write
+    }
+    assert(!plans.isEmpty, "The write did not exercise native Delta 
statistics")
+    plans.asScala.foreach {
+      plan =>
+        assert(
+          plan.exists(_.isInstanceOf[HashAggregateExecTransformer]),
+          s"Expected a native statistics aggregate, but 
got:\n${plan.treeString}")
+    }
+    eventually(timeout(15.seconds), interval(100.millis)) {
+      completionChecks.asScala.foreach(_())
+      assert(statisticsThreads.diff(before).isEmpty, "Statistics workers 
survived task completion")
+    }
+  }
+
+  test("aborted Delta writes close native statistics before task runtimes") {
+    withTempDir {
+      dir =>
+        val path = dir.getCanonicalPath
+        val schema = new StructType().add("id", LongType, nullable = false)
+        DeltaLog.forTable(spark, path).startTransaction()
+          .commit(Seq(Metadata(schemaString = schema.json)), 
DeltaOperations.ManualUpdate)
+        
spark.read.format("delta").load(path).write.format("delta").mode("overwrite").save(path)
+        val invalid = spark.createDataFrame(Seq(Row(1L), Row(null)).asJava, 
schema.asNullable)
+        withNativeStatistics(path) {
+          val failure = intercept[Exception] {
+            invalid.write.format("delta").mode("append").save(path)
+          }
+          assert(
+            Iterator.iterate[Throwable](failure)(_.getCause).takeWhile(_ != 
null)
+              .exists(_.isInstanceOf[InvariantViolationException]),
+            failure.toString)
+        }
+        assert(spark.read.format("delta").load(path).count() == 0)
+        withNativeStatistics(path) {
+          Seq(2L, 
3L).toDF("id").write.format("delta").mode("append").save(path)
+        }
+        assert(spark.read.format("delta").load(path).collect().toSet == 
Set(Row(2L), Row(3L)))
+    }
+  }
+
+  test("multi-file Delta statistics close workers after a successful task") {
+    withTempDir {
+      dir =>
+        val path = dir.getCanonicalPath
+        withNativeStatistics(path) {
+          Seq((0L, 0), (1L, 0), (2L, 0), (3L, 0)).toDF("id", 
"part").coalesce(1)
+            
.write.format("delta").partitionBy("part").option("maxRecordsPerFile", "1")
+            .save(path)
+        }
+        val files = DeltaLog.forTable(spark, path).update().allFiles.collect()
+        assert(files.length == 4)
+        val records = spark.read.json(files.map(_.stats).toSeq.toDS())
+          .select("numRecords").as[Long].collect()
+        assert(records.length == 4 && records.forall(_ == 1))
+    }
+  }
+
+  test("canceled statistics workers can access task resources before cleanup") 
{
+    val workerReady = new CountDownLatch(1)
+    val registryAccessed = new AtomicBoolean(false)
+    val resourceReleased = new AtomicBoolean(false)
+    val cancellationPreserved = new AtomicBoolean(false)
+    val taskThread = new AtomicReference[Thread]()
+    val failures = new ConcurrentLinkedQueue[Throwable]()
+    val completionChecks = new ConcurrentLinkedQueue[() => Unit]()
+    val aggregate = spark.range(1).selectExpr(
+      "to_json(named_struct('numRecords', count(*))) AS stats")
+      .queryExecution.analyzed.collectFirst { case a: Aggregate => a }.get
+    val checkRegistryOnCancel: String => String = json => {
+      try {
+        assert(Thread.currentThread().getName.startsWith("Gluten Delta 
Statistics Writer - "))
+        workerReady.countDown()
+        intercept[InterruptedException] {
+          new CountDownLatch(1).await(30, TimeUnit.SECONDS)
+        }
+        // Detect the lock cycle before acquiring the monitor, so a regression 
fails, not hangs.
+        val owner = ManagementFactory.getThreadMXBean
+          .getThreadInfo(Array(taskThread.get().getId), true, false).head
+        assert(
+          !owner.getLockedMonitors.exists(
+            _.getClassName == classOf[TaskResourceRegistry].getName),
+          "Statistics cleanup is waiting for its worker while holding the task 
resource registry"
+        )
+        TaskResources.addRecycler("statistics cancellation probe", 100) {
+          resourceReleased.set(true)
+        }
+        registryAccessed.set(true)
+        json
+      } catch {
+        case NonFatal(e) =>
+          failures.add(e)
+          throw e
+      } finally {
+        Thread.currentThread().interrupt()
+      }
+    }
+    val statsExpr = ScalaUDF(
+      checkRegistryOnCancel,
+      StringType,
+      Seq(aggregate.aggregateExpressions.head))
+    val tracker = GlutenDeltaJobStatsTracker(new DeltaJobStatisticsTracker(
+      spark.sessionState.newHadoopConf(),
+      new Path("file:/tmp/gluten-stats-cancellation"),
+      aggregate.child.output,
+      statsExpr))
+    val conf = spark.sessionState.conf.clone()
+    // The synthetic task uses stage -1, which otherwise matches the default 
dump stage.
+    conf.setConfString(GlutenConfig.BENCHMARK_TASK_STAGEID.key, "0")
+    val thread = new Thread(
+      () => {
+        SparkSession.clearActiveSession()
+        try {
+          intercept[InterruptedException] {
+            SQLConf.withExistingConf(conf) {
+              TaskResources.runUnsafe {
+                val context = TaskContext.get()
+                val usage = TaskResources.getSharedUsage()
+                completionChecks.add(
+                  () => {
+                    assert(context.isCompleted())
+                    assert(usage.current() == 0)
+                  })
+                val taskTracker = tracker.newTaskInstance()
+                context.addTaskCompletionListener[Unit](_ => 
Thread.currentThread().interrupt())
+                val file = "file:/tmp/gluten-stats-cancellation/part.parquet"
+                taskTracker.newFile(file)
+                taskTracker.closeFile(file)
+              }
+            }
+          }
+          cancellationPreserved.set(Thread.currentThread().isInterrupted)
+        } catch {
+          case NonFatal(e) =>
+            failures.add(e)
+            workerReady.countDown()
+        }
+      },
+      "delta statistics cancellation task"
+    )
+    taskThread.set(thread)
+    thread.setDaemon(true)
+    thread.start()
+    try {
+      assert(workerReady.await(30, TimeUnit.SECONDS), "Statistics worker did 
not reach evaluation")
+    } finally {
+      thread.interrupt()
+      thread.join(30000)
+    }
+    assert(!thread.isAlive, "Statistics cleanup did not terminate")
+    failures.asScala.foreach(e => throw e)
+    assert(registryAccessed.get(), "Statistics worker could not access its 
task resource registry")
+    assert(resourceReleased.get(), "Worker-registered resource was not 
released")
+    assert(cancellationPreserved.get(), "Cleanup cleared the task cancellation 
interrupt")
+    completionChecks.asScala.foreach(_())
+  }
+}
diff --git 
a/backends-velox/src-delta4/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
 
b/backends-velox/src-delta4/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
index 7b0d901dd7..52565fa1b1 100644
--- 
a/backends-velox/src-delta4/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
+++ 
b/backends-velox/src-delta4/main/scala/org/apache/spark/sql/delta/stats/GlutenDeltaJobStatsTracker.scala
@@ -44,6 +44,7 @@ import 
org.apache.spark.sql.execution.aggregate.SortAggregateExec
 import org.apache.spark.sql.execution.datasources.{BasicWriteJobStatsTracker, 
WriteJobStatsTracker, WriteTaskStats, WriteTaskStatsTracker}
 import org.apache.spark.sql.execution.metric.SQLMetric
 import org.apache.spark.sql.vectorized.ColumnarBatch
+import org.apache.spark.task.TaskResources
 import org.apache.spark.util.{SerializableConfiguration, SparkDirectoryUtil, 
Utils}
 
 import com.google.common.collect.Lists
@@ -51,7 +52,7 @@ import org.apache.hadoop.conf.Configuration
 import org.apache.hadoop.fs.Path
 
 import java.util.UUID
-import java.util.concurrent.{Callable, Executors, Future, SynchronousQueue}
+import java.util.concurrent.{Callable, Executors, Future, SynchronousQueue, 
TimeUnit}
 
 import scala.collection.JavaConverters._
 import scala.collection.mutable
@@ -227,6 +228,33 @@ object GlutenDeltaJobStatsTracker extends Logging {
     private var currentPath: String = _
     private var currentJsonFuture: Future[String] = _
 
+    // Registered after TaskResources, so Spark's reverse listener order stops 
the worker first.
+    // A recycler holds the registry lock, which the worker may need to wrap 
its output batch.
+    taskContext.addTaskCompletionListener[Unit] {
+      _ =>
+        Option(currentJsonFuture).foreach(_.cancel(true))
+        resultThreadRunner.shutdownNow()
+        var interrupted = false
+        try {
+          while (!resultThreadRunner.isTerminated) {
+            try {
+              resultThreadRunner.awaitTermination(Long.MaxValue, 
TimeUnit.NANOSECONDS)
+            } catch {
+              case _: InterruptedException => interrupted = true
+            }
+          }
+          try {
+            veloxAggTask.close()
+          } finally {
+            c2r.close()
+          }
+        } finally {
+          if (interrupted) {
+            Thread.currentThread().interrupt()
+          }
+        }
+    }
+
     override def newPartition(partitionValues: InternalRow): Unit = {}
 
     override def newFile(filePath: String): Unit = {
@@ -239,22 +267,28 @@ object GlutenDeltaJobStatsTracker extends Logging {
         override def call(): String = {
           Thread.currentThread().setName(resultThreadName)
           TaskContext.setTaskContext(taskContext)
-          val outBatches = veloxAggTask.asScala.toSeq
-          val row: InternalRow = if (outBatches.isEmpty) {
-            // No input was received. Returns the default aggregation values.
-            emptyRow
-          } else {
-            assert(outBatches.size == 1)
-            val batch = outBatches.head
-            val rows = c2r.toRowIterator(batch).toSeq
-            assert(
-              rows.size == 1,
-              "Only one single output row is expected from the global 
aggregation.")
-            batch.close()
-            rows.head
+          try {
+            val batch = if (veloxAggTask.hasNext) Some(veloxAggTask.next()) 
else None
+            try {
+              val row: InternalRow = batch match {
+                case None =>
+                  // No input was received. Returns the default aggregation 
values.
+                  emptyRow
+                case Some(output) =>
+                  assert(!veloxAggTask.hasNext)
+                  val rows = c2r.toRowIterator(output).toSeq
+                  assert(
+                    rows.size == 1,
+                    "Only one single output row is expected from the global 
aggregation.")
+                  rows.head
+              }
+              Option(getStatsExpr.eval(row)).map(_.toString).orNull
+            } finally {
+              batch.foreach(_.close())
+            }
+          } finally {
+            TaskContext.unset()
           }
-          val jsonStats = Option(getStatsExpr.eval(row)).map(_.toString).orNull
-          jsonStats
         }
         currentPath = filePath
       })
@@ -292,7 +326,15 @@ object GlutenDeltaJobStatsTracker extends Logging {
           // Counts up the reference count for the batch since it
           // will be consumed by Velox aggregation task asynchronously.
           ColumnarBatches.retain(batch)
-          inputBatchQueue.put(Some(batch))
+          var transferred = false
+          try {
+            inputBatchQueue.put(Some(batch))
+            transferred = true
+          } finally {
+            if (!transferred) {
+              batch.close()
+            }
+          }
       }
     }
 
@@ -303,12 +345,17 @@ object GlutenDeltaJobStatsTracker extends Logging {
     }
 
     private def newIteratorFromInputQueue(): ColumnarBatchInIterator = {
+      var batch: ColumnarBatch = null
+      TaskResources.addRecycler("GlutenDeltaStatsBufferedInput", 100) {
+        if (batch != null) {
+          batch.close()
+          batch = null
+        }
+      }
       val itr = new ColumnarBatchInIterator(
         BackendsApiManager.getBackendName,
         Iterators
           .wrap(new Iterator[ColumnarBatch] {
-            private var batch: ColumnarBatch = _
-
             override def hasNext: Boolean = {
               assert(batch == null)
               while (!Thread.currentThread().isInterrupted) {
diff --git 
a/backends-velox/src-delta4/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
 
b/backends-velox/src-delta4/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
new file mode 120000
index 0000000000..1fb6b784b0
--- /dev/null
+++ 
b/backends-velox/src-delta4/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
@@ -0,0 +1 @@
+../../../../../../../../src-delta33/test/scala/org/apache/spark/sql/delta/GlutenDeltaStatsLifecycleSuite.scala
\ No newline at end of file


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to