amogh-jahagirdar commented on code in PR #18984: URL: https://github.com/apache/iceberg/pull/18984#discussion_r4589456935
########## core/src/main/java/org/apache/iceberg/V4ManifestWriter.java: ########## @@ -0,0 +1,393 @@ +/* + * 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.Closeable; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Map; +import org.apache.iceberg.encryption.EncryptedOutputFile; +import org.apache.iceberg.encryption.EncryptionKeyMetadata; +import org.apache.iceberg.encryption.NativeEncryptionOutputFile; +import org.apache.iceberg.io.FileAppender; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.types.Types; + +abstract class V4ManifestWriter implements Closeable { + private static final int FORMAT_VERSION = 4; + private static final long UNASSIGNED_SEQ = -1L; + + // TODO: + // - Relativize paths + + static V4ManifestWriter createRoot( + EncryptedOutputFile file, + Map<Integer, PartitionSpec> specsById, + Types.StructType contentStatsType, + Map<String, String> writerProperties, + int tableSchemaId, + long snapshotId, + long sequenceNumber, + long firstRowId) { + Types.StructType partitionType = Partitioning.unionPartitionTypes(specsById.values()); + return new V4ManifestWriter.RootWriter( + file, + specsById, + partitionType, + contentStatsType, + writerProperties, + tableSchemaId, + snapshotId, + sequenceNumber, + firstRowId); + } + + static V4ManifestWriter createLeaf( + EncryptedOutputFile file, + Map<Integer, PartitionSpec> specsById, + Types.StructType contentStatsType, + Map<String, String> writerProperties, + int tableSchemaId, + Long snapshotId) { + Types.StructType partitionType = Partitioning.unionPartitionTypes(specsById.values()); + return new V4ManifestWriter.LeafWriter( + file, + specsById, + partitionType, + contentStatsType, + writerProperties, + tableSchemaId, + snapshotId); + } + + private final OutputFile output; + private final EncryptionKeyMetadata keyMetadata; + private final Schema manifestSchema; + private final Long snapshotId; + private final FileAppender<StructLike> writer; + + private boolean closed = false; + private int recordCount = 0; + private int addedFiles = 0; + private int existingFiles = 0; + private int deletedFiles = 0; + private int replacedFiles = 0; + private int modifiedFiles = 0; + private long addedRows = 0L; + private long existingRows = 0L; + private long deletedRows = 0L; + private long replacedRows = 0L; + private long modifiedRows = 0L; + private long minDataSequenceNumber = UNASSIGNED_SEQ; + private long unassignedRows = 0L; + + private V4ManifestWriter( + EncryptedOutputFile output, + Schema manifestSchema, + Map<String, String> fileMetadata, + Map<String, String> writerProperties, + Long snapshotId) { + this.output = outputFile(output); + this.manifestSchema = manifestSchema; + this.keyMetadata = output.keyMetadata(); + this.snapshotId = snapshotId; + this.writer = newAppender(this.output, fileMetadata, writerProperties); + } + + protected abstract StructLike prepare(TrackedFile file, Tracking tracking); + + // TODO: add row ID space to spec and ManifestInfo + public long assignedRowIds() { + return unassignedRows; + } + + private FileAppender<StructLike> newAppender( + OutputFile file, Map<String, String> fileMetadata, Map<String, String> writerProperties) { + try { + return InternalData.write(FileFormat.PARQUET, file) + .schema(manifestSchema) + .named("tracked_file") + .meta(fileMetadata) + .set(writerProperties) + .overwrite() + .build(); + } catch (IOException e) { + throw new UncheckedIOException( + "Failed to create manifest writer for location: " + file.location(), e); + } + } + + private ManifestInfo summary() { + return new ManifestInfoStruct( + addedFiles, + existingFiles, + deletedFiles, + replacedFiles, + modifiedFiles, + addedRows, + existingRows, + deletedRows, + replacedRows, + modifiedRows, + minDataSequenceNumber, + null, // no manifest DV + FORMAT_VERSION); + } + + public void append(TrackedFile file) { + TrackingBuilder added = TrackingBuilder.added(snapshotId); + if (file.deletionVector() != null) { + added.dvUpdated(); + } + + write(file, added.build()); + } + + public void appendAtSeq(TrackedFile file, long dataSequenceNumber) { + TrackingBuilder added = TrackingBuilder.added(snapshotId, dataSequenceNumber); + if (file.deletionVector() != null) { + added.dvUpdated(); + } + + write(file, added.build()); + } + + public void modify(TrackedFile file, DeletionVector dv) { + TrackingBuilder modified = TrackingBuilder.from(file.tracking(), snapshotId).dvUpdated(); + TrackedFile withNewDV = Delegates.withDV(file, dv); + write(withNewDV, modified.build()); + } + + public void existing(TrackedFile file) { + Tracking existing = TrackingBuilder.from(file.tracking(), snapshotId).build(); + write(file, existing); + } + + public void replace(TrackedFile file) { + Tracking replaced = TrackingBuilder.replaced(file.tracking(), snapshotId); + write(file, replaced); + } + + public void delete(TrackedFile file) { + Tracking deleted = TrackingBuilder.deleted(file.tracking(), snapshotId); + write(file, deleted); + } + + private void write(TrackedFile file, Tracking tracking) { + this.recordCount += 1; + updateManifestInfo(file, tracking); + writer.add(prepare(file, tracking)); + } + + public long length() { + return writer.length(); + } + + @Override + public void close() throws IOException { + this.closed = true; + writer.close(); + } + + private void updateManifestInfo(TrackedFile file, Tracking tracking) { + if (hasLiveSequenceNumber(tracking)) { + updateMinSequenceNumber(tracking.dataSequenceNumber()); + } + + if (tracking.firstRowId() == null) { + this.unassignedRows += file.recordCount(); + } + + switch (tracking.status()) { + case ADDED -> { + this.addedFiles += 1; + this.addedRows += file.recordCount(); + } + case EXISTING -> { + this.existingFiles += 1; + this.existingRows += file.recordCount(); + } + case DELETED -> { + this.deletedFiles += 1; + this.deletedRows += file.recordCount(); + } + case REPLACED -> { + this.replacedFiles += 1; + this.replacedRows += file.recordCount(); + } + case MODIFIED -> { + this.modifiedFiles += 1; + this.modifiedRows += file.recordCount(); + } + } + } + + private boolean hasLiveSequenceNumber(Tracking tracking) { + return tracking.isLive() && tracking.dataSequenceNumber() != null; + } + + private void updateMinSequenceNumber(long sequenceNumber) { + if (minDataSequenceNumber < 0 || sequenceNumber < minDataSequenceNumber) { + this.minDataSequenceNumber = sequenceNumber; + } + } + + public TrackedFile toTrackedManifest() { + Preconditions.checkState(closed, "Cannot build TrackedFile, writer is not closed"); + return new TrackedFileStruct( + null, + FileContent.DATA_MANIFEST, + output.location(), + FileFormat.PARQUET, + recordCount, + writer.length(), + null, // TODO: track spec ID + null, // manifests do not have a partition + null, // TODO: aggregate content stats + false, // stats are not tight for manifests + null, // sort order is null for manifests + null, // no deletion vector + summary(), + keyMetadata.buffer(), + writer.splitOffsets(), + null); // no column files + } + + private static class LeafWriter extends V4ManifestWriter { + private final V4Metadata.LeafTrackedFileWrapper wrapper; + + private LeafWriter( + EncryptedOutputFile output, + Map<Integer, PartitionSpec> specsById, + Types.StructType partitionType, + Types.StructType contentStatsType, + Map<String, String> writerProperties, + int tableSchemaId, + Long snapshotId) { + super( + output, + V4Metadata.leafManifestSchema(partitionType, contentStatsType), + Map.of( + "format-version", + String.valueOf(FORMAT_VERSION), + "schema-id", + String.valueOf(tableSchemaId), + "snapshot-id", + String.valueOf(snapshotId)), Review Comment: `snapshotId` can be null here for the append case, and `String.valueOf` writes the string `"null"` into the footer. Can we write the key only when it's set? ########## core/src/main/java/org/apache/iceberg/V4ManifestWriter.java: ########## @@ -0,0 +1,393 @@ +/* + * 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.Closeable; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.Map; +import org.apache.iceberg.encryption.EncryptedOutputFile; +import org.apache.iceberg.encryption.EncryptionKeyMetadata; +import org.apache.iceberg.encryption.NativeEncryptionOutputFile; +import org.apache.iceberg.io.FileAppender; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.types.Types; + +abstract class V4ManifestWriter implements Closeable { + private static final int FORMAT_VERSION = 4; + private static final long UNASSIGNED_SEQ = -1L; + + // TODO: + // - Relativize paths + + static V4ManifestWriter createRoot( + EncryptedOutputFile file, + Map<Integer, PartitionSpec> specsById, + Types.StructType contentStatsType, + Map<String, String> writerProperties, + int tableSchemaId, + long snapshotId, + long sequenceNumber, + long firstRowId) { + Types.StructType partitionType = Partitioning.unionPartitionTypes(specsById.values()); + return new V4ManifestWriter.RootWriter( + file, + specsById, + partitionType, + contentStatsType, + writerProperties, + tableSchemaId, + snapshotId, + sequenceNumber, + firstRowId); + } + + static V4ManifestWriter createLeaf( + EncryptedOutputFile file, + Map<Integer, PartitionSpec> specsById, + Types.StructType contentStatsType, + Map<String, String> writerProperties, + int tableSchemaId, + Long snapshotId) { + Types.StructType partitionType = Partitioning.unionPartitionTypes(specsById.values()); + return new V4ManifestWriter.LeafWriter( + file, + specsById, + partitionType, + contentStatsType, + writerProperties, + tableSchemaId, + snapshotId); + } + + private final OutputFile output; + private final EncryptionKeyMetadata keyMetadata; + private final Schema manifestSchema; + private final Long snapshotId; + private final FileAppender<StructLike> writer; + + private boolean closed = false; + private int recordCount = 0; + private int addedFiles = 0; + private int existingFiles = 0; + private int deletedFiles = 0; + private int replacedFiles = 0; + private int modifiedFiles = 0; + private long addedRows = 0L; + private long existingRows = 0L; + private long deletedRows = 0L; + private long replacedRows = 0L; + private long modifiedRows = 0L; + private long minDataSequenceNumber = UNASSIGNED_SEQ; + private long unassignedRows = 0L; + + private V4ManifestWriter( + EncryptedOutputFile output, + Schema manifestSchema, + Map<String, String> fileMetadata, + Map<String, String> writerProperties, + Long snapshotId) { + this.output = outputFile(output); + this.manifestSchema = manifestSchema; + this.keyMetadata = output.keyMetadata(); + this.snapshotId = snapshotId; + this.writer = newAppender(this.output, fileMetadata, writerProperties); + } + + protected abstract StructLike prepare(TrackedFile file, Tracking tracking); + + // TODO: add row ID space to spec and ManifestInfo + public long assignedRowIds() { + return unassignedRows; + } + + private FileAppender<StructLike> newAppender( + OutputFile file, Map<String, String> fileMetadata, Map<String, String> writerProperties) { + try { + return InternalData.write(FileFormat.PARQUET, file) + .schema(manifestSchema) + .named("tracked_file") + .meta(fileMetadata) + .set(writerProperties) + .overwrite() + .build(); + } catch (IOException e) { + throw new UncheckedIOException( + "Failed to create manifest writer for location: " + file.location(), e); + } + } + + private ManifestInfo summary() { + return new ManifestInfoStruct( + addedFiles, + existingFiles, + deletedFiles, + replacedFiles, + modifiedFiles, + addedRows, + existingRows, + deletedRows, + replacedRows, + modifiedRows, + minDataSequenceNumber, + null, // no manifest DV + FORMAT_VERSION); + } + + public void append(TrackedFile file) { + TrackingBuilder added = TrackingBuilder.added(snapshotId); + if (file.deletionVector() != null) { + added.dvUpdated(); + } + + write(file, added.build()); + } + + public void appendAtSeq(TrackedFile file, long dataSequenceNumber) { + TrackingBuilder added = TrackingBuilder.added(snapshotId, dataSequenceNumber); + if (file.deletionVector() != null) { + added.dvUpdated(); + } + + write(file, added.build()); + } + + public void modify(TrackedFile file, DeletionVector dv) { + TrackingBuilder modified = TrackingBuilder.from(file.tracking(), snapshotId).dvUpdated(); + TrackedFile withNewDV = Delegates.withDV(file, dv); + write(withNewDV, modified.build()); + } + + public void existing(TrackedFile file) { + Tracking existing = TrackingBuilder.from(file.tracking(), snapshotId).build(); + write(file, existing); + } + + public void replace(TrackedFile file) { + Tracking replaced = TrackingBuilder.replaced(file.tracking(), snapshotId); + write(file, replaced); + } + + public void delete(TrackedFile file) { + Tracking deleted = TrackingBuilder.deleted(file.tracking(), snapshotId); + write(file, deleted); + } + + private void write(TrackedFile file, Tracking tracking) { + this.recordCount += 1; + updateManifestInfo(file, tracking); Review Comment: The counters are updated before `prepare` validates the entry, so a throw leaves them counting an entry that was never written. Can we update them after `prepare` returns instead? ########## core/src/test/java/org/apache/iceberg/TestV4ManifestWriter.java: ########## @@ -0,0 +1,979 @@ +/* + * 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.optional; +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 java.util.Map; +import java.util.Set; +import org.apache.iceberg.encryption.EncryptionUtil; +import org.apache.iceberg.inmemory.InMemoryOutputFile; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Iterables; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.junit.jupiter.api.Test; + +public class TestV4ManifestWriter { + private static final long COMMIT_SNAPSHOT_ID = 42L; + private static final long COMMIT_SEQUENCE_NUMBER = 50L; + private static final long COMMIT_FIRST_ROW_ID = 1_000L; + private static final long RECORD_COUNT = 100L; + private static final Schema SCHEMA = + new Schema( + 1, + optional(1, "id", Types.IntegerType.get()), + optional(2, "data", Types.StringType.get())); + + private static final PartitionSpec TRUNCATE_SPEC = + PartitionSpec.builderFor(SCHEMA).truncate("id", 100).build(); + private static final Map<Integer, PartitionSpec> SPECS = + Map.of(TRUNCATE_SPEC.specId(), TRUNCATE_SPEC); + + private static final MetricsConfig METRICS_CONFIG = + MetricsTestUtil.from(ImmutableMap.of(), SCHEMA); + + private static final Types.StructType STATS_TYPE = + StatsUtil.statsWriteSchema(SCHEMA, METRICS_CONFIG); + + private static final FieldStats<Integer> ID_STATS_0_99 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 0, 99, RECORD_COUNT, 0L, null, null); + private static final FieldStats<Integer> ID_STATS_100_199 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 100, 199, RECORD_COUNT, 0L, null, null); + private static final FieldStats<String> DATA_STATS = + StatsTestUtil.fieldStats(STATS_TYPE, 2, "a", "z", RECORD_COUNT, 20L, null, 2L); + + private static final ContentStatsStruct CONTENT_STATS_A = new ContentStatsStruct(STATS_TYPE); + private static final ContentStatsStruct CONTENT_STATS_B = new ContentStatsStruct(STATS_TYPE); + + static { + CONTENT_STATS_A.setStats(1, ID_STATS_0_99); + CONTENT_STATS_A.setStats(2, DATA_STATS); + CONTENT_STATS_B.setStats(1, ID_STATS_100_199); + CONTENT_STATS_B.setStats(2, DATA_STATS); + } + + // Tracking used for manifests produced in tests + private static final Tracking COMMIT_TRACKING = + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null); + + private static final DeletionVector DV_A = + DeletionVectorStruct.builder() + .location("s3://bucket/db/table/data/file-a-dv.puffin") + .offset(0) + .sizeInBytes(100) + .cardinality(10) + .build(); + + private static final ColumnFile COLUMN_FILE_A = + new ColumnFileStruct( + "s3://bucket/db/table/data/file-a-new-columns.parquet", + Set.of(2), + FileFormat.PARQUET, + 500L, + null); // key metadata + + private static final TrackedFile FILE_A = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, null, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, // unpartitioned + null, // unpartitioned + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_A_WITH_DV = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, 41L, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, + null, + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + DV_A, + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_B = + new TrackedFileStruct( + null, // tracking + FileContent.DATA, + "s3://bucket/db/table/data/file-b.parquet", + FileFormat.PARQUET, + 100, + 1024, + TRUNCATE_SPEC.specId(), + V4TestHelpers.partition(TRUNCATE_SPEC, 100), + CONTENT_STATS_B, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + // Test plan: + // - Append, existing, delete, replace, modify? + // - Basic cases: + // - Data file, v4 data manifest, v3 data manifest, v3 delete manifest + // - Multiple data files, mixed partition specs + // - Paths are relativized (not done yet) + // - Invalid cases that are rejected + // - Cannot write data or delete manifest to leaf + // - data file with manifest info (tested by wrappers) + // - delete file (tested by wrappers) + // - + + @Test + public void rootDataFileAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.append(FILE_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { Review Comment: The two reads check different things, one that the values are physically written and one that consumers read them back. Since both assert the same expectations, that's easy to miss. Can we give each read its own expectations and `.as()` message, like the leaf tests do? ########## core/src/test/java/org/apache/iceberg/TestV4ManifestWriter.java: ########## @@ -0,0 +1,979 @@ +/* + * 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.optional; +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 java.util.Map; +import java.util.Set; +import org.apache.iceberg.encryption.EncryptionUtil; +import org.apache.iceberg.inmemory.InMemoryOutputFile; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Iterables; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.junit.jupiter.api.Test; + +public class TestV4ManifestWriter { + private static final long COMMIT_SNAPSHOT_ID = 42L; + private static final long COMMIT_SEQUENCE_NUMBER = 50L; + private static final long COMMIT_FIRST_ROW_ID = 1_000L; + private static final long RECORD_COUNT = 100L; + private static final Schema SCHEMA = + new Schema( + 1, + optional(1, "id", Types.IntegerType.get()), + optional(2, "data", Types.StringType.get())); + + private static final PartitionSpec TRUNCATE_SPEC = + PartitionSpec.builderFor(SCHEMA).truncate("id", 100).build(); + private static final Map<Integer, PartitionSpec> SPECS = + Map.of(TRUNCATE_SPEC.specId(), TRUNCATE_SPEC); + + private static final MetricsConfig METRICS_CONFIG = + MetricsTestUtil.from(ImmutableMap.of(), SCHEMA); + + private static final Types.StructType STATS_TYPE = + StatsUtil.statsWriteSchema(SCHEMA, METRICS_CONFIG); + + private static final FieldStats<Integer> ID_STATS_0_99 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 0, 99, RECORD_COUNT, 0L, null, null); + private static final FieldStats<Integer> ID_STATS_100_199 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 100, 199, RECORD_COUNT, 0L, null, null); + private static final FieldStats<String> DATA_STATS = + StatsTestUtil.fieldStats(STATS_TYPE, 2, "a", "z", RECORD_COUNT, 20L, null, 2L); + + private static final ContentStatsStruct CONTENT_STATS_A = new ContentStatsStruct(STATS_TYPE); + private static final ContentStatsStruct CONTENT_STATS_B = new ContentStatsStruct(STATS_TYPE); + + static { + CONTENT_STATS_A.setStats(1, ID_STATS_0_99); + CONTENT_STATS_A.setStats(2, DATA_STATS); + CONTENT_STATS_B.setStats(1, ID_STATS_100_199); + CONTENT_STATS_B.setStats(2, DATA_STATS); + } + + // Tracking used for manifests produced in tests + private static final Tracking COMMIT_TRACKING = + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null); + + private static final DeletionVector DV_A = + DeletionVectorStruct.builder() + .location("s3://bucket/db/table/data/file-a-dv.puffin") + .offset(0) + .sizeInBytes(100) + .cardinality(10) + .build(); + + private static final ColumnFile COLUMN_FILE_A = + new ColumnFileStruct( + "s3://bucket/db/table/data/file-a-new-columns.parquet", + Set.of(2), + FileFormat.PARQUET, + 500L, + null); // key metadata + + private static final TrackedFile FILE_A = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, null, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, // unpartitioned + null, // unpartitioned + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_A_WITH_DV = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, 41L, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, + null, + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + DV_A, + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_B = + new TrackedFileStruct( + null, // tracking + FileContent.DATA, + "s3://bucket/db/table/data/file-b.parquet", + FileFormat.PARQUET, + 100, + 1024, + TRUNCATE_SPEC.specId(), + V4TestHelpers.partition(TRUNCATE_SPEC, 100), + CONTENT_STATS_B, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + // Test plan: + // - Append, existing, delete, replace, modify? + // - Basic cases: + // - Data file, v4 data manifest, v3 data manifest, v3 delete manifest + // - Multiple data files, mixed partition specs + // - Paths are relativized (not done yet) + // - Invalid cases that are rejected + // - Cannot write data or delete manifest to leaf + // - data file with manifest info (tested by wrappers) + // - delete file (tested by wrappers) + // - + + @Test + public void rootDataFileAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = Review Comment: The writer setup repeats in every test. Can we add helpers for the root and leaf writers so each test shows only what varies? ########## core/src/test/java/org/apache/iceberg/TestV4ManifestWriter.java: ########## @@ -0,0 +1,979 @@ +/* + * 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.optional; +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 java.util.Map; +import java.util.Set; +import org.apache.iceberg.encryption.EncryptionUtil; +import org.apache.iceberg.inmemory.InMemoryOutputFile; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Iterables; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.junit.jupiter.api.Test; + +public class TestV4ManifestWriter { + private static final long COMMIT_SNAPSHOT_ID = 42L; + private static final long COMMIT_SEQUENCE_NUMBER = 50L; + private static final long COMMIT_FIRST_ROW_ID = 1_000L; + private static final long RECORD_COUNT = 100L; + private static final Schema SCHEMA = + new Schema( + 1, + optional(1, "id", Types.IntegerType.get()), + optional(2, "data", Types.StringType.get())); + + private static final PartitionSpec TRUNCATE_SPEC = + PartitionSpec.builderFor(SCHEMA).truncate("id", 100).build(); + private static final Map<Integer, PartitionSpec> SPECS = + Map.of(TRUNCATE_SPEC.specId(), TRUNCATE_SPEC); + + private static final MetricsConfig METRICS_CONFIG = + MetricsTestUtil.from(ImmutableMap.of(), SCHEMA); + + private static final Types.StructType STATS_TYPE = + StatsUtil.statsWriteSchema(SCHEMA, METRICS_CONFIG); + + private static final FieldStats<Integer> ID_STATS_0_99 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 0, 99, RECORD_COUNT, 0L, null, null); + private static final FieldStats<Integer> ID_STATS_100_199 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 100, 199, RECORD_COUNT, 0L, null, null); + private static final FieldStats<String> DATA_STATS = + StatsTestUtil.fieldStats(STATS_TYPE, 2, "a", "z", RECORD_COUNT, 20L, null, 2L); + + private static final ContentStatsStruct CONTENT_STATS_A = new ContentStatsStruct(STATS_TYPE); + private static final ContentStatsStruct CONTENT_STATS_B = new ContentStatsStruct(STATS_TYPE); + + static { + CONTENT_STATS_A.setStats(1, ID_STATS_0_99); + CONTENT_STATS_A.setStats(2, DATA_STATS); + CONTENT_STATS_B.setStats(1, ID_STATS_100_199); + CONTENT_STATS_B.setStats(2, DATA_STATS); + } + + // Tracking used for manifests produced in tests + private static final Tracking COMMIT_TRACKING = + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null); + + private static final DeletionVector DV_A = + DeletionVectorStruct.builder() + .location("s3://bucket/db/table/data/file-a-dv.puffin") + .offset(0) + .sizeInBytes(100) + .cardinality(10) + .build(); + + private static final ColumnFile COLUMN_FILE_A = + new ColumnFileStruct( + "s3://bucket/db/table/data/file-a-new-columns.parquet", + Set.of(2), + FileFormat.PARQUET, + 500L, + null); // key metadata + + private static final TrackedFile FILE_A = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, null, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, // unpartitioned + null, // unpartitioned + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_A_WITH_DV = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, 41L, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, + null, + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + DV_A, + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_B = + new TrackedFileStruct( + null, // tracking + FileContent.DATA, + "s3://bucket/db/table/data/file-b.parquet", + FileFormat.PARQUET, + 100, + 1024, + TRUNCATE_SPEC.specId(), + V4TestHelpers.partition(TRUNCATE_SPEC, 100), + CONTENT_STATS_B, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + // Test plan: + // - Append, existing, delete, replace, modify? + // - Basic cases: + // - Data file, v4 data manifest, v3 data manifest, v3 delete manifest + // - Multiple data files, mixed partition specs + // - Paths are relativized (not done yet) + // - Invalid cases that are rejected + // - Cannot write data or delete manifest to leaf + // - data file with manifest info (tested by wrappers) + // - delete file (tested by wrappers) + // - + + @Test + public void rootDataFileAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.append(FILE_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileAppendAtDataSeq() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.appendAtSeq(FILE_A, 33L); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + 33L, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileWithDVAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.append(FILE_A_WITH_DV); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata, sets modified snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // added, not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileWithDVModify() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.modify(FILE_A, DV_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + Tracking originalTracking = FILE_A.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the original metadata, sets modified snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.MODIFIED, + originalTracking.snapshotId(), + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + COMMIT_SNAPSHOT_ID, + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileExisting() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.existing(FILE_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + Tracking originalTracking = FILE_A.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the original metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.EXISTING, + originalTracking.snapshotId(), + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + originalTracking.modifiedSnapshotId(), + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileDelete() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.delete(FILE_A_WITH_DV); + } + + assertThat(read(writer, output.toInputFile())).isEmpty(); Review Comment: This asserts reader behavior in a writer test. Filtering deleted entries is the reader's contract and it's already covered by `statusFilter` in `TestV4ManifestReader`, so if the reader broke this would fail with the writer doing everything right. Can we drop it and keep the assertions on the written entry? ########## core/src/test/java/org/apache/iceberg/TestV4ManifestWriter.java: ########## @@ -0,0 +1,979 @@ +/* + * 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.optional; +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 java.util.Map; +import java.util.Set; +import org.apache.iceberg.encryption.EncryptionUtil; +import org.apache.iceberg.inmemory.InMemoryOutputFile; +import org.apache.iceberg.io.CloseableIterable; +import org.apache.iceberg.io.InputFile; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Iterables; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.types.Types; +import org.junit.jupiter.api.Test; + +public class TestV4ManifestWriter { + private static final long COMMIT_SNAPSHOT_ID = 42L; + private static final long COMMIT_SEQUENCE_NUMBER = 50L; + private static final long COMMIT_FIRST_ROW_ID = 1_000L; + private static final long RECORD_COUNT = 100L; + private static final Schema SCHEMA = + new Schema( + 1, + optional(1, "id", Types.IntegerType.get()), + optional(2, "data", Types.StringType.get())); + + private static final PartitionSpec TRUNCATE_SPEC = + PartitionSpec.builderFor(SCHEMA).truncate("id", 100).build(); + private static final Map<Integer, PartitionSpec> SPECS = + Map.of(TRUNCATE_SPEC.specId(), TRUNCATE_SPEC); + + private static final MetricsConfig METRICS_CONFIG = + MetricsTestUtil.from(ImmutableMap.of(), SCHEMA); + + private static final Types.StructType STATS_TYPE = + StatsUtil.statsWriteSchema(SCHEMA, METRICS_CONFIG); + + private static final FieldStats<Integer> ID_STATS_0_99 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 0, 99, RECORD_COUNT, 0L, null, null); + private static final FieldStats<Integer> ID_STATS_100_199 = + StatsTestUtil.fieldStats(STATS_TYPE, 1, 100, 199, RECORD_COUNT, 0L, null, null); + private static final FieldStats<String> DATA_STATS = + StatsTestUtil.fieldStats(STATS_TYPE, 2, "a", "z", RECORD_COUNT, 20L, null, 2L); + + private static final ContentStatsStruct CONTENT_STATS_A = new ContentStatsStruct(STATS_TYPE); + private static final ContentStatsStruct CONTENT_STATS_B = new ContentStatsStruct(STATS_TYPE); + + static { + CONTENT_STATS_A.setStats(1, ID_STATS_0_99); + CONTENT_STATS_A.setStats(2, DATA_STATS); + CONTENT_STATS_B.setStats(1, ID_STATS_100_199); + CONTENT_STATS_B.setStats(2, DATA_STATS); + } + + // Tracking used for manifests produced in tests + private static final Tracking COMMIT_TRACKING = + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null); + + private static final DeletionVector DV_A = + DeletionVectorStruct.builder() + .location("s3://bucket/db/table/data/file-a-dv.puffin") + .offset(0) + .sizeInBytes(100) + .cardinality(10) + .build(); + + private static final ColumnFile COLUMN_FILE_A = + new ColumnFileStruct( + "s3://bucket/db/table/data/file-a-new-columns.parquet", + Set.of(2), + FileFormat.PARQUET, + 500L, + null); // key metadata + + private static final TrackedFile FILE_A = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, null, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, // unpartitioned + null, // unpartitioned + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_A_WITH_DV = + new TrackedFileStruct( + new TrackingStruct(EntryStatus.EXISTING, 40L, 35L, 34L, 41L, 500L, null, null), + FileContent.DATA, + "s3://bucket/db/table/data/file-a.parquet", + FileFormat.PARQUET, + 100, + 1024, + null, + null, + CONTENT_STATS_A, + false, + SortOrder.unsorted().orderId(), + DV_A, + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + private static final TrackedFile FILE_B = + new TrackedFileStruct( + null, // tracking + FileContent.DATA, + "s3://bucket/db/table/data/file-b.parquet", + FileFormat.PARQUET, + 100, + 1024, + TRUNCATE_SPEC.specId(), + V4TestHelpers.partition(TRUNCATE_SPEC, 100), + CONTENT_STATS_B, + false, + SortOrder.unsorted().orderId(), + null, // no DV + null, // manifest info + null, // key metadata, + List.of(4L), + List.of(COLUMN_FILE_A)); + + // Test plan: + // - Append, existing, delete, replace, modify? + // - Basic cases: + // - Data file, v4 data manifest, v3 data manifest, v3 delete manifest + // - Multiple data files, mixed partition specs + // - Paths are relativized (not done yet) + // - Invalid cases that are rejected + // - Cannot write data or delete manifest to leaf + // - data file with manifest info (tested by wrappers) + // - delete file (tested by wrappers) + // - + + @Test + public void rootDataFileAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.append(FILE_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileAppendAtDataSeq() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.appendAtSeq(FILE_A, 33L); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + 33L, + COMMIT_SEQUENCE_NUMBER, + null, // not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileWithDVAppend() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.append(FILE_A_WITH_DV); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the commit metadata, sets modified snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.ADDED, + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_SEQUENCE_NUMBER, + null, // added, not modified + COMMIT_FIRST_ROW_ID, + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileWithDVModify() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.modify(FILE_A, DV_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + Tracking originalTracking = FILE_A.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the original metadata, sets modified snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.MODIFIED, + originalTracking.snapshotId(), + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + COMMIT_SNAPSHOT_ID, + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileExisting() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.existing(FILE_A); + } + + InputFile in = output.toInputFile(); + for (TrackedFile file : List.of(readOne(writer, in), rawReadOne(in))) { + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A); + Tracking originalTracking = FILE_A.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Tracking uses the original metadata") + .isEqualTo( + new TrackingStruct( + EntryStatus.EXISTING, + originalTracking.snapshotId(), + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + originalTracking.modifiedSnapshotId(), + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + } + + @Test + public void rootDataFileDelete() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.delete(FILE_A_WITH_DV); + } + + assertThat(read(writer, output.toInputFile())).isEmpty(); + + TrackedFile file = rawReadOne(output.toInputFile()); + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + Tracking originalTracking = FILE_A_WITH_DV.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Deleted entry preserves original metadata, sets snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.DELETED, + COMMIT_SNAPSHOT_ID, + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + originalTracking.modifiedSnapshotId(), + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + + @Test + public void rootDataFileReplace() throws IOException { + OutputFile output = new InMemoryOutputFile("manifest.parquet"); + V4ManifestWriter writer = + V4ManifestWriter.createRoot( + EncryptionUtil.plainAsEncryptedOutput(output), + Map.of(), + STATS_TYPE, + Map.of(), + SCHEMA.schemaId(), + COMMIT_SNAPSHOT_ID, + COMMIT_SEQUENCE_NUMBER, + COMMIT_FIRST_ROW_ID); + try (writer) { + writer.replace(FILE_A_WITH_DV); + } + + assertThat(read(writer, output.toInputFile())).isEmpty(); + + TrackedFile file = rawReadOne(output.toInputFile()); + assertThat(file) + .usingComparator(V4TestComparators.trackedFileWithoutStatus()) + .isEqualTo(FILE_A_WITH_DV); + Tracking originalTracking = FILE_A_WITH_DV.tracking(); + assertThat(file.tracking()) + .usingComparator(V4TestComparators.TRACKING) + .as("Replaced entry preserves original metadata, sets snapshot ID") + .isEqualTo( + new TrackingStruct( + EntryStatus.REPLACED, + COMMIT_SNAPSHOT_ID, + originalTracking.dataSequenceNumber(), + originalTracking.fileSequenceNumber(), + originalTracking.modifiedSnapshotId(), + originalTracking.firstRowId(), + null, // no change bitmaps + null)); + } + + @Test + public void rootMixedPartitionDataFiles() throws IOException { Review Comment: The assignment rule across appends isn't covered. Can we append two files and check that the second gets the first's `firstRowId + recordCount`, and that `assignedRowIds()` is the total? That's the main thing `RootWriter` adds over the leaf. -- 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]
