gerashegalov commented on code in PR #19298:
URL: https://github.com/apache/iceberg/pull/19298#discussion_r4793270663


##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java:
##########
@@ -149,9 +168,11 @@ public boolean next() throws IOException {
         } else if (tasks.hasNext()) {
           this.currentIterator.close();
           this.currentTask = tasks.next();
+          scanTimer.start();

Review Comment:
   On Spark 4.2 these windows can overlap within one task, and the task reports 
more than its wall time.
   
   - **When it happens:** 
`spark.sql.sources.v2.bucketing.preserveOrderingOnCoalesce.enabled` and 
`...partitionKeyOrdering.enabled` are both set. They're new in 4.2.0 and off by 
default. `GroupPartitionsExec` then coalesces SPJ partitions with a k-way merge 
(`SortedMergeCoalescedRDD`).
   - **Why the windows overlap:** the merge opens all N readers up front, so 
every row reader's window starts right away.
   - **Why they add up:** `DataSourceRDD` combines the readers' 
`TaskScanDuration` with `CustomTaskMetric.mergeWith`, which sums by default. 
Its javadoc names k-way merge coalescing as the case to handle.
   - **What I measured:** in a local SPJ join with vectorization off, tasks 
reported 1.5x to 2.1x their run time.
   
   Per-call or sampled per-call timing can't overlap on one thread, so the sum 
stays at or below wall time. Overriding `mergeWith` with max wouldn't work, 
because `DataSourceRDD` also merges readers that ran one after another and are 
already closed.



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BaseBatchReader.java:
##########
@@ -62,6 +62,11 @@ abstract class BaseBatchReader<T extends ScanTask> extends 
BaseReader<ColumnarBa
     this.orcConf = orcConf;
   }
 
+  @Override
+  protected boolean timeEachCall() {

Review Comment:
   Nothing pins this override. With it removed, every test still passes, 
because `scanDurationExcludesTimeBetweenCallsWhenTimingEachCall` sets the flag 
on `ClosureTrackingReader` itself. A test through a real `BatchDataReader` 
would catch the batch path silently switching to task-window timing.



##########
spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestSparkReadMetrics.java:
##########
@@ -420,23 +425,48 @@ public void testReadMetricsForV2Table() throws 
NoSuchTableException {
   }
 
   @Test
-  public void scanDurationAggregatedAcrossTasks() throws NoSuchTableException {
+  public void scanDurationAggregatedAcrossTasks() throws NoSuchTableException, 
TimeoutException {
     sql("CREATE TABLE %s (id BIGINT) USING iceberg", tableName);
 
     spark.range(10000).coalesce(1).writeTo(tableName).append();
     spark.range(10001, 20000).coalesce(1).writeTo(tableName).append();
 
-    Dataset<Row> df = spark.sql(String.format("SELECT * FROM %s", tableName));
-    assertThat(df.collectAsList()).hasSize(19999);
+    List<SparkListenerTaskEnd> taskEnds = 
Collections.synchronizedList(Lists.newArrayList());
+    SparkListener listener =
+        new SparkListener() {
+          @Override
+          public void onTaskEnd(SparkListenerTaskEnd taskEnd) {
+            taskEnds.add(taskEnd);
+          }
+        };
+
+    // a tiny split size keeps the two files from being combined into one task
+    Dataset<Row> df =
+        spark.read().format("iceberg").option(SparkReadOptions.SPLIT_SIZE, 
"1").load(tableName);

Review Comment:
   This reads a default Parquet table with vectorization on, so it goes through 
`BatchDataReader`, whose timing this PR doesn't change. The assertion checks 
Spark's own accumulator sum, and the test also passes against the base sources. 
Could it cover the row path too, for example with 
`read.parquet.vectorization.enabled=false`? `scanDurationForNonVectorizedRead` 
is the only Spark-level row-path test, and it only checks `> 0`.



##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/MergingSortedRowDataReader.java:
##########
@@ -132,6 +133,8 @@ class MergingSortedRowDataReader implements 
PartitionReader<InternalRow> {
     UnsafeProjection deepCopyProjection =
         UnsafeProjection.create(SparkSchemaUtil.convert(mergeReadSchema));
 
+    // timed here rather than summed per file, as all files are open for the 
whole merge

Review Comment:
   Nit: this comment describes the alternative rather than the reason. Maybe 
`// the files are read concurrently, so their read windows overlap`?
   
   Also, 4.2's `MergingSortedRowDataReader` doesn't get this change. It reports 
no scanDuration today, but #19116 (and #18775 for 4.0) add per-file summing. 
Once this lands, that would double count, and there's no textual conflict to 
flag it. Porting this hunk to 4.2 here, or noting it on #19116, would avoid 
that. With sampled per-call timing, per-file summing would be correct again.



##########
spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestMergingSortedRowDataReader.java:
##########
@@ -533,6 +533,33 @@ void metricsReportTasksAndDeletes() throws IOException {
     }
   }
 
+  @Test
+  void scanDurationDoesNotCountConcurrentlyOpenFilesTwice()
+      throws IOException, InterruptedException {
+    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();
+
+    BaseScanTaskGroup<FileScanTask> taskGroup = new 
BaseScanTaskGroup<>(planFiles(table));
+    long start = System.nanoTime();
+    try (MergingSortedRowDataReader reader =
+        new MergingSortedRowDataReader(table, table.io(), taskGroup, 
table.schema(), true, false)) {
+      while (reader.next()) {
+        // keep both files open long enough that summing their read windows 
would be visible
+        Thread.sleep(5);

Review Comment:
   Nit: the 5 ms would read better as a named constant, like `PAUSE_NANOS` in 
`TestBaseReader`.
   
   The margin is also thin. I changed `currentMetricsValues()` back to summing 
the file readers' values. That version failed this test when the whole class 
ran, but passed when the test ran on its own. A longer pause per row, or a 
bound well below the summed value, would make it catch the double count 
reliably.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to