This is an automated email from the ASF dual-hosted git repository.
huaxingao pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg.git
The following commit(s) were added to refs/heads/main by this push:
new d414bdc12d Spark 4.1: Keep read metrics from earlier readers in the
same task (#18726)
d414bdc12d is described below
commit d414bdc12daf114373f92e4604c02ba6482a1828
Author: Venkata krishnan Sowrirajan <[email protected]>
AuthorDate: Tue Nov 17 19:48:38 2026 -0800
Spark 4.1: Keep read metrics from earlier readers in the same task (#18726)
* Spark 4.1: Keep read metrics from earlier readers in the same task
When a task reads several input partitions, Spark 4.1 opens one reader per
partition and passes the previous reader's metrics through
initMetricsValues. The readers inherited the no-op default, so numSplits,
numDeletes and scanDuration only reflected the last reader in each task.
MergingSortedRowDataReader also reports scanDuration now, summed across its
file readers.
Generated-by: Claude Opus 5.5
* Spark 4.1: Check numDeletes when a task reads several partitions
Extends the subset-key SPJ test so each of the 5 partitions has a
merge-on-read delete and numDeletes must count all of them, not only the
last reader's.
Generated-by: Claude Opus 5.5
---------
Co-authored-by: Venkata Krishnan Sowrirajan <[email protected]>
---
.../iceberg/spark/source/BatchDataReader.java | 15 +++--
.../iceberg/spark/source/InheritedTaskMetrics.java | 75 ++++++++++++++++++++++
.../spark/source/MergingSortedRowDataReader.java | 16 ++++-
.../apache/iceberg/spark/source/RowDataReader.java | 15 +++--
.../source/TestMergingSortedRowDataReader.java | 33 ++++++++++
.../iceberg/spark/source/TestSparkReadMetrics.java | 61 ++++++++++++++++++
6 files changed, 202 insertions(+), 13 deletions(-)
diff --git
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BatchDataReader.java
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BatchDataReader.java
index d6ef3bb095..319435d3cf 100644
---
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BatchDataReader.java
+++
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BatchDataReader.java
@@ -47,6 +47,7 @@ class BatchDataReader extends BaseBatchReader<FileScanTask>
private static final Logger LOG =
LoggerFactory.getLogger(BatchDataReader.class);
private final long numSplits;
+ private final InheritedTaskMetrics inheritedMetrics = new
InheritedTaskMetrics();
BatchDataReader(
SparkInputPartition partition,
@@ -88,11 +89,15 @@ class BatchDataReader extends BaseBatchReader<FileScanTask>
@Override
public CustomTaskMetric[] currentMetricsValues() {
- return new CustomTaskMetric[] {
- new TaskNumSplits(numSplits),
- new TaskNumDeletes(counter().get()),
- new TaskScanDuration(scanDurationNanos())
- };
+ return inheritedMetrics.addTo(
+ new TaskNumSplits(numSplits),
+ new TaskNumDeletes(counter().get()),
+ new TaskScanDuration(scanDurationNanos()));
+ }
+
+ @Override
+ public void initMetricsValues(CustomTaskMetric[] metrics) {
+ inheritedMetrics.inherit(metrics);
}
@Override
diff --git
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/InheritedTaskMetrics.java
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/InheritedTaskMetrics.java
new file mode 100644
index 0000000000..145e90865a
--- /dev/null
+++
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/InheritedTaskMetrics.java
@@ -0,0 +1,75 @@
+/*
+ * 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.iceberg.spark.source;
+
+import java.util.Map;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.spark.sql.connector.metric.CustomTaskMetric;
+
+/**
+ * Task metrics reported by the readers that ran earlier in the same Spark
task.
+ *
+ * <p>When a task reads several input partitions, Spark opens one reader per
partition and passes
+ * the previous reader's metrics to the next through {@code
initMetricsValues}. Spark keeps only the
+ * last reader's values, so each reader must add the inherited values to its
own.
+ */
+class InheritedTaskMetrics {
+ private final Map<String, Long> values = Maps.newHashMap();
+
+ void inherit(CustomTaskMetric[] metrics) {
+ values.clear();
+ for (CustomTaskMetric metric : metrics) {
+ values.put(metric.name(), metric.value());
+ }
+ }
+
+ CustomTaskMetric[] addTo(CustomTaskMetric... metrics) {
+ CustomTaskMetric[] result = new CustomTaskMetric[metrics.length];
+ for (int i = 0; i < metrics.length; i += 1) {
+ CustomTaskMetric metric = metrics[i];
+ Long inherited = values.get(metric.name());
+ result[i] =
+ inherited != null
+ ? new SummedTaskMetric(metric.name(), inherited + metric.value())
+ : metric;
+ }
+
+ return result;
+ }
+
+ private static class SummedTaskMetric implements CustomTaskMetric {
+ private final String name;
+ private final long value;
+
+ private SummedTaskMetric(String name, long value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ @Override
+ public String name() {
+ return name;
+ }
+
+ @Override
+ public long value() {
+ return value;
+ }
+ }
+}
diff --git
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java
index 8670883db8..e3302204a5 100644
---
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java
+++
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java
@@ -45,6 +45,7 @@ import
org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.apache.iceberg.spark.SparkSchemaUtil;
import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.spark.source.metrics.TaskScanDuration;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.TypeUtil;
import org.apache.iceberg.types.Types;
@@ -75,6 +76,7 @@ class MergingSortedRowDataReader implements
PartitionReader<InternalRow> {
private final CloseableIterator<TaggedRow> mergedIterator;
private final List<RowDataReader> fileReaders;
private final ProjectingInternalRow projectingRow;
+ private final InheritedTaskMetrics inheritedMetrics = new
InheritedTaskMetrics();
private InternalRow current;
private FileBlock currentBlock;
@@ -268,13 +270,21 @@ class MergingSortedRowDataReader implements
PartitionReader<InternalRow> {
@Override
public CustomTaskMetric[] currentMetricsValues() {
long totalDeletes = 0L;
+ long totalScanDurationNanos = 0L;
for (RowDataReader reader : fileReaders) {
totalDeletes += reader.counter().get();
+ totalScanDurationNanos += reader.scanDurationNanos();
}
- return new CustomTaskMetric[] {
- new TaskNumSplits(fileReaders.size()), new TaskNumDeletes(totalDeletes)
- };
+ return inheritedMetrics.addTo(
+ new TaskNumSplits(fileReaders.size()),
+ new TaskNumDeletes(totalDeletes),
+ new TaskScanDuration(totalScanDurationNanos));
+ }
+
+ @Override
+ public void initMetricsValues(CustomTaskMetric[] metrics) {
+ inheritedMetrics.inherit(metrics);
}
private static Comparator<InternalRow> buildComparator(
diff --git
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/RowDataReader.java
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/RowDataReader.java
index a60fbabcaf..d41ccfd33b 100644
---
a/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/RowDataReader.java
+++
b/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/RowDataReader.java
@@ -45,6 +45,7 @@ class RowDataReader extends BaseRowReader<FileScanTask>
implements PartitionRead
private static final Logger LOG =
LoggerFactory.getLogger(RowDataReader.class);
private final long numSplits;
+ private final InheritedTaskMetrics inheritedMetrics = new
InheritedTaskMetrics();
RowDataReader(SparkInputPartition partition) {
this(
@@ -72,11 +73,15 @@ class RowDataReader extends BaseRowReader<FileScanTask>
implements PartitionRead
@Override
public CustomTaskMetric[] currentMetricsValues() {
- return new CustomTaskMetric[] {
- new TaskNumSplits(numSplits),
- new TaskNumDeletes(counter().get()),
- new TaskScanDuration(scanDurationNanos())
- };
+ return inheritedMetrics.addTo(
+ new TaskNumSplits(numSplits),
+ new TaskNumDeletes(counter().get()),
+ new TaskScanDuration(scanDurationNanos()));
+ }
+
+ @Override
+ public void initMetricsValues(CustomTaskMetric[] metrics) {
+ inheritedMetrics.inherit(metrics);
}
@Override
diff --git
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java
index b24d7a0b55..7123a1f7fe 100644
---
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java
+++
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java
@@ -34,6 +34,7 @@ import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -67,6 +68,7 @@ import
org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.spark.TestBase;
import org.apache.iceberg.spark.source.metrics.TaskNumDeletes;
import org.apache.iceberg.spark.source.metrics.TaskNumSplits;
+import org.apache.iceberg.spark.source.metrics.TaskScanDuration;
import org.apache.iceberg.transforms.Transform;
import org.apache.iceberg.transforms.Transforms;
import org.apache.iceberg.types.Types;
@@ -527,6 +529,37 @@ class TestMergingSortedRowDataReader extends TestBase {
assertThat(metrics)
.containsEntry(new TaskNumSplits(0).name(), 3L)
.containsEntry(new TaskNumDeletes(0).name(), 2L);
+ assertThat(metrics.get(new TaskScanDuration(0).name())).isPositive();
+ }
+ }
+
+ @Test
+ void metricsIncludeValuesFromPreviousReader() throws IOException {
+ DataFile file1 = writeDataFile(record(1, "a"), record(3, "c"));
+ DataFile file2 = writeDataFile(record(2, "b"), record(4, "d"));
+
+ table.newAppend().appendFile(file1).appendFile(file2).commit();
+
+ long inheritedNanos = TimeUnit.SECONDS.toNanos(1);
+ BaseScanTaskGroup<FileScanTask> taskGroup = new
BaseScanTaskGroup<>(planFiles(table));
+ try (MergingSortedRowDataReader reader =
+ new MergingSortedRowDataReader(table, table.io(), taskGroup,
table.schema(), true, false)) {
+ // Spark passes the previous reader's metrics when a task reads several
input partitions
+ reader.initMetricsValues(
+ new CustomTaskMetric[] {
+ new TaskNumSplits(3), new TaskNumDeletes(4), new
TaskScanDuration(inheritedNanos)
+ });
+ while (reader.next()) {
+ // drain
+ }
+
+ Map<String, Long> metrics =
+ Arrays.stream(reader.currentMetricsValues())
+ .collect(Collectors.toMap(CustomTaskMetric::name,
CustomTaskMetric::value));
+ assertThat(metrics)
+ .containsEntry(new TaskNumSplits(0).name(), 5L)
+ .containsEntry(new TaskNumDeletes(0).name(), 4L);
+ assertThat(metrics.get(new
TaskScanDuration(0).name())).isGreaterThan(inheritedNanos);
}
}
diff --git
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestSparkReadMetrics.java
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestSparkReadMetrics.java
index d3109365d8..b936b08b4e 100644
---
a/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestSparkReadMetrics.java
+++
b/spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestSparkReadMetrics.java
@@ -560,4 +560,65 @@ public class TestSparkReadMetrics extends
TestBaseWithCatalog {
.hasEntrySatisfying(
"skippedDeleteFiles", sqlMetric ->
assertThat(sqlMetric.value()).isEqualTo(0));
}
+
+ @TestTemplate
+ public void metricsWhenTaskReadsSeveralPartitions() {
+ sql(
+ "CREATE TABLE %s (id BIGINT, dep STRING, region STRING) USING iceberg "
+ + "PARTITIONED BY (dep, region) "
+ + "TBLPROPERTIES ('format-version'='2',
'write.delete.mode'='merge-on-read')",
+ tableName);
+ sql(
+ "INSERT INTO %s VALUES (1, 'hr', 'us'), (2, 'hr', 'eu'), (3, 'hr',
'apac'), "
+ + "(4, 'ops', 'us'), (5, 'ops', 'eu'), (11, 'hr', 'us'), (12,
'hr', 'eu'), "
+ + "(13, 'hr', 'apac'), (14, 'ops', 'us'), (15, 'ops', 'eu')",
+ tableName);
+ // one deleted row in each of the 5 partitions
+ sql("DELETE FROM %s WHERE id > 10", tableName);
+
+ // joining on a subset of the partition keys makes Spark group the 3 hr
and the 2 ops
+ // partitions into one task each, so every task opens several readers
+ Map<String, String> spjConf =
+ ImmutableMap.of(
+ SQLConf.V2_BUCKETING_ENABLED().key(),
+ "true",
+
SQLConf.V2_BUCKETING_ALLOW_JOIN_KEYS_SUBSET_OF_PARTITION_KEYS().key(),
+ "true",
+ SQLConf.REQUIRE_ALL_CLUSTER_KEYS_FOR_CO_PARTITION().key(),
+ "false",
+ SQLConf.ADAPTIVE_EXECUTION_ENABLED().key(),
+ "false",
+ SQLConf.AUTO_BROADCASTJOIN_THRESHOLD().key(),
+ "-1",
+ SparkSQLProperties.PRESERVE_DATA_GROUPING,
+ "true");
+
+ for (String vectorized : new String[] {"true", "false"}) {
+ sql(
+ "ALTER TABLE %s SET TBLPROPERTIES ('%s'='%s')",
+ tableName, TableProperties.PARQUET_VECTORIZATION_ENABLED,
vectorized);
+
+ withSQLConf(
+ spjConf,
+ () -> {
+ Dataset<Row> df =
+ spark.sql(
+ String.format(
+ "SELECT * FROM %s a JOIN %s b ON a.dep = b.dep",
tableName, tableName));
+ df.collect();
+
+ List<SparkPlan> scans =
+
seqAsJavaListConverter(df.queryExecution().executedPlan().collectLeaves()).asJava();
+ assertThat(scans).hasSize(2);
+ for (SparkPlan scan : scans) {
+ assertThat(scan.metrics().get("numSplits").get().value())
+ .as("numSplits with vectorization %s", vectorized)
+ .isEqualTo(5L);
+ assertThat(scan.metrics().get("numDeletes").get().value())
+ .as("numDeletes with vectorization %s", vectorized)
+ .isEqualTo(5L);
+ }
+ });
+ }
+ }
}