kinolaev commented on PR #16956:
URL: https://github.com/apache/iceberg/pull/16956#issuecomment-7197423395
> The description offers to move the `ScanTaskBinWeighter` change out. Could
we take that, since it changes planning for Flink and older Spark too?
Extracted to a separate PR #19152.
> What I'm asking here is the heap number on the sharedEqDeletes thread:
peak heap for a multi-partition task, base vs head.
@laskoviymishka, thanks for making me think this through again. I wrote that
my jobs take less time and memory with this PR, but the two improvements have
different causes.
Without sharing:
- Worst case: all deleted keys in each data file's delete files are unique.
- The deleted keys take the size of the largest set of delete files that
applies to one data file * the materialization cost.
- Each delete file is loaded once for every data file it applies to.
- Best case: all delete files contain the same keys.
- The deleted keys take the size of one equality delete file * the
materialization cost.
- Each delete file is loaded once for every data file it applies to.
With sharing:
- Worst case: data files share no delete files, and all deleted keys in the
task are unique.
- The deleted keys take the size of all equality delete files that apply
to the data files the task reads * the materialization cost.
- Each delete file is loaded once, which is the same as without sharing
because each one applies to a single data file in the task.
- Best case: all data files share the same delete files, and all delete
files contain the same keys.
- The deleted keys take the size of one equality delete file * the
materialization cost.
- Each delete file is loaded once.
So with sharing, the deleted keys always take at least as much heap as
without sharing, and the read is always at least as fast.
But deleted keys are deduplicated in both cases, so they aren't always the
peak. `BaseDeleteLoader` first loads all delete files of a data file into a
`ConcurrentLinkedQueue`, and only then merges them into a `StructLikeSet`. So
without sharing, the peak is at least the largest set of delete files that
applies to one data file * the materialization cost, even in the best case.
Sharing fixes this mostly by accident, because data files from newer
manifests are usually read first. Consider a table that is rewritten by every
commit:
1. data file 1 with IDs 1-1000
2. delete file 2 with IDs 1-1000, and data file 2 with IDs 1-1000
3. delete file 3 with IDs 1-1000, and data file 3 with IDs 1-1000
4. delete file 4 with IDs 1-1000, and data file 4 with IDs 1-1000
Without sharing, data file 1 has the largest set of delete files: 3000 keys
before deduplication, and the number grows with every commit.
With sharing, each data file loads at most one new delete file, so the peak
is 1000 deduplicated keys plus 1000 loaded keys, whatever the number of commits.
If the oldest data file came first, sharing alone wouldn't help: data file 1
would load all delete files at once, and the peak would be the same as without
sharing.
Streaming delete files into the shared deleted keys would fix this. I hope
to have time in December to do it in a separate PR.
---
Meanwhile, here is a benchmark that confirms this expectation:
`IcebergSourceSharedEqDeleteBenchmark` (Spark 4.2, vectorized Parquet, executor
cache off). It reads a table in a single task: 8 partitions with one 1M-row
data file each, plus 8 equality delete files with 200k keys each. Two
parameters vary:
- `sharedDeleteFiles`: the fraction of delete files that are global and
apply to all data files; each of the rest applies to a single partition.
- `sharedDeleteKeys`: the fraction of keys common to all delete files.
All delete files are committed at once, so with sharing, the first data file
the task reads loads all global delete files, whatever the order of data files
in the task. This rules out the accidental memory saving described above.
A full read scans the whole table. A selective read selects one row by ID:
file stats keep all 8 data files in the task, and bloom filters skip all but
the one containing the row. The live heap is sampled every 100 ms after a
forced GC. Heap is the peak live heap minus the live heap before the read, in
MB (base = sharing off, head = sharing on). Each value is the mean of 10 runs
on a laptop ± the 99.9% confidence interval, as JMH reports it.
| shared files | shared keys | full heap, base | full heap, head | selective
heap, base | selective heap, head | full time, base | full time, head |
selective time, base | selective time, head |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 44 ± 2 | 316 ± 3 | 42 ± 2 | 43 ± 2 | 1.49 ± 0.09 s | 1.43 ± 0.14 s
| 0.20 ± 0.06 s | 0.23 ± 0.03 s |
| 0 | 0.5 | 43 ± 0 | 316 ± 3 | 44 ± 2 | 43 ± 2 | 1.40 ± 0.09 s | 1.34 ± 0.08
s | 0.20 ± 0.07 s | 0.21 ± 0.06 s |
| 0 | 1 | 43 ± 0 | 316 ± 3 | 42 ± 1 | 42 ± 1 | 1.37 ± 0.08 s | 1.30 ± 0.09 s
| 0.21 ± 0.04 s | 0.19 ± 0.05 s |
| 0.5 | 0 | 187 ± 1 | 310 ± 2 | 189 ± 2 | 194 ± 5 | 3.38 ± 0.16 s | 1.67 ±
0.10 s | 0.51 ± 0.16 s | 0.52 ± 0.15 s |
| 0.5 | 0.5 | 153 ± 7 | 254 ± 1 | 147 ± 6 | 155 ± 9 | 2.90 ± 0.19 s | 1.69 ±
0.13 s | 0.40 ± 0.08 s | 0.47 ± 0.11 s |
| 0.5 | 1 | 127 ± 3 | 200 ± 2 | 122 ± 13 | 136 ± 16 | 2.10 ± 0.25 s | 1.40 ±
0.10 s | 0.31 ± 0.04 s | 0.34 ± 0.10 s |
| 1 | 0 | 316 ± 1 | 311 ± 10 | 311 ± 10 | 312 ± 10 | 5.60 ± 0.31 s | 1.64 ±
0.17 s | 0.74 ± 0.23 s | 0.64 ± 0.12 s |
| 1 | 0.5 | 243 ± 2 | 238 ± 10 | 239 ± 11 | 238 ± 11 | 4.89 ± 0.07 s | 1.50
± 0.18 s | 0.56 ± 0.18 s | 0.54 ± 0.13 s |
| 1 | 1 | 191 ± 1 | 189 ± 2 | 191 ± 1 | 190 ± 2 | 3.15 ± 0.41 s | 1.12 ±
0.09 s | 0.38 ± 0.08 s | 0.42 ± 0.16 s |
<details>
<summary>IcebergSourceSharedEqDeleteBenchmark</summary>
```java
/*
* 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 static org.apache.iceberg.types.Types.NestedField.required;
import static org.apache.spark.sql.functions.col;
import static org.apache.spark.sql.functions.expr;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.FileFormat;
import org.apache.iceberg.FileScanTask;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.RowDelta;
import org.apache.iceberg.Schema;
import org.apache.iceberg.StructLike;
import org.apache.iceberg.Table;
import org.apache.iceberg.TableProperties;
import org.apache.iceberg.data.GenericRecord;
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.hadoop.HadoopTables;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.ClusteredEqualityDeleteWriter;
import org.apache.iceberg.io.OutputFileFactory;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.apache.iceberg.spark.SparkReadOptions;
import org.apache.iceberg.spark.SparkSQLProperties;
import org.apache.iceberg.types.Types;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.catalyst.InternalRow;
import org.apache.spark.sql.catalyst.expressions.GenericInternalRow;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Level;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.TearDown;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Timeout;
import org.openjdk.jmh.annotations.Warmup;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.infra.IterationParams;
import org.openjdk.jmh.runner.IterationType;
import org.openjdk.jmh.util.ListStatistics;
/**
* Compares reading a table with equality deletes in a single task with and
without sharing equality
* deletes across the data files of the task.
*
* <p>The table has one data file in each of {@link #NUM_PARTITIONS}
partitions and {@link
* #NUM_DELETE_FILES} equality delete files. {@code sharedDeleteFiles} is
the fraction of the delete
* files that are global and apply to all data files, while the rest apply
to a single partition
* each. {@code sharedDeleteKeys} is the fraction of the deleted keys that
all delete files have in
* common.
*
* <p>A {@code full} read scans the whole table. A {@code selective} read
selects a single row by
* ID. IDs are interleaved across partitions, so file stats do not prune any
data file from the task
* and only the bloom filter of the data file that contains the row lets it
be read.
*
* <p>{@code readIceberg} measures the read time. {@code
readIcebergLiveHeap} samples the live heap
* during the read, forcing a GC before each sample, and prints the peak
live heap minus the live
* heap before the read, as the mean over the measurement iterations with
its 99.9% confidence
* interval. JMH can't report it as a secondary result because it sums
auxiliary counters across
* iterations.
*
* <p>To run this benchmark for spark-4.2: <code>
* caffeinate -i ./gradlew -DsparkVersions=4.2
:iceberg-spark:iceberg-spark-4.2_2.13:jmh
* -PjmhIncludeRegex=IcebergSourceSharedEqDeleteBenchmark
*
-PjmhOutputPath=benchmark/iceberg-source-shared-eq-delete-benchmark-result.txt
* </code>
*/
@Warmup(iterations = 3)
@Measurement(iterations = 10)
@Timeout(time = 30, timeUnit = TimeUnit.MINUTES)
public class IcebergSourceSharedEqDeleteBenchmark extends
IcebergSourceBenchmark {
private static final int NUM_PARTITIONS = 8;
private static final int NUM_DELETE_FILES = 8;
private static final int NUM_ROWS_PER_FILE = 1_000_000;
private static final int NUM_DELETES_PER_FILE = 200_000;
// in the middle of the ID range of each data file, so that file stats
cannot prune any of them
private static final long SELECTED_ID = (long) NUM_PARTITIONS *
NUM_ROWS_PER_FILE / 2;
private static final long SPLIT_SIZE = 64L * 1024 * 1024 * 1024;
private static final double BYTES_PER_MB = 1024.0 * 1024.0;
private static final double CONFIDENCE = 0.999;
@Param({"0", "0.5", "1"})
private double sharedDeleteFiles;
@Param({"0", "0.5", "1"})
private double sharedDeleteKeys;
@Param({"full", "selective"})
private String read;
@Param({"false", "true"})
private boolean shareEqualityDeletes;
@Param("false")
private boolean cacheDeleteFiles;
@Setup
public void setupBenchmark() throws IOException {
setupSpark();
appendData();
appendEqDeletes();
validateTable();
}
@TearDown
public void tearDownBenchmark() throws IOException {
tearDownSpark();
cleanupFiles();
}
@State(Scope.Thread)
public static class LiveHeapStats {
private final List<Double> iterationMB = Lists.newArrayList();
private final ListStatistics measuredMB = new ListStatistics();
void add(double mb) {
iterationMB.add(mb);
}
@TearDown(Level.Iteration)
public void collect(IterationParams params) {
if (params.getType() == IterationType.MEASUREMENT) {
iterationMB.forEach(measuredMB::addValue);
}
iterationMB.clear();
}
// printed rather than logged so that it shows up next to the JMH results
@TearDown(Level.Trial)
@SuppressWarnings("checkstyle:BanSystemOut")
public void report() {
System.out.printf(
Locale.ROOT,
"%nPeak live heap minus baseline: %.1f ± %.1f MB (99.9%% CI, %d
reads)%n",
measuredMB.getMean(),
measuredMB.getMeanErrorAt(CONFIDENCE),
measuredMB.getN());
}
}
@Benchmark
@Threads(1)
public void readIceberg(Blackhole blackhole) {
withSQLConf(sqlConf(), () -> materialize(load(), blackhole));
}
@Benchmark
@Threads(1)
public void readIcebergLiveHeap(Blackhole blackhole, LiveHeapStats stats)
throws InterruptedException {
LiveHeapSampler sampler = new LiveHeapSampler();
long baseline = sampler.sample();
sampler.start();
try {
withSQLConf(sqlConf(), () -> materialize(load(), blackhole));
} finally {
sampler.stop();
}
stats.add((sampler.peak() - baseline) / BYTES_PER_MB);
}
private Map<String, String> sqlConf() {
return ImmutableMap.of(
SparkSQLProperties.READ_SHARE_EQUALITY_DELETES_ENABLED,
Boolean.toString(shareEqualityDeletes),
SparkSQLProperties.EXECUTOR_CACHE_DELETE_FILES_ENABLED,
Boolean.toString(cacheDeleteFiles));
}
private Dataset<Row> load() {
Dataset<Row> df =
spark()
.read()
.format("iceberg")
.option(SparkReadOptions.SPLIT_SIZE, SPLIT_SIZE)
.load(table().location());
return "selective".equals(read) ?
df.filter(col("id").equalTo(SELECTED_ID)) : df;
}
private void appendData() {
// IDs are interleaved across partitions so that file stats cannot prune
data files
appendAsFile(
spark()
.range((long) NUM_ROWS_PER_FILE * NUM_PARTITIONS)
.select(
col("id"),
expr("CAST(id % " + NUM_PARTITIONS + " AS INT)").as("part"),
expr("CAST(id AS STRING)").as("data")));
table().refresh();
}
private void appendEqDeletes() throws IOException {
Random random = new Random(42);
long numIds = (long) NUM_ROWS_PER_FILE * NUM_PARTITIONS;
int numCommonKeys = (int) (NUM_DELETES_PER_FILE * sharedDeleteKeys);
Set<Long> usedKeys = Sets.newHashSet(SELECTED_ID);
List<Long> commonKeys = randomKeys(random, numIds, numCommonKeys,
usedKeys);
int numGlobalFiles = (int) (NUM_DELETE_FILES * sharedDeleteFiles);
PartitionSpec unpartitioned = table().specs().get(0);
PartitionSpec partitioned = table().spec();
RowDelta rowDelta = table().newRowDelta();
for (int fileNum = 0; fileNum < NUM_DELETE_FILES; fileNum++) {
List<Long> keys = Lists.newArrayList(commonKeys);
keys.addAll(randomKeys(random, numIds, NUM_DELETES_PER_FILE -
numCommonKeys, usedKeys));
if (fileNum < numGlobalFiles) {
writeEqDeletes(keys, unpartitioned,
null).forEach(rowDelta::addDeletes);
} else {
GenericRecord partition =
GenericRecord.create(partitioned.partitionType());
partition.set(0, (fileNum - numGlobalFiles) % NUM_PARTITIONS);
writeEqDeletes(keys, partitioned,
partition).forEach(rowDelta::addDeletes);
}
}
rowDelta.commit();
table().refresh();
}
private static List<Long> randomKeys(
Random random, long numIds, int numKeys, Set<Long> usedKeys) {
List<Long> keys = Lists.newArrayListWithExpectedSize(numKeys);
while (keys.size() < numKeys) {
long key = (long) (random.nextDouble() * numIds);
if (usedKeys.add(key)) {
keys.add(key);
}
}
return keys;
}
private List<DeleteFile> writeEqDeletes(List<Long> keys, PartitionSpec
spec, StructLike partition)
throws IOException {
OutputFileFactory fileFactory =
OutputFileFactory.builderFor(table(), 1,
1).format(fileFormat()).build();
SparkFileWriterFactory writerFactory =
SparkFileWriterFactory.builderFor(table())
.dataFileFormat(fileFormat())
.equalityDeleteRowSchema(table().schema().select("id"))
.equalityFieldIds(new int[]
{table().schema().findField("id").fieldId()})
.build();
ClusteredEqualityDeleteWriter<InternalRow> writer =
new ClusteredEqualityDeleteWriter<>(
writerFactory, fileFactory, table().io(), Long.MAX_VALUE);
try (ClusteredEqualityDeleteWriter<InternalRow> closeableWriter =
writer) {
for (Long key : keys) {
GenericInternalRow row = new GenericInternalRow(1);
row.setLong(0, key);
closeableWriter.write(row, spec, partition);
}
}
return writer.result().deleteFiles();
}
private void validateTable() throws IOException {
Preconditions.checkState(
load().rdd().getNumPartitions() == 1, "Expected the table to be read
by a single task");
try (CloseableIterable<FileScanTask> tasks =
table().newScan().filter(Expressions.equal("id",
SELECTED_ID)).planFiles()) {
int numFiles = Iterables.size(tasks);
Preconditions.checkState(
numFiles == NUM_PARTITIONS,
"Expected file stats to keep all %s data files for the selective
read, got %s",
NUM_PARTITIONS,
numFiles);
}
withSQLConf(
sqlConf(),
() ->
Preconditions.checkState(
spark()
.read()
.format("iceberg")
.load(table().location())
.filter(col("id").equalTo(SELECTED_ID))
.count()
== 1,
"Expected the selective read to return a single row"));
}
@Override
protected Table initTable() {
Schema schema =
new Schema(
required(1, "id", Types.LongType.get()),
required(2, "part", Types.IntegerType.get()),
required(3, "data", Types.StringType.get()));
Map<String, String> properties = Maps.newHashMap();
properties.put(TableProperties.FORMAT_VERSION, "2");
properties.put(TableProperties.PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX +
"id", "true");
properties.put(TableProperties.PARQUET_BLOOM_FILTER_MAX_BYTES,
Integer.toString(4 << 20));
Table table =
new HadoopTables(hadoopConf())
.create(schema, PartitionSpec.unpartitioned(), properties,
newTableLocation());
// global equality deletes belong to the unpartitioned spec
table.updateSpec().addField("part").commit();
return table;
}
@Override
protected Configuration initHadoopConf() {
return new Configuration();
}
@Override
protected FileFormat fileFormat() {
return FileFormat.PARQUET;
}
/** Samples the live heap in the background, forcing a GC before each
sample. */
static class LiveHeapSampler {
private static final long SAMPLE_INTERVAL_MS = 100L;
private final MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
private final Thread thread = new Thread(this::run, "live-heap-sampler");
private volatile boolean stopped = false;
private volatile long peak = 0L;
long sample() {
System.gc();
return memory.getHeapMemoryUsage().getUsed();
}
void start() {
thread.setDaemon(true);
thread.start();
}
void stop() throws InterruptedException {
this.stopped = true;
thread.join();
}
long peak() {
return peak;
}
private void run() {
while (!stopped) {
this.peak = Math.max(peak, sample());
try {
Thread.sleep(SAMPLE_INTERVAL_MS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}
}
}
```
</details>
--
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]