This is an automated email from the ASF dual-hosted git repository.
rdblue 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 76e9ed1663 Core: Implement minimal v4 writes in
MergingSnapshotProducer (#19030)
76e9ed1663 is described below
commit 76e9ed1663056af861d72db065ceea06ae21ff34
Author: Ryan Blue <[email protected]>
AuthorDate: Fri Nov 20 14:40:50 2026 -0800
Core: Implement minimal v4 writes in MergingSnapshotProducer (#19030)
---
.../main/java/org/apache/iceberg/FilePlanner.java | 2 +-
.../apache/iceberg/MergingSnapshotProducer.java | 114 ++++++-
.../java/org/apache/iceberg/MetricsConfig.java | 10 +
.../org/apache/iceberg/RootManifestProducer.java | 188 +++++++++++
.../java/org/apache/iceberg/SnapshotProducer.java | 128 +++++---
.../org/apache/iceberg/TrackedFileAdapters.java | 26 +-
.../java/org/apache/iceberg/V4ManifestReader.java | 29 ++
.../apache/iceberg/inmemory/InMemoryFileIO.java | 54 +++-
.../apache/iceberg/inmemory/InMemoryInputFile.java | 34 +-
.../apache/iceberg/AdaptiveMetadataTestBase.java | 299 ++++++++++++++++++
.../java/org/apache/iceberg/InMemoryTables.java | 203 ++++++++++++
.../test/java/org/apache/iceberg/TestAppend.java | 342 +++++++++++++++++++++
.../org/apache/iceberg/TestRemoveSnapshotsV4.java | 43 +--
.../org/apache/iceberg/TestV4ManifestReader.java | 48 +++
.../iceberg/inmemory/TestInMemoryFileIO.java | 2 +-
.../org/apache/iceberg/rest/TestRESTCatalog.java | 36 ++-
16 files changed, 1448 insertions(+), 110 deletions(-)
diff --git a/core/src/main/java/org/apache/iceberg/FilePlanner.java
b/core/src/main/java/org/apache/iceberg/FilePlanner.java
index ec0a2bd928..7b6353b572 100644
--- a/core/src/main/java/org/apache/iceberg/FilePlanner.java
+++ b/core/src/main/java/org/apache/iceberg/FilePlanner.java
@@ -199,7 +199,7 @@ class FilePlanner {
DeleteFile[] deletes = NO_DELETES;
if (dataFile.deletionVector() != null) {
- TrackedFile tracked = TrackedFileAdapters.asTrackedFile(dataFile);
+ TrackedFile tracked =
TrackedFileAdapters.asTrackedFileUnchecked(dataFile);
DeleteFile dv = TrackedFileAdapters.asDVDeleteFile(tracked, specsById);
scanMetrics.dvs().increment();
deletes = new DeleteFile[] {dv};
diff --git a/core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java
b/core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java
index 3b2ce91d22..22050ec886 100644
--- a/core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java
+++ b/core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java
@@ -104,6 +104,9 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
private final SnapshotSummary.Builder appendedManifestsSummary =
SnapshotSummary.builder();
private Expression deleteExpression = Expressions.alwaysFalse();
+ // reused v4 producer
+ private RootManifestProducer rootManifestProducer;
+
// cache new data manifests after writing
private final List<ManifestFile> cachedNewDataManifests =
Lists.newLinkedList();
private boolean hasNewDataFiles = false;
@@ -303,13 +306,19 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
ContentFileUtil.dvDesc(file));
break;
case 3:
- case 4:
Preconditions.checkArgument(
file.content() == FileContent.EQUALITY_DELETES ||
ContentFileUtil.isDV(file),
"Must use DVs for position deletes in V%s: %s",
formatVersion,
file.location());
break;
+ case 4:
+ Preconditions.checkArgument(
+ ContentFileUtil.isDV(file),
+ "Must use DVs for deletes in v%s: %s",
+ formatVersion,
+ file.location());
+ break;
default:
throw new IllegalArgumentException("Unsupported format version: " +
formatVersion);
}
@@ -362,6 +371,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateAddedDataFiles(
TableMetadata base, Long startingSnapshotId, PartitionSet partitionSet,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
addedDataFiles(base, startingSnapshotId, null, partitionSet, parent);
@@ -393,6 +408,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
Long startingSnapshotId,
Expression conflictDetectionFilter,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
addedDataFiles(base, startingSnapshotId, conflictDetectionFilter,
null, parent);
@@ -474,6 +495,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateNoNewDeletesForDataFiles(
TableMetadata base, Long startingSnapshotId, Iterable<DataFile>
dataFiles, Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
validateNoNewDeletesForDataFiles(
base, startingSnapshotId, null, dataFiles,
newDataFilesDataSequenceNumber != null, parent);
}
@@ -494,6 +521,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
Expression dataFilter,
Iterable<DataFile> dataFiles,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
validateNoNewDeletesForDataFiles(
base, startingSnapshotId, dataFilter, dataFiles, false, parent);
}
@@ -528,6 +561,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
return;
}
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
List<DeleteFileIndex> deleteIndexes =
addedDeleteFilesIndexedPerSnapshot(base, startingSnapshotId,
dataFilter, null, parent);
@@ -573,6 +612,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateNoNewDeleteFiles(
TableMetadata base, Long startingSnapshotId, Expression dataFilter,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
Set<String> locations =
referencedDeleteFileLocations(
addedDeleteFilesIndexedPerSnapshot(base, startingSnapshotId,
dataFilter, null, parent));
@@ -594,6 +639,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateNoNewDeleteFiles(
TableMetadata base, Long startingSnapshotId, PartitionSet partitionSet,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
Set<String> locations =
referencedDeleteFileLocations(
addedDeleteFilesIndexedPerSnapshot(
@@ -679,6 +730,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateDeletedDataFiles(
TableMetadata base, Long startingSnapshotId, Expression dataFilter,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
deletedDataFiles(base, startingSnapshotId, dataFilter, null, parent);
@@ -708,6 +765,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
*/
protected void validateDeletedDataFiles(
TableMetadata base, Long startingSnapshotId, PartitionSet partitionSet,
Snapshot parent) {
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
CloseableIterable<ManifestEntry<DataFile>> conflictEntries =
deletedDataFiles(base, startingSnapshotId, null, partitionSet, parent);
@@ -826,6 +889,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
return;
}
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
Set<String> matchingOperations =
skipDeletes
? VALIDATE_DATA_FILES_EXIST_SKIP_DELETE_OPERATIONS
@@ -876,6 +945,12 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
return;
}
+ Long parentId = parent != null ? parent.snapshotId() : null;
+ Preconditions.checkArgument(
+ base.formatVersion() < 4 || Objects.equals(parentId,
startingSnapshotId),
+ "Cannot validate concurrent commit (%s) in v4 table",
+ parentId);
+
// DVs for data files added in this operation can't conflict with
concurrent commits
Set<String> unmatchedReferencedDataFiles =
Sets.newHashSet(dvsByReferencedFile.keySet());
for (DataFileSet dataFiles : newDataFilesBySpec.values()) {
@@ -1025,6 +1100,43 @@ abstract class MergingSnapshotProducer<ThisT> extends
SnapshotProducer<ThisT> {
}
}
+ @Override
+ protected NewSnapshotMetadata writeRootManifest(
+ TableMetadata base, Snapshot parent, long sequenceNumber) {
+ validateDeleteFilesForVersion(base.formatVersion());
+
+ if (addsDeleteFiles()) {
+ throw new UnsupportedOperationException("Cannot add new delete files in
v4");
+ } else if (filterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot remove data files in
v4");
+ } else if (deleteFilterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot remove delete files in
v4");
+ } else if (!appendManifests.isEmpty()) {
+ throw new UnsupportedOperationException("Cannot append manifest files in
v4");
+ }
+
+ if (rootManifestProducer == null || hasNewDataFiles) {
+ this.rootManifestProducer = new RootManifestProducer(ops(),
snapshotId());
+ for (DataFile file : Iterables.concat(newDataFilesBySpec.values())) {
+ rootManifestProducer.appendFile(file);
+ }
+
+ this.hasNewDataFiles = false;
+ }
+
+ TrackedFile result = rootManifestProducer.apply(base, parent,
sequenceNumber);
+
+ summaryBuilder.clear();
+ summaryBuilder.merge(addedDataFilesSummary);
+
+ return new NewSnapshotMetadata(
+ null,
+ result.location(),
+ result.fileSizeInBytes(),
+ rootManifestProducer.assignedRowIds(),
+ rootManifestProducer.manifestLocations());
+ }
+
@Override
public List<ManifestFile> apply(TableMetadata base, Snapshot snapshot) {
validateDeleteFilesForVersion(base.formatVersion());
diff --git a/core/src/main/java/org/apache/iceberg/MetricsConfig.java
b/core/src/main/java/org/apache/iceberg/MetricsConfig.java
index f438c1bc56..a9023d6c47 100644
--- a/core/src/main/java/org/apache/iceberg/MetricsConfig.java
+++ b/core/src/main/java/org/apache/iceberg/MetricsConfig.java
@@ -111,6 +111,16 @@ public final class MetricsConfig implements Serializable {
return from(table.properties(), table.schema(), table.sortOrder(),
table.spec());
}
+ /**
+ * Creates a metrics config from table metadata.
+ *
+ * @param meta a {@link TableMetadata}
+ * @return a metrics config for the given table
+ */
+ static MetricsConfig forTable(TableMetadata meta) {
+ return from(meta.properties(), meta.schema(), meta.sortOrder(),
meta.spec());
+ }
+
public Iterable<Integer> metricsFieldIds() {
Preconditions.checkState(idToName != null, "Cannot resolve column mode by
ID: missing schema");
return Collections.unmodifiableSet(idToName.keySet());
diff --git a/core/src/main/java/org/apache/iceberg/RootManifestProducer.java
b/core/src/main/java/org/apache/iceberg/RootManifestProducer.java
new file mode 100644
index 0000000000..f45f9862f0
--- /dev/null
+++ b/core/src/main/java/org/apache/iceberg/RootManifestProducer.java
@@ -0,0 +1,188 @@
+/*
+ * 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;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.apache.iceberg.encryption.EncryptedOutputFile;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.Types;
+
+/** Responsible for producing v4 root manifest files for a commit. */
+class RootManifestProducer {
+ private final TableOperations ops;
+ private final FileIO io;
+ private final long snapshotId;
+ private final Map<String, String> writerProperties = Map.of();
+ private final List<TrackedFile> appendedDataFiles = Lists.newArrayList();
+
+ // internal state
+ private final String commitUUID = UUID.randomUUID().toString();
+ private final AtomicInteger attempt = new AtomicInteger(0);
+
+ // commit metadata
+ private final Set<String> manifestLocations = Sets.newHashSet();
+ private long assignedRowIds = 0;
+
+ RootManifestProducer(TableOperations ops, long snapshotId) {
+ this.ops = ops;
+ this.io = ops.io();
+ this.snapshotId = snapshotId;
+ }
+
+ void appendFile(DataFile dataFile) {
+ appendedDataFiles.add(TrackedFileAdapters.asTrackedFile(dataFile,
ops.current().schema()));
+ }
+
+ TrackedFile apply(TableMetadata base, Snapshot parent, long
attemptSequenceNumber) {
+ RootMetadata root = RootMetadata.fromSnapshot(base, parent, io);
+
+ manifestLocations.clear();
+ V4ManifestWriter rootWriter = newRootWriter(base, attemptSequenceNumber,
base.nextRowId());
+ try (rootWriter) {
+ for (TrackedFile added : appendedDataFiles) {
+ rootWriter.append(added);
+ }
+
+ if (root != null) {
+ for (TrackedFile file : root.dataFiles()) {
+ if (file.tracking().isLive()) {
+ rootWriter.existing(file);
+ }
+ }
+
+ for (TrackedFile dataManifest : root.dataManifests()) {
+ if (dataManifest.tracking().isLive()) {
+ rootWriter.existing(dataManifest);
+ manifestLocations.add(dataManifest.location());
+ }
+ }
+
+ for (TrackedFile deleteManifest : root.deleteManifests()) {
+ if (deleteManifest.tracking().isLive()) {
+ rootWriter.existing(deleteManifest);
+ manifestLocations.add(deleteManifest.location());
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to write root manifest", e);
+ }
+
+ this.assignedRowIds = rootWriter.assignedRowIds();
+
+ return rootWriter.toTrackedManifest();
+ }
+
+ long assignedRowIds() {
+ return assignedRowIds;
+ }
+
+ Set<String> manifestLocations() {
+ return ImmutableSet.copyOf(manifestLocations);
+ }
+
+ private EncryptedOutputFile newRootOutputFile() {
+ String filename =
+ String.format(
+ Locale.ROOT, "root-%d-%d-%s", snapshotId,
attempt.incrementAndGet(), commitUUID);
+ String rootManifestLocation =
+ ops.metadataFileLocation(FileFormat.PARQUET.addExtension(filename));
+ OutputFile rawOutputFile = ops.io().newOutputFile(rootManifestLocation);
+ return ops.encryption().encrypt(rawOutputFile);
+ }
+
+ private V4ManifestWriter newRootWriter(TableMetadata base, long
sequenceNumber, long firstRowId) {
+ // always use the latest stats type to prevent dropping stats from new
files in the root
+ Types.StructType statsType =
+ StatsUtil.statsWriteSchema(base.schema(),
MetricsConfig.forTable(base));
+ return V4ManifestWriter.createRoot(
+ newRootOutputFile(),
+ base.specsById(),
+ statsType,
+ writerProperties,
+ base.currentSchemaId(),
+ snapshotId,
+ sequenceNumber,
+ firstRowId);
+ }
+
+ private record RootMetadata(
+ List<TrackedFile> dataFiles,
+ List<TrackedFile> dataManifests,
+ List<TrackedFile> deleteManifests) {
+ private static RootMetadata fromRootManifest(TableMetadata meta, Snapshot
snapshot, FileIO io) {
+ ManifestFile root = RootManifestFile.from(snapshot, meta.location(), io);
+
+ ImmutableList.Builder<TrackedFile> rootDataFiles =
ImmutableList.builder();
+ ImmutableList.Builder<TrackedFile> dataManifests =
ImmutableList.builder();
+ ImmutableList.Builder<TrackedFile> deleteManifests =
ImmutableList.builder();
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(root, io, meta.schema(), meta.specsById())
+ .tableLocation(meta.location())
+ .metricsConfig(MetricsConfig.forTable(meta))
+ .build()) {
+
+ for (TrackedFile file : reader) {
+ switch (file.contentType()) {
+ case DATA -> rootDataFiles.add(file);
+ case DATA_MANIFEST -> dataManifests.add(file);
+ case DELETE_MANIFEST -> deleteManifests.add(file);
+ default ->
+ throw new IllegalStateException(
+ String.format(
+ "Invalid %s file in root manifest: %s",
+ file.contentType(), file.location()));
+ }
+ }
+
+ return new RootMetadata(
+ rootDataFiles.build(), dataManifests.build(),
deleteManifests.build());
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to read root manifest: " +
root.path(), e);
+ }
+ }
+
+ private static RootMetadata fromSnapshot(TableMetadata meta, Snapshot
snapshot, FileIO io) {
+ if (snapshot == null) {
+ return null;
+ } else if (snapshot.manifestListLocation() != null) {
+ List<TrackedFile> dataManifests =
+ Lists.transform(snapshot.dataManifests(io),
TrackedFileAdapters::asTrackedFile);
+ List<TrackedFile> deleteManifests =
+ Lists.transform(snapshot.deleteManifests(io),
TrackedFileAdapters::asTrackedFile);
+ return new RootMetadata(ImmutableList.of(), dataManifests,
deleteManifests);
+ }
+
+ return fromRootManifest(meta, snapshot, io);
+ }
+ }
+}
diff --git a/core/src/main/java/org/apache/iceberg/SnapshotProducer.java
b/core/src/main/java/org/apache/iceberg/SnapshotProducer.java
index 74c89b603c..2e707d24f5 100644
--- a/core/src/main/java/org/apache/iceberg/SnapshotProducer.java
+++ b/core/src/main/java/org/apache/iceberg/SnapshotProducer.java
@@ -57,6 +57,7 @@ import org.apache.iceberg.exceptions.CommitFailedException;
import org.apache.iceberg.exceptions.CommitStateUnknownException;
import org.apache.iceberg.exceptions.RuntimeIOException;
import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.io.FileIO;
import org.apache.iceberg.io.OutputFile;
import org.apache.iceberg.metrics.CommitMetrics;
import org.apache.iceberg.metrics.CommitMetricsResult;
@@ -69,7 +70,9 @@ import
org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTest
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.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.apache.iceberg.relocated.com.google.common.math.IntMath;
import org.apache.iceberg.util.Exceptions;
import org.apache.iceberg.util.PropertyUtil;
@@ -109,7 +112,7 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
private final String commitUUID = UUID.randomUUID().toString();
private final AtomicInteger manifestCount = new AtomicInteger(0);
private final AtomicInteger attempt = new AtomicInteger(0);
- private final Map<String, Set<String>> manifestsByManifestList =
Maps.newHashMap();
+ private final Map<String, Set<String>> rootToManifestLocations =
Maps.newHashMap();
private final long targetManifestSizeBytes;
private final FileFormat manifestFormat;
private final Map<String, String> manifestWriterProps;
@@ -286,25 +289,43 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
protected void validate(TableMetadata currentMetadata, Snapshot snapshot) {}
/**
- * Apply the update's changes to the given metadata and snapshot. Return the
new manifest list.
+ * Apply the update's changes to the given metadata and snapshot. Return the
new version's
+ * manifests as a list.
*
* @param metadataToUpdate the base table metadata to apply changes to
- * @param snapshot snapshot to apply the changes to
+ * @param snapshot snapshot to apply the changes to; will be the new
snapshot's parent
* @return a manifest list for the new snapshot.
*/
protected abstract List<ManifestFile> apply(TableMetadata metadataToUpdate,
Snapshot snapshot);
- @Override
- public Snapshot apply() {
- refresh();
- Snapshot parentSnapshot = SnapshotUtil.latestSnapshot(base, targetBranch);
-
- long sequenceNumber = base.nextSequenceNumber();
- Long parentSnapshotId = parentSnapshot == null ? null :
parentSnapshot.snapshotId();
+ /** Result type for root file writes implemented by child operations. */
+ protected record NewSnapshotMetadata(
+ String manifestListLocation,
+ String rootManifestLocation,
+ long rootFileSize,
+ Long assignedRowIds,
+ Set<String> manifestLocations) {
+ private String rootLocation() {
+ return manifestListLocation != null ? manifestListLocation :
rootManifestLocation;
+ }
+ }
- runValidations(parentSnapshot);
+ /**
+ * Apply the update's change to the given metadata and snapshot. Return the
new root manifest
+ * metadata.
+ *
+ * @param metadataToUpdate the base table metadata to apply changes to
+ * @param parent snapshot to apply the changes to; will be the new
snapshot's parent
+ * @param sequenceNumber the sequence number of this commit if it succeeds
+ * @return metadata for the new snapshot, including root manifest location
+ */
+ protected NewSnapshotMetadata writeRootManifest(
+ TableMetadata metadataToUpdate, Snapshot parent, long sequenceNumber) {
+ throw new UnsupportedOperationException("v4 writes are not yet
implemented");
+ }
- List<ManifestFile> manifests = apply(base, parentSnapshot);
+ protected NewSnapshotMetadata writeManifestList(Snapshot parent, long
sequenceNumber) {
+ List<ManifestFile> manifests = apply(base, parent);
OutputFile manifestList = manifestListPath();
@@ -314,16 +335,11 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
manifestList,
ops.encryption(),
snapshotId(),
- parentSnapshotId,
+ parent == null ? null : parent.snapshotId(),
sequenceNumber,
base.nextRowId());
try (writer) {
- // keep track of the manifest lists created and the manifests they
reference
- manifestsByManifestList.put(
- manifestList.location(),
-
manifests.stream().map(ManifestFile::path).collect(Collectors.toSet()));
-
ManifestFile[] manifestFiles = new ManifestFile[manifests.size()];
Tasks.range(manifestFiles.length)
@@ -337,11 +353,39 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
throw new RuntimeIOException(e, "Failed to write manifest list file");
}
+ this.manifestListEncryptionKeys = writer.encryptionKeys();
+ Set<String> manifestLocations =
+ manifests.stream().map(ManifestFile::path).collect(Collectors.toSet());
+ Long assignedRowIds = base.formatVersion() >= 3 ? writer.nextRowId() -
base.nextRowId() : null;
+
+ return new NewSnapshotMetadata(
+ manifestList.location(), null, writer.length(), assignedRowIds,
manifestLocations);
+ }
+
+ @Override
+ public Snapshot apply() {
+ refresh();
+ Snapshot parentSnapshot = SnapshotUtil.latestSnapshot(base, targetBranch);
+
+ long sequenceNumber = base.nextSequenceNumber();
+
+ runValidations(parentSnapshot);
+
+ NewSnapshotMetadata result;
+ if (base.formatVersion() < 4) {
+ result = writeManifestList(parentSnapshot, sequenceNumber);
+ } else {
+ result = writeRootManifest(base, parentSnapshot, sequenceNumber);
+ }
+
+ // keep track of the manifest lists created and the manifests they
reference
+ rootToManifestLocations.put(result.rootLocation(),
result.manifestLocations());
+
Long nextRowId = null;
Long assignedRows = null;
if (base.formatVersion() >= 3) {
nextRowId = base.nextRowId();
- assignedRows = writer.nextRowId() - base.nextRowId();
+ assignedRows = result.assignedRowIds();
}
Map<String, String> summary = summary();
@@ -361,18 +405,16 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
replacedRecords);
}
- this.manifestListEncryptionKeys = writer.encryptionKeys();
-
return new BaseSnapshot(
sequenceNumber,
snapshotId(),
- parentSnapshotId,
+ parentSnapshot == null ? null : parentSnapshot.snapshotId(),
snapshotTimestampMillis(parentSnapshot),
operation(),
summary(base),
base.currentSchemaId(),
- manifestList.location(),
- null, // rootManifest
+ result.manifestListLocation(),
+ result.rootManifestLocation(),
nextRowId,
assignedRows,
manifestListEncryptionKeys != null ?
manifestListEncryptionKeys.fileKey().keyId() : null);
@@ -562,10 +604,10 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
cleanUncommitted(committedManifestPaths(saved));
}
- // also clean up unused manifest lists created by multiple attempts
- for (String manifestList : manifestsByManifestList.keySet()) {
- if (!saved.manifestListLocation().equals(manifestList)) {
- deleteFile(manifestList);
+ // also clean up unused root files created by multiple attempts
+ for (String rootLocation : rootToManifestLocations.keySet()) {
+ if (!rootLocation(saved).equals(rootLocation)) {
+ deleteFile(rootLocation);
}
}
} else {
@@ -587,6 +629,12 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
}
}
+ private static String rootLocation(Snapshot snapshot) {
+ return snapshot.manifestListLocation() != null
+ ? snapshot.manifestListLocation()
+ : snapshot.rootManifestLocation();
+ }
+
private void notifyListeners() {
try {
Object event = updateEvent();
@@ -614,32 +662,30 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
}
protected void cleanAll() {
- for (String manifestList : manifestsByManifestList.keySet()) {
+ for (String manifestList : rootToManifestLocations.keySet()) {
deleteFile(manifestList);
}
- manifestsByManifestList.clear();
+ rootToManifestLocations.clear();
cleanUncommitted(EMPTY_SET);
}
private Set<String> committedManifestPaths(Snapshot saved) {
- Set<String> paths = writtenManifestPaths(saved.manifestListLocation());
+ Set<String> paths = writtenManifestPaths(rootLocation(saved));
if (paths != null) {
// this producer wrote the manifest list, so its manifest paths are
already in memory
return paths;
}
// this producer did not write the manifest list (e.g. a fast-forward
cherry-pick), so read it
- return saved.allManifests(ops.io()).stream()
- .map(ManifestFile::path)
- .collect(Collectors.toSet());
+ return readManifestLocations(saved, base.location(), ops.io());
}
/**
* Returns the paths of the manifests written to the given manifest list, or
null if not written
* by this producer.
*/
- Set<String> writtenManifestPaths(String manifestListLocation) {
- return manifestsByManifestList.get(manifestListLocation);
+ Set<String> writtenManifestPaths(String rootLocation) {
+ return rootToManifestLocations.get(rootLocation);
}
protected void deleteFile(String path) {
@@ -967,4 +1013,14 @@ abstract class SnapshotProducer<ThisT> implements
SnapshotUpdate<ThisT> {
}
}
}
+
+ private static Set<String> readManifestLocations(
+ Snapshot snapshot, String tableLocation, FileIO io) {
+ if (snapshot.rootManifestLocation() != null) {
+ ManifestFile root = RootManifestFile.from(snapshot, tableLocation, io);
+ return Sets.newHashSet(V4ManifestReader.readManifestLocations(root, io));
+ } else {
+ return Sets.newHashSet(Iterables.transform(snapshot.allManifests(io),
ManifestFile::path));
+ }
+ }
}
diff --git a/core/src/main/java/org/apache/iceberg/TrackedFileAdapters.java
b/core/src/main/java/org/apache/iceberg/TrackedFileAdapters.java
index be1ce48270..26d86c158d 100644
--- a/core/src/main/java/org/apache/iceberg/TrackedFileAdapters.java
+++ b/core/src/main/java/org/apache/iceberg/TrackedFileAdapters.java
@@ -48,10 +48,18 @@ class TrackedFileAdapters {
return new TrackedDataFile(file, resolveSpecId(file, specsById));
}
- static TrackedFile asTrackedFile(DataFile file) {
+ static TrackedFile asTrackedFileUnchecked(DataFile file) {
return ((TrackedDataFile) file).file();
}
+ static TrackedFile asTrackedFile(DataFile file, Schema tableSchema) {
+ if (file instanceof TrackedDataFile wrapped) {
+ return wrapped.file();
+ }
+
+ return forDataFile(tableSchema).wrap(file);
+ }
+
static DeleteFile asDVDeleteFile(TrackedFile file, Map<Integer,
PartitionSpec> specsById) {
Preconditions.checkArgument(
file.contentType() == FileContent.DATA,
@@ -69,6 +77,14 @@ class TrackedFileAdapters {
return new TrackedManifestFile(file);
}
+ static TrackedFile asTrackedFile(ManifestFile file) {
+ if (file instanceof TrackedManifestFile wrapper) {
+ return wrapper.file();
+ }
+
+ return forManifestFile().wrap(file);
+ }
+
/** Returns a reusable adapter from {@link DataFile} to {@link TrackedFile}.
*/
static DataTrackedFile forDataFile(Schema tableSchema) {
return new DataTrackedFile(tableSchema);
@@ -437,7 +453,9 @@ class TrackedFileAdapters {
@Override
public long sequenceNumber() {
- return file.tracking().dataSequenceNumber();
+ return file.tracking() != null
+ ? file.tracking().dataSequenceNumber()
+ : ManifestWriter.UNASSIGNED_SEQ;
}
@Override
@@ -447,7 +465,7 @@ class TrackedFileAdapters {
@Override
public Long snapshotId() {
- return file.tracking().snapshotId();
+ return file.tracking() != null ? file.tracking().snapshotId() : null;
}
@Override
@@ -512,7 +530,7 @@ class TrackedFileAdapters {
@Override
public Long firstRowId() {
- return file.tracking().firstRowId();
+ return file.tracking() != null ? file.tracking().firstRowId() : null;
}
@Override
diff --git a/core/src/main/java/org/apache/iceberg/V4ManifestReader.java
b/core/src/main/java/org/apache/iceberg/V4ManifestReader.java
index d63e395b8f..abea2e1878 100644
--- a/core/src/main/java/org/apache/iceberg/V4ManifestReader.java
+++ b/core/src/main/java/org/apache/iceberg/V4ManifestReader.java
@@ -18,6 +18,8 @@
*/
package org.apache.iceberg;
+import java.io.IOException;
+import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -40,6 +42,8 @@ import
org.apache.iceberg.relocated.com.google.common.annotations.VisibleForTest
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.ImmutableSet;
+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.types.RestoreColumns;
@@ -59,6 +63,31 @@ class V4ManifestReader extends CloseableGroup implements
CloseableIterable<Track
TrackedFile.CONTENT_TYPE.fieldId(), // needed for content filtering
TrackedFile.RECORD_COUNT.fieldId()); // needed for first_row_id
assignment and filtering
+ /**
+ * Reads leaf manifest locations from a root manifest file.
+ *
+ * @param root a root {@link ManifestFile}
+ * @param io a {@link FileIO}
+ * @return a list of manifest locations tracked by the root manifest
+ */
+ static List<String> readManifestLocations(ManifestFile root, FileIO io) {
+ try (V4ManifestReader reader =
+ builder(root, io, new Schema(), ImmutableMap.of())
+ .metricsConfig(MetricsConfig.getDefault())
+ .select(TrackedFile.CONTENT_TYPE.name(),
TrackedFile.LOCATION.name())
+ .build()) {
+ Iterable<TrackedFile> manifests =
+ Iterables.filter(
+ reader,
+ file ->
+ file.contentType() == FileContent.DATA_MANIFEST
+ || file.contentType() == FileContent.DELETE_MANIFEST);
+ return Lists.newArrayList(Iterables.transform(manifests,
TrackedFile::location));
+ } catch (IOException e) {
+ throw new UncheckedIOException("Failed to read root manifest: " +
root.path(), e);
+ }
+ }
+
static Builder builder(
ManifestFile manifest, FileIO io, Schema tableSchema, Map<Integer,
PartitionSpec> specsById) {
return new Builder(
diff --git a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryFileIO.java
b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryFileIO.java
index 5a999438c0..6e0c237c00 100644
--- a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryFileIO.java
+++ b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryFileIO.java
@@ -21,16 +21,29 @@ package org.apache.iceberg.inmemory;
import java.util.Map;
import org.apache.iceberg.exceptions.NotFoundException;
import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.FileInfo;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.SupportsPrefixOperations;
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.Maps;
import org.apache.iceberg.util.SerializableMap;
-public class InMemoryFileIO implements FileIO {
+public class InMemoryFileIO implements FileIO, SupportsPrefixOperations {
- private static final Map<String, byte[]> IN_MEMORY_FILES =
Maps.newConcurrentMap();
+ private static class InMemoryFile extends FileInfo {
+ private final byte[] content;
+
+ private InMemoryFile(String location, long size, long createdAtMillis,
byte[] content) {
+ super(location, size, createdAtMillis);
+ Preconditions.checkArgument(content != null, "Invalid content: null");
+ this.content = content;
+ }
+ }
+
+ private static final Map<String, InMemoryFile> IN_MEMORY_FILES =
Maps.newConcurrentMap();
private boolean closed = false;
private SerializableMap<String, String> properties =
SerializableMap.copyOf(ImmutableMap.of());
@@ -46,7 +59,19 @@ public class InMemoryFileIO implements FileIO {
public void addFile(String location, byte[] contents) {
Preconditions.checkState(!closed, "Cannot call addFile after calling
close()");
- IN_MEMORY_FILES.put(location, contents);
+ IN_MEMORY_FILES.put(
+ location,
+ new InMemoryFile(location, contents.length,
System.currentTimeMillis(), contents));
+ }
+
+ public byte[] contents(String location) {
+ Preconditions.checkState(!closed, "Cannot call contents after calling
close()");
+ InMemoryFile info = IN_MEMORY_FILES.get(location);
+ if (info != null) {
+ return info.content;
+ }
+
+ throw new NotFoundException("No in-memory file found for location: %s",
location);
}
public boolean fileExists(String location) {
@@ -56,11 +81,7 @@ public class InMemoryFileIO implements FileIO {
@Override
public InputFile newInputFile(String location) {
Preconditions.checkState(!closed, "Cannot call newInputFile after calling
close()");
- byte[] contents = IN_MEMORY_FILES.get(location);
- if (null == contents) {
- throw new NotFoundException("No in-memory file found for location: %s",
location);
- }
- return new InMemoryInputFile(location, contents);
+ return new InMemoryInputFile(location, this);
}
@Override
@@ -85,4 +106,21 @@ public class InMemoryFileIO implements FileIO {
public void close() {
closed = true;
}
+
+ public void clear() {
+ IN_MEMORY_FILES.clear();
+ }
+
+ @Override
+ public Iterable<FileInfo> listPrefix(String prefix) {
+ return Iterables.transform(
+ Iterables.filter(
+ IN_MEMORY_FILES.values(), (InMemoryFile file) ->
file.location().startsWith(prefix)),
+ FileInfo.class::cast);
+ }
+
+ @Override
+ public void deletePrefix(String prefix) {
+ listPrefix(prefix).forEach(info -> deleteFile(info.location()));
+ }
}
diff --git
a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryInputFile.java
b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryInputFile.java
index 788ae1c1c5..3d3e5a988d 100644
--- a/core/src/main/java/org/apache/iceberg/inmemory/InMemoryInputFile.java
+++ b/core/src/main/java/org/apache/iceberg/inmemory/InMemoryInputFile.java
@@ -21,6 +21,7 @@ package org.apache.iceberg.inmemory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;
+import org.apache.iceberg.exceptions.NotFoundException;
import org.apache.iceberg.io.InputFile;
import org.apache.iceberg.io.SeekableInputStream;
import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
@@ -29,6 +30,7 @@ public class InMemoryInputFile implements InputFile {
private final String location;
private final byte[] contents;
+ private final InMemoryFileIO parentFileIO;
public InMemoryInputFile(byte[] contents) {
this("memory:" + UUID.randomUUID(), contents);
@@ -36,19 +38,25 @@ public class InMemoryInputFile implements InputFile {
public InMemoryInputFile(String location, byte[] contents) {
Preconditions.checkNotNull(location, "location is null");
- Preconditions.checkNotNull(contents, "contents is null");
this.location = location;
- this.contents = contents.clone();
+ this.contents = contents;
+ this.parentFileIO = null;
+ }
+
+ public InMemoryInputFile(String location, InMemoryFileIO parentFileIO) {
+ this.location = location;
+ this.contents = null;
+ this.parentFileIO = parentFileIO;
}
@Override
public long getLength() {
- return contents.length;
+ return content().length;
}
@Override
public SeekableInputStream newStream() {
- return new InMemorySeekableInputStream(contents);
+ return new InMemorySeekableInputStream(content());
}
@Override
@@ -56,9 +64,25 @@ public class InMemoryInputFile implements InputFile {
return location;
}
+ private byte[] content() {
+ if (contents != null) {
+ return contents;
+ } else if (parentFileIO != null) {
+ return parentFileIO.contents(location);
+ }
+
+ throw new NotFoundException("File does not exist: %s", location);
+ }
+
@Override
public boolean exists() {
- return true;
+ if (contents != null) {
+ return true;
+ } else if (parentFileIO != null) {
+ return parentFileIO.fileExists(location);
+ }
+
+ return false;
}
private static class InMemorySeekableInputStream extends SeekableInputStream
{
diff --git
a/core/src/test/java/org/apache/iceberg/AdaptiveMetadataTestBase.java
b/core/src/test/java/org/apache/iceberg/AdaptiveMetadataTestBase.java
new file mode 100644
index 0000000000..1419415e23
--- /dev/null
+++ b/core/src/test/java/org/apache/iceberg/AdaptiveMetadataTestBase.java
@@ -0,0 +1,299 @@
+/*
+ * 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;
+
+import static org.apache.iceberg.types.Types.NestedField.required;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.encryption.EncryptionUtil;
+import org.apache.iceberg.inmemory.InMemoryFileIO;
+import org.apache.iceberg.io.FileInfo;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.io.SupportsPrefixOperations;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
+import org.apache.iceberg.relocated.com.google.common.collect.Iterators;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+
+public class AdaptiveMetadataTestBase {
+ // Schema passed to create tables
+ public static final Schema SCHEMA =
+ new Schema(
+ required(3, "id", Types.IntegerType.get()), required(4, "data",
Types.StringType.get()));
+
+ protected static final int BUCKETS_NUMBER = 16;
+
+ // Partition spec used to create tables
+ public static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(SCHEMA).bucket("data", BUCKETS_NUMBER).build();
+
+ public static final DataFile FILE_A =
+ DataFiles.builder(SPEC)
+ .withPath("file:/warehouse/table/data/data_bucket=0/data-a.parquet")
+ .withFileSizeInBytes(10)
+ .withPartition(TestHelpers.Row.of(0))
+ .withRecordCount(1)
+ .build();
+
+ static final DeleteFile FILE_A_DV =
+ FileMetadata.deleteFileBuilder(SPEC)
+ .ofPositionDeletes()
+
.withPath("file:/warehouse/table/data/data_bucket=0/data-a-deletes.puffin")
+ .withFileSizeInBytes(10)
+ .withPartition(TestHelpers.Row.of(0))
+ .withRecordCount(1)
+ .withReferencedDataFile(FILE_A.location())
+ .withContentOffset(4)
+ .withContentSizeInBytes(6)
+ .build();
+
+ static final DeleteFile FILE_A_EQ_DELETES =
+ FileMetadata.deleteFileBuilder(SPEC)
+ .ofEqualityDeletes(1)
+
.withPath("file:/warehouse/table/data/data_bucket=0/data-a-eq-deletes.parquet")
+ .withFileSizeInBytes(10)
+ .withPartition(TestHelpers.Row.of(0))
+ .withRecordCount(1)
+ .build();
+
+ public static final DataFile FILE_B =
+ DataFiles.builder(SPEC)
+ .withPath("file:/warehouse/table/data/data_bucket=1/data-b.parquet")
+ .withFileSizeInBytes(10)
+ .withPartition(TestHelpers.Row.of(1))
+ .withRecordCount(1)
+ .withSplitOffsets(ImmutableList.of(1L))
+ .build();
+
+ private static final Iterator<FileContent> ALL_DATA_FILES =
Iterators.cycle(FileContent.DATA);
+
+ public InMemoryFileIO io = new InMemoryFileIO();
+ public InMemoryTables.Table defaultTable = null;
+
+ @BeforeEach
+ public void setupTable() throws Exception {
+ this.defaultTable = create("test", SCHEMA, SPEC, 4);
+ }
+
+ @AfterEach
+ public void cleanupTables() {
+ InMemoryTables.clearTables();
+ io.clear();
+ }
+
+ protected InMemoryTables.Table create(
+ String name, Schema schema, PartitionSpec spec, int formatVersion) {
+ return InMemoryTables.create(name, io, schema, spec, formatVersion);
+ }
+
+ protected InMemoryTables.Table load(String name) {
+ return InMemoryTables.load(name, io);
+ }
+
+ protected InMemoryTables.Table upgrade(String name, int newFormatVersion) {
+ return InMemoryTables.upgrade(name, io, newFormatVersion);
+ }
+
+ public TableMetadata readMetadata() {
+ return InMemoryTables.readMetadata("test");
+ }
+
+ protected Snapshot commit(Table table, SnapshotUpdate<?> snapshotUpdate,
String branch) {
+ Snapshot snapshot;
+ if (branch.equals(SnapshotRef.MAIN_BRANCH)) {
+ snapshotUpdate.commit();
+ snapshot = table.currentSnapshot();
+ } else {
+ ((SnapshotProducer<?>) snapshotUpdate.toBranch(branch)).commit();
+ snapshot = table.snapshot(branch);
+ }
+
+ return snapshot;
+ }
+
+ protected Snapshot apply(SnapshotUpdate<?> snapshotUpdate, String branch) {
+ if (branch.equals(SnapshotRef.MAIN_BRANCH)) {
+ return snapshotUpdate.apply();
+ } else {
+ return ((SnapshotProducer<?>) snapshotUpdate.toBranch(branch)).apply();
+ }
+ }
+
+ protected static List<TrackedFile> readRoot(Table table, Snapshot snapshot)
throws IOException {
+ ManifestFile root = RootManifestFile.from(snapshot, table.location(),
table.io());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(root, table.io(), table.schema(),
table.specs())
+ .metricsConfig(MetricsConfig.forTable(table))
+ .tableLocation(table.location())
+ .build()) {
+ return Lists.newArrayList(reader);
+ }
+ }
+
+ protected void validateNoLeafManifests(List<TrackedFile> files) {
+
assertThat(files).extracting(TrackedFile::contentType).containsOnly(FileContent.DATA);
+ }
+
+ protected Iterable<String> listLeafManifests(Table table) {
+ SupportsPrefixOperations fileIO = (SupportsPrefixOperations) table.io();
+ return Iterables.transform(
+ fileIO.listPrefix(table.location() + "/metadata/leaf-"),
FileInfo::location);
+ }
+
+ protected Iterable<String> listRootManifests(Table table) {
+ SupportsPrefixOperations fileIO = (SupportsPrefixOperations) table.io();
+ return Iterables.transform(
+ fileIO.listPrefix(table.location() + "/metadata/root-"),
FileInfo::location);
+ }
+
+ protected ManifestFile writeLeafManifest(Table table, OutputFile output,
DataFile... files)
+ throws IOException {
+ Types.StructType contentStatsType =
+ StatsUtil.statsWriteSchema(table.schema(),
MetricsConfig.forTable(table));
+ TrackedFileAdapters.DataTrackedFile wrapper =
TrackedFileAdapters.forDataFile(table.schema());
+
+ V4ManifestWriter writer =
+ V4ManifestWriter.createLeaf(
+ EncryptionUtil.plainAsEncryptedOutput(output),
+ table.specs(),
+ contentStatsType,
+ Map.of(),
+ table.schema().schemaId(),
+ null);
+ try (writer) {
+ for (DataFile file : files) {
+ writer.append(wrapper.wrap(file));
+ }
+ }
+
+ return TrackedFileAdapters.asManifestFile(writer.toTrackedManifest());
+ }
+
+ protected static Iterator<FileContent> contents(FileContent... contents) {
+ return Iterators.forArray(contents);
+ }
+
+ protected static Iterator<Long> dataSeqs(Long... seqs) {
+ return Iterators.forArray(seqs);
+ }
+
+ protected static Iterator<Long> fileSeqs(Long... seqs) {
+ return Iterators.forArray(seqs);
+ }
+
+ protected static Iterator<Long> ids(Long... ids) {
+ return Iterators.forArray(ids);
+ }
+
+ protected static Iterator<String> locations(String... locations) {
+ return Iterators.forArray(locations);
+ }
+
+ protected static Iterator<String> locations(DataFile... files) {
+ return locations(Arrays.asList(files));
+ }
+
+ protected static Iterator<String> locations(List<DataFile> files) {
+ return Iterables.transform(files, DataFile::location).iterator();
+ }
+
+ protected static Iterator<EntryStatus> statuses(EntryStatus... statuses) {
+ return statuses(Arrays.asList(statuses));
+ }
+
+ protected static Iterator<EntryStatus> statuses(List<EntryStatus> statuses) {
+ return statuses.iterator();
+ }
+
+ protected void validateFiles(
+ List<TrackedFile> files, Iterator<Long> ids, Iterator<String> locations)
{
+ validateFiles(files, ALL_DATA_FILES, null, null, ids, locations, null);
+ }
+
+ protected void validateFiles(
+ List<TrackedFile> files,
+ Iterator<Long> dataSeqs,
+ Iterator<Long> fileSeqs,
+ Iterator<Long> ids,
+ Iterator<String> locations) {
+ validateFiles(files, ALL_DATA_FILES, dataSeqs, fileSeqs, ids, locations,
null);
+ }
+
+ protected void validateFiles(
+ List<TrackedFile> files,
+ Iterator<Long> dataSeqs,
+ Iterator<Long> fileSeqs,
+ Iterator<Long> ids,
+ Iterator<String> locations,
+ Iterator<EntryStatus> statuses) {
+ validateFiles(files, ALL_DATA_FILES, dataSeqs, fileSeqs, ids, locations,
statuses);
+ }
+
+ protected void validateFiles(
+ List<TrackedFile> files,
+ Iterator<FileContent> contents,
+ Iterator<Long> dataSeqs,
+ Iterator<Long> fileSeqs,
+ Iterator<Long> ids,
+ Iterator<String> locations,
+ Iterator<EntryStatus> statuses) {
+ for (TrackedFile file : files) {
+ assertThat(file.contentType()).as("Content
type").isEqualTo(contents.next());
+ assertThat(file.location()).as("Location").isEqualTo(locations.next());
+ assertThat(file.tracking().snapshotId()).as("Snapshot
ID").isEqualTo(ids.next());
+ if (dataSeqs != null) {
+ assertThat(file.tracking().dataSequenceNumber()).as("Data
seq").isEqualTo(dataSeqs.next());
+ }
+
+ if (fileSeqs != null) {
+ assertThat(file.tracking().fileSequenceNumber()).as("File
seq").isEqualTo(fileSeqs.next());
+ }
+
+ if (statuses != null) {
+
assertThat(file.tracking().status()).as("Status").isEqualTo(statuses.next());
+ }
+ }
+
+ assertThat(locations).as("Should match expected number of
files").isExhausted();
+ }
+
+ protected void validateBranchFiles(Table table, String ref, DataFile...
expectedFiles) {
+ validateBranchFiles(table, ref, Arrays.asList(expectedFiles));
+ }
+
+ protected void validateBranchFiles(Table table, String ref,
Iterable<DataFile> expectedFiles) {
+ Set<String> expectedLocations =
+ Sets.newHashSet(Iterables.transform(expectedFiles,
DataFile::location));
+ Set<String> actualLocations =
+ Sets.newHashSet(
+ Iterables.transform(
+ table.newScan().useRef(ref).planFiles(), task ->
task.file().location()));
+ assertThat(actualLocations).as("Files should
match").isEqualTo(expectedLocations);
+ }
+}
diff --git a/core/src/test/java/org/apache/iceberg/InMemoryTables.java
b/core/src/test/java/org/apache/iceberg/InMemoryTables.java
new file mode 100644
index 0000000000..7ed8868c52
--- /dev/null
+++ b/core/src/test/java/org/apache/iceberg/InMemoryTables.java
@@ -0,0 +1,203 @@
+/*
+ * 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;
+
+import static org.apache.iceberg.TableMetadata.newTableMetadata;
+
+import java.util.Map;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.exceptions.CommitFailedException;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.LocationProvider;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+
+public class InMemoryTables {
+
+ private InMemoryTables() {}
+
+ private static final String WAREHOUSE_LOCATION = "memory:/warehouse";
+
+ public static Table upgrade(String name, FileIO io, int newFormatVersion) {
+ Table table = load(name, io);
+ org.apache.iceberg.TableOperations ops = table.ops();
+ TableMetadata base = ops.current();
+ ops.commit(base, ops.current().upgradeToFormatVersion(newFormatVersion));
+ return table;
+ }
+
+ public static Table create(
+ String name, FileIO io, Schema schema, PartitionSpec spec, int
formatVersion) {
+ return createTable(name, io, schema, spec, Map.of(), formatVersion);
+ }
+
+ public static Table create(
+ String name,
+ FileIO io,
+ Schema schema,
+ PartitionSpec spec,
+ Map<String, String> properties,
+ int formatVersion) {
+ return createTable(name, io, schema, spec, properties, formatVersion);
+ }
+
+ private static Table createTable(
+ String name,
+ FileIO io,
+ Schema schema,
+ PartitionSpec spec,
+ Map<String, String> properties,
+ int formatVersion) {
+ TableOperations ops = new TableOperations(name, io);
+ if (ops.current() != null) {
+ throw new AlreadyExistsException("Table already exists: %s", name);
+ }
+
+ String location = WAREHOUSE_LOCATION + "/" + name;
+ TableMetadata metadata =
+ newTableMetadata(schema, spec, SortOrder.unsorted(), location,
properties, formatVersion);
+
+ ops.commit(null, metadata);
+
+ return new Table(ops);
+ }
+
+ public static Table load(String name, FileIO io) {
+ TableOperations ops = new TableOperations(name, io);
+ return new Table(ops);
+ }
+
+ public static class Table extends BaseTable {
+ private final TableOperations ops;
+
+ private Table(TableOperations ops) {
+ super(ops, ops.tableName);
+ this.ops = ops;
+ }
+
+ TableOperations ops() {
+ return ops;
+ }
+ }
+
+ private static final Map<String, TableMetadata> METADATA = Maps.newHashMap();
+ private static final Map<String, Integer> VERSIONS = Maps.newHashMap();
+
+ public static void clearTables() {
+ synchronized (METADATA) {
+ METADATA.clear();
+ VERSIONS.clear();
+ }
+ }
+
+ static TableMetadata readMetadata(String tableName) {
+ synchronized (METADATA) {
+ return METADATA.get(tableName);
+ }
+ }
+
+ static Integer metadataVersion(String tableName) {
+ synchronized (METADATA) {
+ return VERSIONS.get(tableName);
+ }
+ }
+
+ public static class TableOperations implements
org.apache.iceberg.TableOperations {
+ private final String tableName;
+ private final FileIO fileIO;
+ protected TableMetadata current = null;
+ private long lastSnapshotId = 0;
+ private int failCommits = 0;
+
+ public TableOperations(String tableName, FileIO fileIO) {
+ this.tableName = tableName;
+ this.fileIO = fileIO;
+ refresh();
+ if (current != null) {
+ for (Snapshot snap : current.snapshots()) {
+ this.lastSnapshotId = Math.max(lastSnapshotId, snap.snapshotId());
+ }
+ } else {
+ this.lastSnapshotId = 0;
+ }
+ }
+
+ void failCommits(int numFailures) {
+ this.failCommits = numFailures;
+ }
+
+ @Override
+ public TableMetadata current() {
+ return current;
+ }
+
+ @Override
+ public TableMetadata refresh() {
+ synchronized (METADATA) {
+ this.current = METADATA.get(tableName);
+ }
+ return current;
+ }
+
+ @Override
+ public void commit(TableMetadata base, TableMetadata updatedMetadata) {
+ if (base != current) {
+ throw new CommitFailedException("Cannot commit changes based on stale
metadata");
+ }
+ synchronized (METADATA) {
+ refresh();
+ if (base == current) {
+ if (failCommits > 0) {
+ this.failCommits -= 1;
+ throw new CommitFailedException("Injected failure");
+ }
+ Integer version = VERSIONS.get(tableName);
+ // remove changes from the committed metadata
+ this.current =
+ TableMetadata.buildFrom(updatedMetadata)
+ .discardChanges()
+ .withMetadataLocation((current != null) ?
current.metadataFileLocation() : null)
+ .build();
+ VERSIONS.put(tableName, version == null ? 0 : version + 1);
+ METADATA.put(tableName, current);
+ } else {
+ throw new CommitFailedException(
+ "Commit failed: table was updated at %d",
current.lastUpdatedMillis());
+ }
+ }
+ }
+
+ @Override
+ public FileIO io() {
+ return fileIO;
+ }
+
+ @Override
+ public LocationProvider locationProvider() {
+ Preconditions.checkNotNull(
+ current, "Current metadata should not be null when locationProvider
is called");
+ return LocationProviders.locationsFor(current.location(),
current.properties());
+ }
+
+ @Override
+ public String metadataFileLocation(String fileName) {
+ return current.location() + "/metadata/" + fileName;
+ }
+ }
+}
diff --git a/core/src/test/java/org/apache/iceberg/TestAppend.java
b/core/src/test/java/org/apache/iceberg/TestAppend.java
new file mode 100644
index 0000000000..ad791d1df7
--- /dev/null
+++ b/core/src/test/java/org/apache/iceberg/TestAppend.java
@@ -0,0 +1,342 @@
+/*
+ * 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;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.iceberg.exceptions.CommitFailedException;
+import org.apache.iceberg.io.OutputFile;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.FieldSource;
+
+public class TestAppend extends AdaptiveMetadataTestBase {
+ private static final List<String> BRANCHES = List.of("main", "branch");
+
+ @Test
+ public void appendNullFile() {
+ assertThatThrownBy(() ->
defaultTable.newAppend().appendFile(null).commit())
+ .isInstanceOf(NullPointerException.class)
+ .hasMessage("Invalid data file: null");
+ }
+
+ @Test
+ public void appendManifest() throws IOException {
+ OutputFile output =
+
io.newOutputFile("memory:/warehouse/table/metadata/append-manifest.parquet");
+ ManifestFile manifest = writeLeafManifest(defaultTable, output, FILE_A,
FILE_B);
+ AppendFiles append = defaultTable.newAppend().appendManifest(manifest);
+ assertThatThrownBy(append::commit)
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessage("Cannot append manifest files in v4");
+ }
+
+ @Test
+ public void removeDataFile() {
+ defaultTable.newAppend().appendFile(FILE_A).appendFile(FILE_B).commit();
+ MergingSnapshotProducer<?> producer = (MergeAppend)
defaultTable.newAppend();
+ producer.delete(FILE_A);
+ assertThatThrownBy(producer::commit)
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessage("Cannot remove data files in v4");
+ }
+
+ @Test
+ public void addDeleteFile() {
+ defaultTable.newAppend().appendFile(FILE_A).appendFile(FILE_B).commit();
+ MergingSnapshotProducer<?> producer = (MergeAppend)
defaultTable.newAppend();
+ producer.add(FILE_A_DV);
+ assertThatThrownBy(producer::commit)
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessage("Cannot add new delete files in v4");
+ }
+
+ @Test
+ public void removeDeleteFile() {
+ MergingSnapshotProducer<?> producer = (MergeAppend)
defaultTable.newAppend();
+ producer.delete(FILE_A_EQ_DELETES);
+ assertThatThrownBy(producer::commit)
+ .isInstanceOf(UnsupportedOperationException.class)
+ .hasMessage("Cannot remove delete files in v4");
+ }
+
+ @ParameterizedTest
+ @FieldSource("BRANCHES")
+ public void emptyTableAppend(String branch) throws IOException {
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0);
+
+ TableMetadata base = readMetadata();
+ assertThat(base.currentSnapshot()).isNull();
+ assertThat(base.lastSequenceNumber()).isEqualTo(0);
+
+ Snapshot committedSnapshot =
+ commit(
+ defaultTable,
defaultTable.newAppend().appendFile(FILE_A).appendFile(FILE_B), branch);
+
+ assertThat(committedSnapshot).isNotNull();
+ assertThat(defaultTable.ops().current().lastSequenceNumber()).isEqualTo(1);
+
+ long snapshotId = committedSnapshot.snapshotId();
+
+ List<TrackedFile> rootFiles = readRoot(defaultTable, committedSnapshot);
+ validateNoLeafManifests(rootFiles);
+ validateFiles(
+ rootFiles,
+ dataSeqs(1L, 1L),
+ fileSeqs(1L, 1L),
+ ids(snapshotId, snapshotId),
+ locations(FILE_A, FILE_B),
+ statuses(EntryStatus.ADDED, EntryStatus.ADDED));
+
+ validateBranchFiles(defaultTable, branch, FILE_A, FILE_B);
+ }
+
+ @Test
+ public void appendWithDifferentSpecs() throws IOException {
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0);
+
+ TableMetadata base = readMetadata();
+ assertThat(base.currentSnapshot()).as("Should not have a current
snapshot").isNull();
+ assertThat(base.lastSequenceNumber()).as("Last sequence number should be
0").isEqualTo(0);
+
+ defaultTable.updateSpec().addField("id").commit();
+ PartitionSpec newSpec = defaultTable.spec();
+
+ assertThat(defaultTable.specs()).as("Table should have 2
specs").hasSize(2);
+
+ DataFile fileNewSpec =
+ DataFiles.builder(newSpec)
+
.withPath("memory:/warehouse/table/data/data_bucket=0/id=0/data-b.parquet")
+ .withPartition(TestHelpers.Row.of(0, 0))
+ .withFileSizeInBytes(10)
+ .withRecordCount(1)
+ .build();
+
+
defaultTable.newAppend().appendFile(FILE_A).appendFile(fileNewSpec).commit();
+ Snapshot committedSnapshot = defaultTable.currentSnapshot();
+
+ assertThat(committedSnapshot).as("Should create a snapshot").isNotNull();
+ assertThat(defaultTable.ops().current().lastSequenceNumber()).isEqualTo(1);
+
+ long snapshotId = committedSnapshot.snapshotId();
+
+ List<TrackedFile> rootFiles = readRoot(defaultTable, committedSnapshot);
+ validateNoLeafManifests(rootFiles);
+ validateFiles(
+ rootFiles,
+ dataSeqs(1L, 1L),
+ fileSeqs(1L, 1L),
+ ids(snapshotId, snapshotId),
+ locations(FILE_A, fileNewSpec),
+ statuses(EntryStatus.ADDED, EntryStatus.ADDED));
+ }
+
+ @Test
+ public void concurrentAppends() throws IOException {
+ defaultTable.updateProperties().set("random-snapshot-ids", "true");
+ AppendFiles append = defaultTable.newAppend().appendFile(FILE_A);
+ Snapshot pending = append.apply();
+ assertThat(defaultTable.currentSnapshot()).isNull();
+ assertThat(pending).isNotNull();
+ assertThat(pending.sequenceNumber()).isEqualTo(1);
+ validateFiles(
+ readRoot(defaultTable, pending),
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(pending.snapshotId()),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+ // use a separate table instance to test recovery
+ Table separateInstance = load("test");
+ separateInstance.newAppend().appendFile(FILE_B).commit();
+ Snapshot concurrent = separateInstance.currentSnapshot();
+ assertThat(concurrent).isNotNull();
+ assertThat(concurrent.sequenceNumber()).isEqualTo(1);
+ validateFiles(
+ readRoot(defaultTable, concurrent),
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(concurrent.snapshotId()),
+ locations(FILE_B),
+ statuses(EntryStatus.ADDED));
+
+ assertThat(defaultTable.currentSnapshot()).as("Original Table is
unchanged").isNull();
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(
+ pending.rootManifestLocation(), concurrent.rootManifestLocation());
+
+ append.commit();
+ Snapshot latest = defaultTable.currentSnapshot();
+
assertThat(latest.rootManifestLocation()).isNotEqualTo(pending.rootManifestLocation());
+ assertThat(latest.snapshotId()).isEqualTo(pending.snapshotId());
+ assertThat(latest.parentId()).isEqualTo(concurrent.snapshotId());
+ assertThat(latest.sequenceNumber()).isEqualTo(2);
+ validateFiles(
+ readRoot(defaultTable, latest),
+ dataSeqs(2L, 1L),
+ fileSeqs(2L, 1L),
+ ids(pending.snapshotId(), concurrent.snapshotId()),
+ locations(FILE_A, FILE_B),
+ statuses(EntryStatus.ADDED, EntryStatus.EXISTING));
+
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(
+ latest.rootManifestLocation(), concurrent.rootManifestLocation());
+ }
+
+ @Test
+ public void appendToUpgradedTable() throws IOException {
+ Table v3Table = create("upgraded_table", SCHEMA, SPEC, 3);
+ v3Table.newAppend().appendFile(FILE_A).commit();
+ Snapshot v3Snapshot = v3Table.currentSnapshot();
+ long v3SnapshotId = v3Snapshot.snapshotId();
+
+ assertThat(v3Snapshot.allManifests(io)).hasSize(1);
+ ManifestFile v3Manifest = v3Snapshot.allManifests(io).get(0);
+
+ Table upgraded = upgrade("upgraded_table", 4);
+ upgraded.newAppend().appendFile(FILE_B).commit();
+ Snapshot snapshot = upgraded.currentSnapshot();
+ long snapshotId = snapshot.snapshotId();
+
+ List<TrackedFile> rootFiles = readRoot(upgraded, snapshot);
+ validateFiles(
+ rootFiles,
+ contents(FileContent.DATA, FileContent.DATA_MANIFEST),
+ dataSeqs(2L, 1L),
+ fileSeqs(2L, 1L),
+ ids(snapshotId, v3SnapshotId),
+ locations(FILE_B.location(), v3Manifest.path()),
+ statuses(EntryStatus.ADDED, EntryStatus.EXISTING));
+ }
+
+ @Test
+ public void failureCleanup() throws IOException {
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0);
+
+ defaultTable.newAppend().appendFile(FILE_A).commit();
+ Snapshot snap = defaultTable.currentSnapshot();
+
+ long baseId = snap.snapshotId();
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(1);
+
+ validateFiles(
+ readRoot(defaultTable, snap),
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(baseId),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+ defaultTable.ops().failCommits(5);
+
+ AppendFiles append = defaultTable.newAppend().appendFile(FILE_B);
+ Snapshot pending = append.apply();
+
+ String pendingRootLocation = pending.rootManifestLocation();
+
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(pendingRootLocation,
snap.rootManifestLocation());
+ validateFiles(
+ readRoot(defaultTable, pending),
+ ids(pending.snapshotId(), baseId),
+ locations(FILE_B, FILE_A));
+
+ assertThatThrownBy(append::commit)
+ .isInstanceOf(CommitFailedException.class)
+ .hasMessage("Injected failure");
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(1);
+
+ Snapshot latest = defaultTable.currentSnapshot();
+ assertThat(latest.snapshotId()).as("Should not have a new
commit").isEqualTo(snap.snapshotId());
+
+ List<TrackedFile> files = readRoot(defaultTable, latest);
+ validateNoLeafManifests(files);
+ validateFiles(
+ files,
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(baseId),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(snap.rootManifestLocation());
+ }
+
+ @Test
+ public void recoveryAndCleanup() throws IOException {
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(0);
+
+ defaultTable.newAppend().appendFile(FILE_A).commit();
+ Snapshot snap = defaultTable.currentSnapshot();
+
+ long baseId = snap.snapshotId();
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(1);
+
+ validateFiles(
+ readRoot(defaultTable, snap),
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(baseId),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+ defaultTable.ops().failCommits(3);
+
+ AppendFiles append = defaultTable.newAppend().appendFile(FILE_B);
+ Snapshot pending = append.apply();
+
+ String pendingRootLocation = pending.rootManifestLocation();
+
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(pendingRootLocation,
snap.rootManifestLocation());
+ validateFiles(
+ readRoot(defaultTable, pending),
+ dataSeqs(2L, 1L),
+ fileSeqs(2L, 1L),
+ ids(pending.snapshotId(), baseId),
+ locations(FILE_B, FILE_A),
+ statuses(EntryStatus.ADDED, EntryStatus.EXISTING));
+
+ append.commit();
+ assertThat(readMetadata().lastSequenceNumber()).isEqualTo(2);
+
+ Snapshot latest = defaultTable.currentSnapshot();
+ assertThat(latest.rootManifestLocation())
+ .as("Pending root manifest should be rewritten")
+ .isNotEqualTo(pendingRootLocation);
+ assertThat(listRootManifests(defaultTable))
+ .containsExactlyInAnyOrder(latest.rootManifestLocation(),
snap.rootManifestLocation());
+
+ List<TrackedFile> files = readRoot(defaultTable, latest);
+ validateNoLeafManifests(files);
+ validateFiles(
+ files,
+ dataSeqs(2L, 1L),
+ fileSeqs(2L, 1L),
+ ids(latest.snapshotId(), baseId),
+ locations(FILE_B, FILE_A),
+ statuses(EntryStatus.ADDED, EntryStatus.EXISTING));
+ }
+}
diff --git a/core/src/test/java/org/apache/iceberg/TestRemoveSnapshotsV4.java
b/core/src/test/java/org/apache/iceberg/TestRemoveSnapshotsV4.java
index 5aafa83a88..762a9cf34e 100644
--- a/core/src/test/java/org/apache/iceberg/TestRemoveSnapshotsV4.java
+++ b/core/src/test/java/org/apache/iceberg/TestRemoveSnapshotsV4.java
@@ -21,28 +21,22 @@ package org.apache.iceberg;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import java.io.File;
import java.util.Set;
import org.apache.iceberg.exceptions.ValidationException;
-import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
import org.apache.iceberg.relocated.com.google.common.collect.Sets;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
-class TestRemoveSnapshotsV4 {
+class TestRemoveSnapshotsV4 extends AdaptiveMetadataTestBase {
private static final String CLEANUP_UNSUPPORTED_MESSAGE =
"File cleanup for V4 tables is not supported. "
+ "Use CleanupLevel.NONE to skip file cleanup.";
- private static final long ROOT_MANIFEST_SNAPSHOT_ID = 42L;
-
- @TempDir private File tableDir;
@AfterEach
void clearTables() {
- TestTables.clearTables();
+ InMemoryTables.clearTables();
}
@ParameterizedTest
@@ -87,36 +81,9 @@ class TestRemoveSnapshotsV4 {
}
private Table tableWithRootManifestSnapshot() {
- Table table =
- TestTables.create(
- tableDir, "test", TestBase.SCHEMA, TestBase.SPEC,
SortOrder.unsorted(), 3);
- table.newAppend().appendFile(TestBase.FILE_A).commit();
-
- table.updateProperties().set("format-version", "4").commit();
-
- TableOperations ops = ((HasTableOperations) table).operations();
- TableMetadata base = ops.current();
- Snapshot parent = base.currentSnapshot();
- Snapshot rootManifestSnapshot =
- new BaseSnapshot(
- base.lastSequenceNumber() + 1,
- ROOT_MANIFEST_SNAPSHOT_ID,
- parent.snapshotId(),
- parent.timestampMillis() + 1,
- DataOperations.APPEND,
- ImmutableMap.of(),
- base.currentSchemaId(),
- null,
- "file:/nonexistent/root-manifest.parquet",
- base.nextRowId(),
- 0L,
- null);
- ops.commit(
- base,
- TableMetadata.buildFrom(base)
- .setBranchSnapshot(rootManifestSnapshot, SnapshotRef.MAIN_BRANCH)
- .build());
- table.refresh();
+ Table table = create("table", SCHEMA, SPEC, 4);
+ table.newAppend().appendFile(FILE_A).commit();
+ table.newAppend().appendFile(FILE_B).commit();
return table;
}
}
diff --git a/core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java
b/core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java
index d49f7d77c6..54211f13a8 100644
--- a/core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java
+++ b/core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java
@@ -2057,6 +2057,54 @@ class TestV4ManifestReader {
assertGeospatialBounds(readOne(builder), geomLower, geomUpper, geogLower,
geogUpper);
}
+ @ParameterizedTest
+ @FieldSource("MANIFEST_FORMATS")
+ public void readManifestLocations(FileFormat format) throws IOException {
+ TrackedFile dataFile =
+ dataFile(
+ new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null,
null, null, null, null),
+ "s3://bucket/table/data-file.parquet");
+ TrackedFile deletedDataManifest =
+ V4TestHelpers.manifestRefWithTracking(
+ new TrackingStruct(
+ EntryStatus.DELETED, SNAPSHOT_ID, null, null, null, null,
null, null),
+ FileContent.DATA_MANIFEST,
+ "s3://bucket/table/deleted-data-manifest.parquet");
+ TrackedFile dataManifest =
+ V4TestHelpers.manifestRefWithTracking(
+ new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null,
null, null, null, null),
+ FileContent.DATA_MANIFEST,
+ "s3://bucket/table/data-manifest.parquet");
+ TrackedFile deletedDeleteManifest =
+ V4TestHelpers.manifestRefWithTracking(
+ new TrackingStruct(
+ EntryStatus.DELETED, SNAPSHOT_ID, null, null, null, null,
null, null),
+ FileContent.DELETE_MANIFEST,
+ "s3://bucket/table/deleted-delete-manifest.parquet");
+ TrackedFile deleteManifest =
+ V4TestHelpers.manifestRefWithTracking(
+ new TrackingStruct(
+ EntryStatus.EXISTING, SNAPSHOT_ID, null, null, null, null,
null, null),
+ FileContent.DELETE_MANIFEST,
+ "s3://bucket/table/delete-manifest.parquet");
+
+ ManifestFile manifest =
+ writeManifest(
+ format,
+ UNPARTITIONED_TYPE,
+ ImmutableList.of(
+ dataFile,
+ deletedDataManifest,
+ dataManifest,
+ deletedDeleteManifest,
+ deleteManifest));
+ when(manifest.firstRowId()).thenReturn(1_000L);
+
+ List<String> locations = V4ManifestReader.readManifestLocations(manifest,
IO);
+
+ assertThat(locations).containsExactly(dataManifest.location(),
deleteManifest.location());
+ }
+
private static ContentStats contentStats(
Types.StructType statsType,
GeospatialBound geomLower,
diff --git
a/core/src/test/java/org/apache/iceberg/inmemory/TestInMemoryFileIO.java
b/core/src/test/java/org/apache/iceberg/inmemory/TestInMemoryFileIO.java
index 97e5d29f4e..1b770314ee 100644
--- a/core/src/test/java/org/apache/iceberg/inmemory/TestInMemoryFileIO.java
+++ b/core/src/test/java/org/apache/iceberg/inmemory/TestInMemoryFileIO.java
@@ -59,7 +59,7 @@ public class TestInMemoryFileIO {
public void testNewInputFileNotFound() {
InMemoryFileIO fileIO = new InMemoryFileIO();
assertThatExceptionOfType(NotFoundException.class)
- .isThrownBy(() -> fileIO.newInputFile("s3://nonexistent/file"))
+ .isThrownBy(() ->
fileIO.newInputFile("s3://nonexistent/file").newStream())
.withMessageContaining("No in-memory file found");
}
diff --git a/core/src/test/java/org/apache/iceberg/rest/TestRESTCatalog.java
b/core/src/test/java/org/apache/iceberg/rest/TestRESTCatalog.java
index 32b292309e..d37cf3d753 100644
--- a/core/src/test/java/org/apache/iceberg/rest/TestRESTCatalog.java
+++ b/core/src/test/java/org/apache/iceberg/rest/TestRESTCatalog.java
@@ -2632,10 +2632,12 @@ public class TestRESTCatalog extends
CatalogTests<RESTCatalog> {
UpdateTableRequest body = (UpdateTableRequest) req.body();
MetadataUpdate.AddSnapshot addSnapshot =
(MetadataUpdate.AddSnapshot) body.updates().get(0);
- assertThatThrownBy(
- () ->
table.io().newInputFile(addSnapshot.snapshot().manifestListLocation()))
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining("No in-memory file found");
+ assertThat(
+ table
+ .io()
+
.newInputFile(addSnapshot.snapshot().manifestListLocation())
+ .exists())
+ .isFalse();
});
}
@@ -2710,14 +2712,13 @@ public class TestRESTCatalog extends
CatalogTests<RESTCatalog> {
assertThat(appendSnapshot).isPresent();
MetadataUpdate.AddSnapshot addSnapshot =
(MetadataUpdate.AddSnapshot) appendSnapshot.get();
- assertThatThrownBy(
- () ->
- catalog
- .loadTable(TABLE)
- .io()
-
.newInputFile(addSnapshot.snapshot().manifestListLocation()))
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining("No in-memory file found");
+ assertThat(
+ catalog
+ .loadTable(TABLE)
+ .io()
+
.newInputFile(addSnapshot.snapshot().manifestListLocation())
+ .exists())
+ .isFalse();
});
}
@@ -2870,10 +2871,13 @@ public class TestRESTCatalog extends
CatalogTests<RESTCatalog> {
MetadataUpdate.AddSnapshot addSnapshot =
(MetadataUpdate.AddSnapshot) appendSnapshot.get();
String manifestListLocation =
addSnapshot.snapshot().manifestListLocation();
- assertThatThrownBy(
- () ->
catalog.loadTable(TABLE).io().newInputFile(manifestListLocation))
- .isInstanceOf(NotFoundException.class)
- .hasMessageContaining("No in-memory file found");
+ assertThat(
+ catalog
+ .loadTable(TABLE)
+ .io()
+
.newInputFile(addSnapshot.snapshot().manifestListLocation())
+ .exists())
+ .isFalse();
});
}