danielcweeks commented on code in PR #19030:
URL: https://github.com/apache/iceberg/pull/19030#discussion_r4637311403
##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -1025,6 +1100,39 @@ private void validateDeleteFilesForVersion(int
currentFormatVersion) {
}
}
+ @Override
+ protected NewSnapshotMetadata writeRootManifest(
+ TableMetadata base, Snapshot parent, long sequenceNumber) {
+ validateDeleteFilesForVersion(base.formatVersion());
+
+ if (addsDeleteFiles()) {
+ throw new UnsupportedOperationException("Cannot commit new delete files
to v4 table");
+ } else if (filterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot commit deleted data
files to v4");
+ } else if (deleteFilterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot commit deleted delete
files to v4");
+ }
Review Comment:
This was flagged for me because there are other paths that this doesn't
capture (like `appendManifests()`) and will silently drop files.
<!-- lenses: blue-review, nastra-test-review -->
##########
core/src/test/java/org/apache/iceberg/TestAppend.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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");
+ }
+
+ @ParameterizedTest
+ @FieldSource("BRANCHES")
+ public void testEmptyTableAppend(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 testAppendWithDifferentSpecs() 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("file:/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));
Review Comment:
This doesn't actually assert what the name indicates because we don't check
which spec was written to.
<!-- lenses: nastra-test-review -->
##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -1025,6 +1100,39 @@ private void validateDeleteFilesForVersion(int
currentFormatVersion) {
}
}
+ @Override
+ protected NewSnapshotMetadata writeRootManifest(
+ TableMetadata base, Snapshot parent, long sequenceNumber) {
+ validateDeleteFilesForVersion(base.formatVersion());
+
+ if (addsDeleteFiles()) {
+ throw new UnsupportedOperationException("Cannot commit new delete files
to v4 table");
+ } else if (filterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot commit deleted data
files to v4");
+ } else if (deleteFilterManager.containsDeletes()) {
+ throw new UnsupportedOperationException("Cannot commit deleted delete
files to v4");
+ }
+
+ if (rootManifestProducer == null || hasNewDataFiles) {
Review Comment:
I don't think we're actually getting reuse here because we rebuild on retry.
<!-- lenses: weeks-review, russell-review, blue-review -->
##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -362,6 +371,12 @@ private ManifestFile copyManifest(ManifestFile manifest) {
*/
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);
Review Comment:
We're doing this check in lots of places now. Is the plan to remove it or
should we pull it into a single helper class?
<!-- lenses: weeks-review, russell-review, blue-review, nastra-test-review
-->
##########
core/src/main/java/org/apache/iceberg/MergingSnapshotProducer.java:
##########
@@ -303,13 +306,19 @@ private static void
validateDeleteFileForVersion(DeleteFile file, int formatVers
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 position deletes in V%s: %s",
+ formatVersion,
+ file.location());
+ break;
Review Comment:
nit: v4 removes equality deletes, but the message still says "Must use DVs
for position deletes", which is confusing
<!-- lenses: russell-review, nastra-test-review -->
##########
core/src/test/java/org/apache/iceberg/TestAppend.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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");
+ }
+
+ @ParameterizedTest
+ @FieldSource("BRANCHES")
+ public void testEmptyTableAppend(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 testAppendWithDifferentSpecs() 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("file:/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 testFailure() 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(defaultTable.io().newInputFile(pendingRootLocation).exists()).isTrue();
+ 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();
+
+ List<TrackedFile> files = readRoot(defaultTable, latest);
+ validateNoLeafManifests(files);
+ validateFiles(
+ files,
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(baseId),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+
assertThat(defaultTable.io().newInputFile(pendingRootLocation).exists()).isFalse();
+ }
+
+ @Test
+ public void testRecovery() 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(1);
+
Review Comment:
It looks like `failCommits` doesn't change the parent, so the retry rewrites
the same root. It would probably be better to have a separate commit involved.
<!-- lenses: russell-review -->
##########
core/src/test/java/org/apache/iceberg/TestAppend.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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");
+ }
+
+ @ParameterizedTest
+ @FieldSource("BRANCHES")
+ public void testEmptyTableAppend(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 testAppendWithDifferentSpecs() 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("file:/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 testFailure() 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(defaultTable.io().newInputFile(pendingRootLocation).exists()).isTrue();
+ 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();
+
+ List<TrackedFile> files = readRoot(defaultTable, latest);
+ validateNoLeafManifests(files);
+ validateFiles(
+ files,
+ dataSeqs(1L),
+ fileSeqs(1L),
+ ids(baseId),
+ locations(FILE_A),
+ statuses(EntryStatus.ADDED));
+
+
assertThat(defaultTable.io().newInputFile(pendingRootLocation).exists()).isFalse();
+ }
+
+ @Test
+ public void testRecovery() 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(1);
+
+ AppendFiles append = defaultTable.newAppend().appendFile(FILE_B);
+ Snapshot pending = append.apply();
+
+ String pendingRootLocation = pending.rootManifestLocation();
+
+
assertThat(defaultTable.io().newInputFile(pendingRootLocation).exists()).isTrue();
+ 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(defaultTable.io().newInputFile(pendingRootLocation).exists()).isFalse();
Review Comment:
nit: it would be nice to add an `as()` context here since this will just
result in something like "expected false, but got true".
<!-- lenses: nastra-test-review -->
##########
core/src/test/java/org/apache/iceberg/TestAppend.java:
##########
@@ -0,0 +1,216 @@
+/*
+ * 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.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");
+ }
+
+ @ParameterizedTest
+ @FieldSource("BRANCHES")
+ public void testEmptyTableAppend(String branch) throws IOException {
Review Comment:
nit: I think we're avoiding `test` prefix for new tests (here and other
places).
<!-- lenses: nastra-test-review -->
##########
core/src/main/java/org/apache/iceberg/SnapshotProducer.java:
##########
@@ -286,25 +289,42 @@ public ThisT deleteWith(Consumer<String> deleteCallback) {
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
+ * @return a {@link TrackedFile} for the new root manifest
+ */
Review Comment:
nit: the javadoc says this returns a `TrackedFile`, but it returns
`NewSnapshotMetadata`. It's also missing `@param sequenceNumber`.
<!-- lenses: weeks-review, russell-review, blue-review -->
##########
core/src/main/java/org/apache/iceberg/RootManifestProducer.java:
##########
@@ -0,0 +1,192 @@
+/*
+ * 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.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 Types.StructType contentStatsType;
+ private final int startingSchemaId;
+ 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);
+ private final AtomicInteger manifestCount = 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;
+ this.contentStatsType =
+ StatsUtil.statsWriteSchema(ops.current().schema(),
MetricsConfig.forTable(ops.current()));
+ this.startingSchemaId = ops.current().currentSchemaId();
+ }
+
+ 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 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())
+ .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);
Review Comment:
I don't think this gets tested. We could add a test with a v3 + append,
then upgrade to v4 + append.
<!-- lenses: weeks-review, russell-review, nastra-test-review -->
--
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]