Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ private InputFormatConfig() {
public static final int COMMIT_TABLE_THREAD_POOL_SIZE_DEFAULT = 10;
public static final String COMMIT_FILE_THREAD_POOL_SIZE = "iceberg.mr.commit.file.thread.pool.size";
public static final int COMMIT_FILE_THREAD_POOL_SIZE_DEFAULT = 10;
/**
* The threads a DV writer loads the previous deletes of its data files with, ahead of merging them one data file at a
* time; 1 loads each when the writer merges it.
*/
public static final String PREVIOUS_DELETES_LOAD_THREAD_POOL_SIZE =
"iceberg.mr.previous.deletes.load.thread.pool.size";
public static final int PREVIOUS_DELETES_LOAD_THREAD_POOL_SIZE_DEFAULT = 1;

public static final String CASE_SENSITIVE = "iceberg.mr.case.sensitive";
public static final boolean CASE_SENSITIVE_DEFAULT = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* 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.mr.hive.writer;

import java.io.InterruptedIOException;
import java.io.UncheckedIOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.apache.iceberg.util.ThreadPools;

/**
* Loads values on a pool of its own ahead of their use, in the order they are expected to be used, at most a window of
* them at a time: the window bounds what is held, whatever the order of use. A key not loaded ahead (another order, or
* not expected) is loaded when it is used. One thread uses the values; {@link #close} cancels what is still loading.
*/
class BoundedPreloader<K, V> implements AutoCloseable {
private final Function<K, V> load;
private final int window;
private final ExecutorService pool;
private final Iterator<K> ahead;
private final Map<K, Future<V>> loading = Maps.newHashMap();
private final Set<K> used = Sets.newHashSet();

BoundedPreloader(Function<K, V> load, List<K> expectedOrder, int threads, String poolName) {
this.load = load;
this.window = 2 * threads;
this.pool = ThreadPools.newFixedThreadPool(poolName, threads);
this.ahead = expectedOrder.iterator();
loadAhead();
}

/** The value of the key: loaded ahead, or loaded now. */
V get(K key) {
used.add(key);
Future<V> future = loading.remove(key);
if (future == null) {
return load.apply(key);
}
try {
return future.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new UncheckedIOException(new InterruptedIOException("Interrupted while loading " + key));
} catch (ExecutionException e) {
throw e.getCause() instanceof RuntimeException runtime ? runtime : new RuntimeException(e.getCause());
} finally {
loadAhead();
}
}

private void loadAhead() {
while (loading.size() < window && ahead.hasNext()) {
K key = ahead.next();
if (!used.contains(key)) {
loading.put(key, pool.submit(() -> load.apply(key)));
}
}
}

/** The values loaded or loading ahead that are not used yet. */
int heldAhead() {
return loading.size();
}

@Override
public void close() {
loading.values().forEach(future -> future.cancel(true));
loading.clear();
pool.shutdownNow();
try {
pool.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@
package org.apache.iceberg.mr.hive.writer;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.hadoop.conf.Configuration;
import org.apache.iceberg.PartitionKey;
import org.apache.iceberg.PartitionSpec;
import org.apache.iceberg.StructLike;
import org.apache.iceberg.Table;
import org.apache.iceberg.data.CachingDeleteLoader;
import org.apache.iceberg.data.DeleteLoader;
Expand All @@ -45,9 +47,11 @@
import org.apache.iceberg.io.OutputFileFactory;
import org.apache.iceberg.io.PartitioningDVWriter;
import org.apache.iceberg.io.PartitioningWriter;
import org.apache.iceberg.mr.InputFormatConfig;
import org.apache.iceberg.mr.hive.FilesForCommit;
import org.apache.iceberg.mr.hive.writer.WriterBuilder.Context;
import org.apache.iceberg.relocated.com.google.common.base.Suppliers;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
import org.apache.iceberg.util.DeleteFileSet;
import org.apache.iceberg.util.Tasks;
Expand Down Expand Up @@ -133,7 +137,11 @@ static PartitioningWriter<PositionDelete<Record>, DeleteWriteResult> newDeleteWr
DeleteGranularity deleteGranularity = context.deleteGranularity();

if (context.useDVs()) {
return new PartitioningDVWriter<>(files, new PreviousDeleteLoader(table, rewritableDeletes, conf));
PreviousDeleteLoader loader = new PreviousDeleteLoader(table, rewritableDeletes, conf);
PartitioningWriter<PositionDelete<Record>, DeleteWriteResult> writer = new PartitioningDVWriter<>(files, loader);
int threads = conf.getInt(InputFormatConfig.PREVIOUS_DELETES_LOAD_THREAD_POOL_SIZE,
InputFormatConfig.PREVIOUS_DELETES_LOAD_THREAD_POOL_SIZE_DEFAULT);
return threads > 1 ? new PreloadingDVWriter<>(writer, loader, threads) : writer;
}
// partition-scoped position delete writers do not rewrite previous deletes
if (inputOrdered) {
Expand All @@ -151,6 +159,7 @@ static PartitioningWriter<PositionDelete<Record>, DeleteWriteResult> newDeleteWr
private static class PreviousDeleteLoader implements Function<CharSequence, PositionDeleteIndex> {
private final Supplier<Map<String, DeleteFileSet>> deleteFiles;
private final DeleteLoader deleteLoader;
private BoundedPreloader<String, PositionDeleteIndex> preloader;

private PreviousDeleteLoader(Table table, Supplier<Map<String, DeleteFileSet>> deleteFiles, Configuration conf) {
this.deleteFiles = Suppliers.memoize(deleteFiles::get);
Expand All @@ -160,12 +169,80 @@ private PreviousDeleteLoader(Table table, Supplier<Map<String, DeleteFileSet>> d

@Override
public PositionDeleteIndex apply(CharSequence path) {
DeleteFileSet deleteFileSet = deleteFiles.get().get(path.toString());
return preloader != null ? preloader.get(path.toString()) : load(path.toString());
}

private PositionDeleteIndex load(String path) {
DeleteFileSet deleteFileSet = deleteFiles.get().get(path);
if (deleteFileSet == null) {
return null;
}
return deleteLoader.loadPositionDeletes(deleteFileSet, path);
}

/**
* Loads the previous deletes of the data files ahead of their merge, in the given order, on a pool of the task's
* own: at most two per thread are held ahead of the merge.
*/
void preload(List<String> mergeOrder, int threads) {
Map<String, DeleteFileSet> rewritable = deleteFiles.get();
List<String> withDeletes = mergeOrder.stream().filter(rewritable::containsKey).toList();
if (withDeletes.size() > 1) {
LOG.info("Loading the previous deletes of {} data files ahead of their merge on {} threads",
withDeletes.size(), threads);
preloader = new BoundedPreloader<>(this::load, withDeletes, threads, "dv-previous-deletes");
}
}

void stopPreload() {
if (preloader != null) {
preloader.close();
preloader = null;
}
}
}

/**
* A DV writer that loads the previous deletes of its data files ahead of the DV writer's merge, which takes them one
* data file at a time: each load is an object store read the writer would otherwise wait for in turn.
*/
private static class PreloadingDVWriter<T> implements PartitioningWriter<PositionDelete<T>, DeleteWriteResult> {
private final PartitioningWriter<PositionDelete<T>, DeleteWriteResult> writer;
private final PreviousDeleteLoader loader;
private final int threads;
// the DV writer keeps the deletes of its data files in a hash map by path and merges them in its order: a hash map
// of the same paths, put in the same order, iterates the same way (any other order only loses the look-ahead)
private final Map<String, Boolean> mergeOrder = Maps.newHashMap();

private PreloadingDVWriter(PartitioningWriter<PositionDelete<T>, DeleteWriteResult> writer,
PreviousDeleteLoader loader, int threads) {
this.writer = writer;
this.loader = loader;
this.threads = threads;
}

@Override
public void write(PositionDelete<T> delete, PartitionSpec spec, StructLike partition) {
mergeOrder.putIfAbsent(delete.path().toString(), Boolean.TRUE);
writer.write(delete, spec, partition);
}

@Override
public DeleteWriteResult result() {
return writer.result();
}

@Override
public void close() throws IOException {
try {
if (!mergeOrder.isEmpty()) {
loader.preload(Lists.newArrayList(mergeOrder.keySet()), threads);
}
writer.close();
} finally {
loader.stopPreload();
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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.mr.hive.writer;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.IntStream;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class TestBoundedPreloader {

private static List<Integer> keys(int count) {
return IntStream.range(0, count).boxed().toList();
}

@Test
public void theValuesAreLoadedAheadInTheExpectedOrderAtMostTwoPerThread() {
AtomicInteger loads = new AtomicInteger();
Function<Integer, String> load = key -> {
loads.incrementAndGet();
return "v" + key;
};
try (BoundedPreloader<Integer, String> preloader = new BoundedPreloader<>(load, keys(20), 2, "test")) {
assertThat(preloader.heldAhead()).isEqualTo(4);
for (int key = 0; key < 20; key++) {
assertThat(preloader.get(key)).isEqualTo("v" + key);
assertThat(preloader.heldAhead()).isLessThanOrEqualTo(4);
}
assertThat(preloader.heldAhead()).isZero();
}
assertThat(loads.get()).isEqualTo(20);
}

@Test
public void anotherOrderOfUseIsServedAndStaysBounded() {
AtomicInteger loads = new AtomicInteger();
Function<Integer, String> load = key -> {
loads.incrementAndGet();
return "v" + key;
};
List<Integer> reversed = Lists.newArrayList(keys(20));
Collections.reverse(reversed);
try (BoundedPreloader<Integer, String> preloader = new BoundedPreloader<>(load, keys(20), 2, "test")) {
for (int key : reversed) {
assertThat(preloader.get(key)).isEqualTo("v" + key);
assertThat(preloader.heldAhead()).isLessThanOrEqualTo(4);
}
}
// a key used before it was loaded ahead is not loaded ahead again
assertThat(loads.get()).isLessThanOrEqualTo(20 + 4);
}

@Test
public void aKeyNotExpectedIsLoadedWhenUsed() {
try (BoundedPreloader<Integer, String> preloader =
new BoundedPreloader<>(key -> "v" + key, keys(3), 1, "test")) {
assertThat(preloader.get(7)).isEqualTo("v7");
}
}

@Test
public void aFailedLoadSurfacesWhenItsValueIsUsed() {
Function<Integer, String> load = key -> {
if (key == 1) {
throw new IllegalStateException("cannot read " + key);
}
return "v" + key;
};
try (BoundedPreloader<Integer, String> preloader = new BoundedPreloader<>(load, keys(3), 2, "test")) {
assertThat(preloader.get(0)).isEqualTo("v0");
assertThatThrownBy(() -> preloader.get(1)).isInstanceOf(IllegalStateException.class).hasMessage("cannot read 1");
assertThat(preloader.get(2)).isEqualTo("v2");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import org.apache.iceberg.expressions.Expressions;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.mr.Catalogs;
import org.apache.iceberg.mr.InputFormatConfig;
import org.apache.iceberg.mr.hive.IcebergAcidUtil;
import org.apache.iceberg.mr.mapred.Container;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
Expand Down Expand Up @@ -186,6 +187,19 @@ private HiveIcebergWriter deleteWriter() {
*/
@Test
public void testDVWriterDecodesAPositionDeleteFileOncePerQuery() throws IOException, HiveException {
assertDVWriterMergesPreviousDeletes(1);
}

/**
* With several load threads, the DV writer loads the previous deletes of its data files concurrently before it
* merges them, with the same DVs as a writer that loads each in turn.
*/
@Test
public void testDVWriterPreloadsPreviousDeletesConcurrently() throws IOException, HiveException {
assertDVWriterMergesPreviousDeletes(4);
}

private void assertDVWriterMergesPreviousDeletes(int loadThreads) throws IOException, HiveException {
Assume.assumeFalse(partitioned);
helper.appendToTable(RECORDS);
List<String> dataFiles = Lists.newArrayList();
Expand Down Expand Up @@ -214,6 +228,7 @@ public void testDVWriterDecodesAPositionDeleteFileOncePerQuery() throws IOExcept
jc.set(Catalogs.NAME, "dummy");
HiveConf.setVar(jc, HiveConf.ConfVars.HIVE_EXECUTION_ENGINE, "tez");
HiveConf.setVar(jc, HiveConf.ConfVars.HIVE_QUERY_ID, DV_WRITER_QUERY_ID);
jc.setInt(InputFormatConfig.PREVIOUS_DELETES_LOAD_THREAD_POOL_SIZE, loadThreads);

LlapProxy.setDaemon(true);
try {
Expand Down
Loading