gerashegalov commented on code in PR #19298:
URL: https://github.com/apache/iceberg/pull/19298#discussion_r4802868280
##########
spark/v4.1/spark/src/test/java/org/apache/iceberg/spark/source/TestBaseReader.java:
##########
@@ -246,6 +253,140 @@ public void testIdempotentExplicitClosure() throws
IOException {
}
}
+ private static class PausingRowReader extends BaseReader<Integer,
FileScanTask> {
+ private final long openPauseNanos;
+ private final long rowPauseNanos;
+
+ PausingRowReader(
+ Table table, List<FileScanTask> tasks, long openPauseNanos, long
rowPauseNanos) {
+ super(table, table.io(), new BaseCombinedScanTask(tasks), null, false,
true);
+ this.openPauseNanos = openPauseNanos;
+ this.rowPauseNanos = rowPauseNanos;
+ }
+
+ @Override
+ protected Stream<ContentFile<?>> referencedFiles(FileScanTask task) {
+ return Stream.of();
+ }
+
+ @Override
+ protected CloseableIterator<Integer> open(FileScanTask task) {
+ pause(openPauseNanos);
+ return pausing(IntStream.range(0, (int)
task.file().recordCount()).iterator(), rowPauseNanos);
+ }
+ }
+
+ private static class PausingBatchReader extends
BaseBatchReader<FileScanTask> {
+ private final long batchPauseNanos;
+
+ PausingBatchReader(Table table, List<FileScanTask> tasks, long
batchPauseNanos) {
+ super(table, table.io(), new BaseCombinedScanTask(tasks), null, false,
null, null, true);
+ this.batchPauseNanos = batchPauseNanos;
+ }
+
+ @Override
+ protected Stream<ContentFile<?>> referencedFiles(FileScanTask task) {
+ return Stream.of();
+ }
+
+ @Override
+ protected CloseableIterator<ColumnarBatch> open(FileScanTask task) {
+ ColumnarBatch batch = new ColumnarBatch(new ColumnVector[0], 0);
+ return pausing(
+ Collections.nCopies((int) task.file().recordCount(),
batch).iterator(), batchPauseNanos);
+ }
+ }
+
+ @Test
+ void scanDurationExcludesTimeBetweenRows() throws IOException {
+ List<FileScanTask> tasks = createFileScanTasks(1, 2);
+ PausingRowReader reader = new PausingRowReader(table, tasks, 0L, 0L);
+
+ assertThat(reader.next()).isTrue();
+ pause(PAUSE_NANOS);
+ assertThat(reader.next()).isTrue();
+ assertThat(reader.next()).isFalse();
+
+ assertThat(reader.scanDurationNanos()).isLessThan(PAUSE_NANOS);
+ }
+
+ @Test
+ void scanDurationCountsEachOpenOnce() throws IOException {
+ List<FileScanTask> tasks = createFileScanTasks(2, 1);
+ PausingRowReader reader = new PausingRowReader(table, tasks, PAUSE_NANOS,
0L);
+
+ while (reader.next()) {
+ // drain
+ }
+
+ assertThat(reader.scanDurationNanos()).isBetween(2 * PAUSE_NANOS, 3 *
PAUSE_NANOS);
+ }
+
+ @Test
+ void scanDurationCountsFirstRowOfEachFileOnce() throws IOException {
+ List<FileScanTask> tasks = createFileScanTasks(2, 1);
+ PausingRowReader reader = new PausingRowReader(table, tasks, 0L,
PAUSE_NANOS);
+
+ while (reader.next()) {
+ // drain
+ }
+
+ assertThat(reader.scanDurationNanos()).isBetween(2 * PAUSE_NANOS, 3 *
PAUSE_NANOS);
+ }
+
+ @Test
+ void scanDurationEstimatesTimeSpentReadingRows() throws IOException {
+ List<FileScanTask> tasks = createFileScanTasks(1, 2000);
+ PausingRowReader reader = new PausingRowReader(table, tasks, 0L,
ROW_PAUSE_NANOS);
+
+ long start = System.nanoTime();
+ while (reader.next()) {
+ // drain
+ }
+ long elapsedNanos = System.nanoTime() - start;
+
+ // rows are timed from a random sample, so the estimate is only close to
the elapsed time
+ assertThat(reader.scanDurationNanos()).isBetween(elapsedNanos / 4,
elapsedNanos * 4);
Review Comment:
Two small things about the test bounds:
- **This bound can't tell a calibration error apart.** I tried scaling by 2×
or ½×, and halving the mean gap. All three pass, since they land well inside
÷4/×4. With 2,000 rows there are about 31 samples, and the sample-count noise
is about 10%, so `isBetween(elapsedNanos / 2, elapsedNanos * 2)` would still
pass reliably on an idle machine. Under load, a stall inside a sampled call is
×64, so it's worth a few reruns before tightening.
- **Lines 322 and 334 now use a fixed `3 * PAUSE_NANOS` upper bound.** I see
why `elapsed` didn't work: a scaled sliver can exceed it. But the fixed bound
fails if the thread stalls for more than about 20 ms inside one of the exactly
timed pauses, for example from a GC in the shared test JVM. `isBetween(2 *
PAUSE_NANOS, elapsedNanos + PAUSE_NANOS)` keeps the stall-proof bound and still
leaves room for the scaled slivers. Both passed 14 reruns here, idle and under
full CPU load, so this is about robustness, not an observed flake.
Separately, the tests can't force a sample, because `ThreadLocalRandom` has
no seam. So the branch where an opening call is also sampled is only checked on
the row path about 1.6% of the time. Counting the open inside the scaled window
is only caught by the batch test. A package-private gap supplier would make
this deterministic. Optional.
##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java:
##########
@@ -165,10 +193,38 @@ public boolean next() throws IOException {
}
throw e;
} finally {
- this.scanDurationNanos += System.nanoTime() - start;
+ recordScanDuration(timeEachCall, timeCall, startNanos, opened,
openStartNanos);
}
}
+ private void recordScanDuration(
+ boolean timeEachCall,
+ boolean timeCall,
+ long startNanos,
+ boolean opened,
+ long openStartNanos) {
+ long endNanos = timeCall || opened ? System.nanoTime() : 0L;
+ if (opened) {
+ this.scanDurationNanos += endNanos - openStartNanos;
+ }
+
+ if (timeCall) {
+ long callNanos = (opened ? openStartNanos : endNanos) - startNanos;
+ if (timeEachCall) {
+ this.scanDurationNanos += callNanos;
+ } else {
+ this.scanDurationNanos += callNanos * ROW_SAMPLE_INTERVAL;
Review Comment:
Each sampled window includes part of the two `nanoTime()` calls that time
it, about 20–40 ns here. Multiplying by 64 charges that to every row, including
the 63 in 64 that never paid for it. On narrow row scans that's a large share
of the per-row cost. On Spark 4.1, JDK 17:
- Draining a `RowDataReader` over 5M BIGINT rows, scanDuration came out at
1.20–1.32× the drain loop's own wall time. `main`, which really pays for the
clock reads, gives 0.65×, and the previous revision gives 1.00×.
- On a non-vectorized `SELECT sum(id)` over 10M rows, scanDuration is the
same as on `main` (about 455 ms), even though the task now runs 325 ms faster
(588 ms against 915 ms).
- Reading a real 2M-row Parquet file through the 4.0 port in #18775, the
sampled mean was no lower than timing every row, even though the sampled read
was 56 ms cheaper.
One option is to subtract a clock overhead calibrated once per JVM from each
sampled `callNanos`, clamped at 0. For example, use the minimum back-to-back
`nanoTime()` delta measured in a static initializer. It's approximate for very
cheap rows, but it removes most of the bias. If that's too fiddly, the javadoc
and the metric docs should at least say that on row reads the value is a
sampled estimate that includes about one clock read per row. Raising the
interval won't help, because the bias per row stays the same.
##########
spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/source/BaseReader.java:
##########
@@ -149,6 +172,11 @@ public boolean next() throws IOException {
} else if (tasks.hasNext()) {
this.currentIterator.close();
this.currentTask = tasks.next();
+ if (!opened) {
+ opened = true;
+ openStartNanos = System.nanoTime();
Review Comment:
This makes the opening call exact, but on Parquet that only covers the first
row group. Later row groups are loaded inside an ordinary `next()`
(`ParquetReader.FileIterator.next()` calls `advance()`, which calls
`readNextRowGroup()`). With the default 512 MB files and 128 MB row groups,
that's about 3 of 4 loads per file, and each is caught 1 time in 64, then
scaled by 64. ORC/Avro batch reads on the row path, page decompression,
delete-filter skips and GC pauses behave the same way. This partly corrects my
own suggestion: "always time `open(task)`" only helps with the first row group.
The total stays unbiased. Per task, though, the value becomes close to
bimodal. I simulated this exact sampler with 4 row groups × 1M rows per task,
30 ns/row and 50 ms per row-group read (true time 345 ms):
- About 95% of tasks report roughly 0.56 of their read time.
- The rest report about 10×.
- The total over 100 tasks lands at 0.97 ± 0.17.
`ScanDuration` shows `total (min, med, max)` so stragglers stand out, but on
the row path the max mostly shows which task happened to sample a row-group
read. That's also why a single task can exceed its run time, even though the
k-way sum stays within wall time on average.
Could we:
1. Note in the `scanDurationNanos()` javadoc and the metric docs that on row
reads the per-task values are sampled estimates and only the total is reliable?
2. Move this `if (!opened)` block above `this.currentIterator.close()`, so
that closing the previous file (S3 stream abort or drain) is exact too?
A smaller interval, such as 16, would cut the variance about 4× for roughly
2 ns/row. Having the Parquet reader time `readNextRowGroup()` itself would be
the real fix, but that's for a follow-up.
##########
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:
Thanks, confirmed with the same SPJ probe on 4.2 at 4b464cf. With k-way
merge coalescing and vectorization off, the scan stage now reports 0.05–0.09 of
run time, in line with sequential coalescing (0.04–0.07). Before this change it
was 0.55–0.69.
One caveat on "stays within wall time": it holds on average. A sampled call
is scaled by 64, so a task that happens to sample an expensive call can still
report more than its own run time. I left a note about that on
`BaseReader.java` line 177.
##########
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:
Thanks, confirmed. With the override removed,
`batchScanDurationCoversEveryCallAndNothingBetween` fails (33 ms against the ≥
40 ms bound).
##########
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:
Thanks! The `supportsColumnar()` assertion is a nice touch. It makes sure
the non-vectorized variant really goes through `RowDataReader`.
##########
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:
Makes sense. With the test gone, nothing is left from this one.
##########
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:
Agreed. I checked that #19116 merges cleanly on top of this and sums per
file. That's right again now that the timed windows can't overlap.
--
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]