You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by "anoopj (via GitHub)" <gi...@apache.org> on 2026/06/24 22:07:28 UTC
[PR] Core: Add v4 manifest reader [iceberg]
anoopj opened a new pull request, #16958:
URL: https://github.com/apache/iceberg/pull/16958
The reader supports:
- column projection
- partition pruning via a row filter, including multi-spec manifests
Content stats reading and metadata inheritance are not yet implemented.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3664424297
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
Review Comment:
nit: maybe `MANIFEST_FORMATS`? Or alternative name the parameter in the test methods in a way that indicates that this is the format of the manifest
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3661551959
##########
core/src/test/java/org/apache/iceberg/TestTrackedFileStruct.java:
##########
@@ -33,13 +33,9 @@
class TestTrackedFileStruct {
private static final int FORMAT_VERSION_V4 = 4;
- private static final Types.StructType PARTITION_TYPE =
- Types.StructType.of(
- Types.NestedField.optional(1000, "id_bucket", Types.IntegerType.get()),
- Types.NestedField.optional(1001, "category", Types.StringType.get()));
private static final List<Types.NestedField> FIELDS =
Review Comment:
This name is confusing based on how it's defined. It looks like it's supposed to be empty, but can only assume we're holding the default read fields, right? Why not call it something more like `DEFAULT_FIELDS`?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670091702
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
Review Comment:
Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3589298561
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final boolean reuseContainers;
Review Comment:
Responding below.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3555903784
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // Always project tracking and content type. status drives live-file filtering, and content
+ // type distinguishes data, delete, and manifest-reference entries.
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+
+ // Force-project the remaining fields the partition filter reads, regardless of caller
+ // projection.
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
Review Comment:
Didn't know about `TypeUtil`. Fixed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540546356
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
Review Comment:
Yeah, not for things that are currently being worked on. The TODO should not catch anything. Tests should catch when something is missing.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540544690
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // Always project tracking and content type. status drives live-file filtering, and content
+ // type distinguishes data, delete, and manifest-reference entries.
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+
+ // Force-project the remaining fields the partition filter reads, regardless of caller
+ // projection.
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
Review Comment:
Why is this performing its own projection rather than using `TypeUtil` methods?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540539701
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
Review Comment:
I would expect the builder to handle schema projection. Why do this here instead of in the builder?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540406652
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
This is a good point, but I don't have a name suggestion that is better right now. Let's keep it in mind.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540404401
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
+ */
+ static StructType partitionType(Schema schema, Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allActiveFieldIds(schema, specs));
Review Comment:
I don't think using `allActiveFieldIds` is correct here.
That method will filter out partition fields when the source is no longer part of the table schema. In some cases (bucket joins), that is fine because the data is still partitioned by a subset of its partition fields.
However, for a partition type that can hold any partition tuple, it doesn't work. Equality deletes are matched using partition tuple equality. For example, say I have `file_a.parquet` in partition `(id_bucket=7, is_test=false)`, and I also have a delete file `deletes.parquet` in partition `(id_bucket=7, is_test=true)`. The delete file does not apply to the data file because they are in different partitions.
With the use of `allActiveFieldIds` here, dropping the `is_test` identity partition and then the `is_test` column from the table would result in a unified partition type that only has `id_bucket`. As a result, checking whether the partition matches (and the deletes should be applied) will pass for `file_a.parquet` and `deletes.parquet`.
This needs to union all partition fields so that we don't drop tuple values that define equality.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3548168670
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
+ */
+ static StructType partitionType(Schema schema, Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allActiveFieldIds(schema, specs));
Review Comment:
Thanks for pointing this out - I didn't think about this scenario. We can fix it by dropping the filter on active fields, but there might be another problem: partition specs don't store the type, and we derive it based on the type of the source column. So if the source column doesn't exist in the schema anymore, we can't derive the partition type. I think this might be working in v3 because of the way the reader is implemented: the reader gets the schema from the Avro schema, and uses it instead of the schema from the metadata.
Maybe the Parquet reader can also work that way (can verify), but is this by design? Does the other Iceberg implementations actually work in this scenario in v3 if this detail is not in the spec?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640866148
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
+ Schema projection = projection(fullSchema);
+ if (projection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for live filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (hasPartitionFilter()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ projectedIds.addAll(TypeUtil.getProjectedIds(unionPartitionType));
+ }
+
+ // list and map fields cannot be projected by ID; their element IDs carry the selection
+ projectedIds.removeIf(
Review Comment:
It wasn't necessary because it turns out `getProjectedIds()` already returns list element IDs, not the list field IDs. Removed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640887920
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
Review Comment:
restructured along these lines.
A couple of deviations to call out: (1) content stats stay stubbed as an empty struct in this PR, so the stats-ID union + StatsUtil.statsReadSchema in the scan-planning branch is the target for the stats PR; (2) I kept select/project resolving in build() rather than eagerly resolving in select() needs caseSensitive, set by a separate builder method, so eager resolution would need an ordering guarantee. So we will need to do it in build.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640934440
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
Review Comment:
I renamed it it to `includeNonLive()`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640932417
##########
core/src/main/java/org/apache/iceberg/TrackedFile.java:
##########
@@ -95,20 +96,39 @@ interface TrackedFile {
Types.ListType.ofRequired(136, Types.IntegerType.get()),
"Field ids used to determine row equality in equality delete files");
- static Types.StructType schemaWithContentStats(
+ /**
+ * Returns the schema for the given partition and content stats types.
+ *
+ * <p>The partition and content stats fields use {@link Types.UnknownType} when their types have
+ * no fields, so that they are not stored in manifest files.
+ */
+ static Types.StructType schema(
Types.StructType partitionType, Types.StructType contentStatsType) {
+ return schema(Tracking.schema(), partitionType, contentStatsType);
+ }
+
+ /** Returns the schema with the given tracking, partition, and content stats types. */
+ static Types.StructType schema(
Review Comment:
I have removed the method.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642085457
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
+ return new V4ManifestReader(
+ file,
+ readSchema(hasPartitionFilter),
+ partitionEvaluators,
+ partitionProjections,
+ includeAll,
+ scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ Schema projection = fileProjection;
+ if (columns != null) {
+ projection =
+ caseSensitive ? fullSchema.select(columns) : fullSchema.caseInsensitiveSelect(columns);
+ }
+
+ if (projection == null) {
+ if (scanPlanning) {
+ // scan planning does not read the change-tracking fields omitted by SCAN_TYPE
+ return TypeUtil.replaceFieldTypes(
+ fullSchema,
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.SCAN_TYPE));
+ }
+
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for liveness filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (rowFilter != Expressions.alwaysTrue()) {
+ // record_count is read when evaluating a filter against file metrics
+ projectedIds.add(TrackedFile.RECORD_COUNT.fieldId());
+ }
+
+ if (hasPartitionFilter) {
Review Comment:
I was initially confused by this. I think it could use a comment to clarify that this is for user-requested schemas (select or project called):
```java
// For user-requested schemas, only add the partition tuple if it is needed for filtering
if (hasPartitionFilter) { ... }
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648809493
##########
core/src/test/java/org/apache/iceberg/TestTrackedFileStruct.java:
##########
@@ -359,12 +355,12 @@ void serializationRoundTrip(RoundTripSerializer<TrackedFileStruct> serializer) t
FileContent.DATA,
FORMAT_VERSION_V4,
"s3://bucket/data/file.parquet",
- FileFormat.PARQUET,
- null, // PartitionData has its own serialization tests
+ FileFormat.PARQUET, // PartitionData has its own serialization tests
Review Comment:
Yes, i forgot to adjust when we changed the constructor order. Fixed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648035810
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
Review Comment:
You're right that the DATA_MANIFEST/DELETE_MANIFEST cases are unreachable today. The history: `matchesPartition` used to handle manifests itself, but per an earlier [review comment](https://github.com/apache/iceberg/pull/16958#discussion_r3583527549) the manifest check was lifted to the call site (isManifest(entry) || matchesPartition(entry)) so matchesPartition only does partition filtering. That's what makes those two cases dead right now.
I kept the switch exhaustive rather than reducing it to DATA/EQUALITY_DELETES so that if manifest-level pruning is added later, the skip metrics are already correct and a manifest reaching here can't be silently miscounted.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648271399
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
Review Comment:
I think that this should be a constant since it is a DV made from only constants.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648381992
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
Review Comment:
Prefer `Iterables.getOnlyElement` rather than `get(0)`. That will fail if there are unexpected items.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648371940
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
Review Comment:
This is a good test. I'd prefer to remove the additional logic that I commented on above and use just this test. I'd also prefer to use different file types, not just data files.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648363868
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
Review Comment:
Same comment as above. These aren't really round trips, they are single-record reads. And if we are testing a few specific records like this, can't this be a parameterized test of a single record with fixed cases?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648430367
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
Review Comment:
I don't see the utility of this test. A list field should behave like any other.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501355425
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
Review Comment:
Done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501783689
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
Review Comment:
The branch is intentional: when the table is _fully_ unpartitioned there's no partition tuple, so we just don't project the field. Happy to switch to that if we want null per #17000, but the explicit omit is clearer here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3518992916
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
Review Comment:
We are wrong here with adding only the `status`. See my above comment
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3518776622
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
`specId` is an optional field in the V4 schema. I double checked the proposal doc and the spec PR and none of them gives extra info on the behavior difference between leaf manifest and data/delete file entries.
I get the point, we return early for leaf manifests so here we only have data/delete entries where we expect `specId` not to be null. I think in the spec we should articulate better that it is mandatory for those entries. Will leave a comment.
Since the field is optional, shouldn't we have an extra Preconditions check to verify that?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3493620540
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
Review Comment:
As a followup of today's discussion, we will keep the partition tuple for planning/pruning for now and we can move to content stats based pruning later. This implementation in this PR is purely a pruning optimization, so swapping/removing it has no correctness implications.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3494077847
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
`TrackedFile` is an abstraction that we want to keep internal for now. `V4ManifestReader` is the best name I could come up with. Open to other suggestions here. cc @rdblue for his thoughts.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3484747517
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
Review Comment:
On the read path, we don't use builders. `Tracking` here comes from deserializing the manifest and not from a builder.
But i think the check here is not needed for a different reason. We have made `Tracking` a required field, so the internal reader should throw before prepare() runs. So this check is likely redundant.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
Review Comment:
They look symmetric but the underlying mechanism differs. ROW_POSITION is synthesized by the reader itself. FILE_PATH us only populated when the caller injects it. I'd lean toward keeping the manual set for now
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field with {@link MetadataColumns#ROW_POSITION} appended so the reader
+ * populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
Review Comment:
Your understanding correct! `Tracking.schema()` is the on-disk schema. `TrackingStruct.BASE_TYPE` is the same schema plus `row_position`. We can reuse it. I just needed to change the visibility of `TrackingStruct.BASE_TYPE` from private to package private.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501336943
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
Review Comment:
Generally we don't add many TODOs in the code (I got past feedback on this).
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501648007
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
Review Comment:
Replaced.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501721074
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
Review Comment:
Removed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540546356
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
Review Comment:
Yeah, not for things that are currently being worked on.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670183006
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
Review Comment:
moved to the arrow form
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648464037
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
Review Comment:
Where are the other partitioning tests? I would expect partitioning cases to be co-located and this suite has not yet tested filtering when there are files with different specs.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642118115
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
Review Comment:
This should not be calling `set`. Is there a PR to fix `DeletionVectorStruct`?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640955137
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
+ Schema projection = projection(fullSchema);
+ if (projection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for live filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (hasPartitionFilter()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ projectedIds.addAll(TypeUtil.getProjectedIds(unionPartitionType));
+ }
+
+ // list and map fields cannot be projected by ID; their element IDs carry the selection
+ projectedIds.removeIf(
+ id -> {
+ Types.NestedField field = fullSchema.findField(id);
+ return field != null && (field.type().isListType() || field.type().isMapType());
+ });
+
+ // project instead of select to preserve narrow struct projections from the caller
+ return TypeUtil.project(fullSchema, projectedIds);
+ }
+
+ private Schema projection(Schema fullSchema) {
Review Comment:
I have inlined it. I think it reads better now.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641079854
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
Review Comment:
was the initial version use `liveOnly()` for the builder config? I thought that was a good name.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640855684
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
Review Comment:
Done as suggested
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642003319
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
Review Comment:
I don't think this state check is necessary. This can only happen if there is a bug in the builder below, which is responsible for creating both maps. It could just as easily create a single map: `Map<Integer, Pair<Evaluator, StructProjection>>` and avoid this case entirely. It's fine to use two maps to represent this, but if we do we should rely on the builder to construct these maps correctly.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3643203189
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
Review Comment:
this method name doesn't match what is tested inside anymore, which also has `includeAll` tested.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
Review Comment:
I think Ryan meant this API from `Comparators`
```
public static Comparator<StructLike> forType(Types.StructType struct)
```
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
Review Comment:
`tracking.status` and `content_type` are always added even if not selected/projected. I am wondering if `location` should also always be projected. isn't it needed for all read scenarios?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646998440
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
Review Comment:
Thanks for the tip. Done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647208744
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
Review Comment:
Done. I annotated the positional `TrackingStruct` args in `fileWithStatus` as well.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648767759
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
Review Comment:
Thanks. Added.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648782454
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
Review Comment:
deleted it.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648955899
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
Review Comment:
flipped the dataFile helper to dataFile(location, specId, partition)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648953658
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
Review Comment:
yes. done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648966819
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnknownManifestFormatThrows(FileFormat format) throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = V4ManifestReader.builder(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithUnknownSpec(FileFormat format) throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithNullSpecId(FileFormat format) throws IOException {
Review Comment:
i don't think it's covered elsewhere. We have `testPartitionFilterKeepsFileWithUnknownSpec` for a file whose spec ID isn't in the reader's specsById while this one has a null spec ID. they follow different code paths, so worth having a test.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648970837
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
Review Comment:
refactored to a `DV` constant
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3598156949
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(partitionType, spec.partitionType()));
+ }
+ }
+
+ return new V4ManifestReader(
+ file, readSchema(), partitionEvaluators, partitionProjections, onlyLive, scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !partitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
Review Comment:
Two loops here could go away.
**Loop at 240-249 (replacing `TRACKING`'s type with `SCAN_TRACKING`)** doesn't need to exist at all — build the right shape up front instead of building the wrong shape and rewriting it. Give `TrackedFile.schema` an overload that takes the tracking type:
```java
// in TrackedFile.java
static Types.StructType schema(
Types.StructType partitionType, Types.StructType contentStatsType) {
return schema(Tracking.schema(), partitionType, contentStatsType);
}
static Types.StructType schema(
Types.StructType trackingType,
Types.StructType partitionType,
Types.StructType contentStatsType) {
return Types.StructType.of(
Types.NestedField.required(TRACKING.fieldId(), TRACKING.name(), trackingType, TRACKING.doc()),
CONTENT_TYPE,
FORMAT_VERSION,
LOCATION,
// ...rest unchanged
);
}
```
**Loop at 256-259 (collecting projected field IDs)** is `TypeUtil.getProjectedIds`:
```java
Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(fileProjection));
```
Pairs with the `Tracking.scanSchema()` suggestion above. `readSchema()` collapses to:
```java
private Schema readSchema() {
Schema fullSchema = new Schema(
TrackedFile.schema(Tracking.scanSchema(), partitionType, Types.StructType.of()).fields());
if (fileProjection == null) {
return fullSchema;
}
Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(fileProjection));
projectedIds.add(TrackedFile.TRACKING.fieldId());
projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
if (hasPartitionFilter()) {
projectedIds.add(TrackedFile.SPEC_ID.fieldId());
projectedIds.add(TrackedFile.PARTITION_ID);
}
return TypeUtil.select(fullSchema, projectedIds);
}
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668813160
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
Review Comment:
The naming here is too generic. This actually tests filtering for matching files across disjoint specs.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670138972
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
Review Comment:
Renamed to ID_PARTITIONING_SPECS, matching the ID_PARTITION_TYPE rename
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670155867
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
+ private final Map<Integer, Type> replacementsById;
+
+ ReplaceTypeById(Map<Integer, Type> replacementsById) {
+ this.replacementsById = replacementsById;
+ }
+
+ @Override
+ public Type schema(Schema schema, Type structResult) {
+ return structResult;
+ }
+
+ @Override
+ public Type struct(Types.StructType struct, List<Type> fieldResults) {
+ List<Types.NestedField> fields = struct.fields();
+ List<Types.NestedField> newFields = Lists.newArrayListWithExpectedSize(fields.size());
+ boolean hasChanged = false;
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ Type fieldReplacement = fieldResults.get(i);
+ Types.NestedField field = fields.get(i);
+ if (field.type() != fieldReplacement) {
+ hasChanged = true;
+ newFields.add(Types.NestedField.from(field).ofType(fieldReplacement).build());
+ } else {
+ newFields.add(field);
+ }
+ }
+
+ if (hasChanged) {
+ return Types.StructType.of(newFields);
+ }
+
+ return struct;
+ }
+
+ @Override
+ public Type field(Types.NestedField field, Type fieldResult) {
+ return replacementsById.getOrDefault(field.fieldId(), fieldResult);
+ }
+
+ @Override
+ public Type list(Types.ListType list, Type elementResult) {
+ Type elementReplacement = replacementsById.getOrDefault(list.elementId(), elementResult);
+ if (list.elementType() != elementReplacement) {
+ if (list.isElementRequired()) {
+ return Types.ListType.ofRequired(list.elementId(), elementReplacement);
+ } else {
+ return Types.ListType.ofOptional(list.elementId(), elementReplacement);
+ }
+ }
+
+ return list;
+ }
+
+ @Override
+ public Type map(Types.MapType map, Type keyResult, Type valueResult) {
Review Comment:
Added a test.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
Review Comment:
Fixed
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3627852464
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
Review Comment:
If the `readSchema()` method switched to `TypeUtil.project` for `selectFullTypes=false` projection, do we also need to rename this method to `project`?
```
Builder select(Collection<String> newColumns)
```
I know Ryan's original comment mentioned `project` should take a read schema directly. But the `TypeUtil.project` speaks otherwise.
Then there is a question why do we have two project methods? Should we differentiate them as?
```
// auto add some default fields
1. Builder project(Collection<String> newColumns)
// use the supplied schema as it is without any auto add
2. Builder project(Schema newFileProjection)
```
if we are not sure we need option 2 yet, we can leave it out in the initial version.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3664408203
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
Review Comment:
nit: unnecessary cast
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3470620388
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,571 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int WRITER_FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.writerFormatVersion()).isEqualTo(file.writerFormatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .writerFormatVersion(WRITER_FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
+ assertThat(actual.partition().size()).isEqualTo(0);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactly("keep.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .writerFormatVersion(WRITER_FORMAT_VERSION_V4)
+ .location("delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(100L)
+ .fileSizeInBytes(1024L)
+ .partition(partition(2))
+ .specId(0)
+ .equalityIds(ImmutableList.of(1))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles()).isEmpty();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info =
+ ManifestInfoStruct.builder()
+ .addedFilesCount(1)
+ .existingFilesCount(0)
+ .deletedFilesCount(0)
+ .replacedFilesCount(0)
+ .addedRowsCount(1L)
+ .existingRowsCount(0L)
+ .deletedRowsCount(0L)
+ .replacedRowsCount(0L)
+ .minSequenceNumber(1L)
+ .build();
+ TrackedFile manifestRef =
+ TrackedFileBuilder.dataManifest(SNAPSHOT_ID)
+ .writerFormatVersion(WRITER_FORMAT_VERSION_V4)
+ .location("leaf.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(1L)
+ .fileSizeInBytes(100L)
+ .partition(partition(2))
+ .specId(0)
+ .manifestInfo(info)
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder("data-1.parquet", "leaf.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactly("keep.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.partitionType(TABLE_SCHEMA, specsById.values());
+
+ TrackedFile keepById =
+ dataFileBuilder("spec0-id1.parquet", unionPartition(unionType, 1, null)).specId(0).build();
+ TrackedFile prunedById =
+ dataFileBuilder("spec0-id2.parquet", unionPartition(unionType, 2, null)).specId(0).build();
+ TrackedFile keptOtherSpec =
+ dataFileBuilder("spec1-data.parquet", unionPartition(unionType, null, "x"))
+ .specId(1)
+ .build();
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, TABLE_SCHEMA, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder("spec0-id1.parquet", "spec1-data.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly("s3://bucket/added-1.parquet", "s3://bucket/added-2.parquet");
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::allFiles)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Unable to determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testFileWithUnknownSpecThrows() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so pruning cannot resolve a spec for this file
+ TrackedFile file = dataFileBuilder("orphan.parquet", partition(1)).specId(5).build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThatThrownBy(() -> Lists.newArrayList(reader.allFiles()))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not one of the known specs");
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFileBuilder(location, partition).build();
+ }
+
+ private static TrackedFileBuilder dataFileBuilder(String location, PartitionData partition) {
+ return TrackedFileBuilder.data(SNAPSHOT_ID)
+ .writerFormatVersion(WRITER_FORMAT_VERSION_V4)
+ .location(location)
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(100L)
+ .fileSizeInBytes(1024L)
+ .partition(partition)
+ .specId(0);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
Review Comment:
Not using the builder here so that we can set any status here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3606574482
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
Review Comment:
I think that the default should be to return only live files. Getting the deleted and replaced entries is much less common.
I think `onlyLive` should default to `true` and the configuration should be `includeDeletedAndReplaced()`. I would love to make that shorter if there's a better term for entries that are deleted or replaced. "Dead" and "non-live" don't seem good to me. Maybe "inert"?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3606842710
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(partitionType, spec.partitionType()));
+ }
+ }
+
+ return new V4ManifestReader(
+ file, readSchema(), partitionEvaluators, partitionProjections, onlyLive, scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !partitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType fullType = TrackedFile.schema(partitionType, Types.StructType.of());
+
+ // replace tracking with the subset of fields read on the scan path
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(
+ Types.NestedField.required(
+ field.fieldId(), field.name(), SCAN_TRACKING, field.doc()));
+ } else {
+ fields.add(field);
+ }
+ }
+
+ Schema fullSchema = new Schema(fields);
+ if (fileProjection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // status drives live-file filtering and content type distinguishes entry kinds
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (hasPartitionFilter()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ }
+
+ return TypeUtil.select(fullSchema, projectedIds);
Review Comment:
I wrote a lot above about how to configure the builder. I think we should solve that and then come back to how we want to build the projection here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648561718
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnknownManifestFormatThrows(FileFormat format) throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = V4ManifestReader.builder(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithUnknownSpec(FileFormat format) throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithNullSpecId(FileFormat format) throws IOException {
Review Comment:
Isn't this tested elsewhere? I seem to remember it.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648856036
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
Review Comment:
Reworked to test correctness rather than incidental behavior. The manifest now also writes a DELETED and a REPLACED entry, and the test asserts that exactly the one live entry survives. For the requested field I assert location is correct and that unrequested fields (fileFormat, specId, sortOrderId) are null. I dropped the `recordCount == -1` assertion. Also agree that the inheritance and stats filtering belong to the future PRs that implement them.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647200066
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
Review Comment:
Done. i converted it to native JUnit5 equivalent.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648222622
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema requestedProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base = TrackedFile.schema(unionPartitionType, Types.StructType.of());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a filter; files that cannot match the expression are skipped. */
+ Builder filter(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && requestedProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ requestedProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.requestedProjection = newProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ Evaluator evaluator = new Evaluator(spec.partitionType(), partFilter, caseSensitive);
+ StructProjection projection =
+ StructProjection.create(unionPartitionType, spec.partitionType());
+ partitionFilters.put(spec.specId(), Pair.of(evaluator, projection));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionFilters.isEmpty();
+ return new V4ManifestReader(
+ file, readSchema(hasPartitionFilter), partitionFilters, includeAll, scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ if (scanPlanning) {
+ // scan planning does not read the change-tracking fields omitted by SCAN_TYPE
+ return TypeUtil.replaceFieldTypes(
+ fullSchema, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.SCAN_TYPE));
+ }
+
+ if (columns != null) {
+ Schema selected =
+ caseSensitive ? fullSchema.select(columns) : fullSchema.caseInsensitiveSelect(columns);
+ return addRequiredColumns(selected, hasPartitionFilter);
+ }
+
+ if (requestedProjection != null) {
+ return addRequiredColumns(requestedProjection, hasPartitionFilter);
+ }
+
+ return fullSchema;
+ }
+
+ private Schema addRequiredColumns(Schema projection, boolean hasPartitionFilter) {
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for liveness filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (rowFilter != Expressions.alwaysTrue()) {
Review Comment:
This is a little inconsistent. Status is always added for liveness checks, even if `includeAll` is true. But `record_count` is only added when there is a row filter.
I think this is perfectly fine for now, but we should avoid tests that validate this behavior. We could later drop status when returning all entries without affecting correctness, so the validation tests should check that the correct live entries are returned, but not that status is always projected.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648413874
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
Review Comment:
Should be identical to the `project` and `select` tests, except for how the read schema is configured.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648779721
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
Review Comment:
Much cleaner. Thanks!
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648947183
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
Review Comment:
added. `testRestrictedReadReturnsOnlyRequestedFields` asserts fileFormat, specId, and sortOrderId are all null when only location is requested.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648967521
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
Review Comment:
Done
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3634317380
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
Review Comment:
I think we should handle the schema differently here. Here's what I recommend:
1. The full manifest schema is known ahead of time for a table, based on the table's schema, partition specs, and metrics config. We should generate the full manifest schema here so we only need to project fields from it later on.
2. The project and select methods should produce `fileProjection` (or maybe just `projection`?) that will be used by `readSchema` rather than tracking the columns separately. We can produce the selected schema right away and fail any issues in the `select` method
3. `readSchema` should determine what to prune from the full schema.
* If the projection was set by `project` or `select`, then get the projected IDs (without structs), union that with required fields (like `record_count`) and prune the schema
* If the projection was not set but `scanPlanning` is true then we can prune columns that aren't needed. To do this, I would get the set of IDs from the row filter, union it with the requested stats IDs (which I think still need to be added), and pass those to `StatsUtil.statsReadSchema`. Then replace the schema's fields with `TrackingStruct.SCAN_TYPE` and stats schema.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642018992
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
Review Comment:
Should `TrackedFile.schema` return a `Schema` instead? It seems odd to copy it like this.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642132364
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add((StructLike) file);
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ private V4ManifestReader.Builder newReader(
+ InputFile manifest, Map<Integer, PartitionSpec> specsById) {
+ return V4ManifestReader.builder(manifest, specsById);
+ }
+
+ private List<TrackedFile> read(InputFile manifest, Map<Integer, PartitionSpec> specsById)
Review Comment:
This needs to pass the file schema so that the content stats schema can be built.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642136256
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
Review Comment:
This is a good example. It would be nice if the other factory methods followed this convention.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642108979
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
Review Comment:
Wait, do these constructor args not follow the same order as fields?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642075838
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
+ return new V4ManifestReader(
+ file,
+ readSchema(hasPartitionFilter),
+ partitionEvaluators,
+ partitionProjections,
+ includeAll,
+ scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ Schema projection = fileProjection;
+ if (columns != null) {
+ projection =
+ caseSensitive ? fullSchema.select(columns) : fullSchema.caseInsensitiveSelect(columns);
+ }
+
+ if (projection == null) {
+ if (scanPlanning) {
+ // scan planning does not read the change-tracking fields omitted by SCAN_TYPE
+ return TypeUtil.replaceFieldTypes(
+ fullSchema,
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.SCAN_TYPE));
+ }
+
+ return fullSchema;
Review Comment:
The current structure makes this method harder to follow. I understand needing to reuse the same projection logic for `select` and `project` calls, but I think this should avoid depending on the state of `projection`. That's why I commented that the check wasn't needed above; I didn't realize that this is trying to detect that neither `select` nor `project` was called so it can exit early using `fullSchema`.
It would be better to refactor the projection code below into a method that can be used in both `select` and `project` cases.
```java
if (scanPlanning) {
return TypeUtil.replaceFieldTypes(...);
}
if (columns != null) {
return addRequiredColumns(
caseSensitive ? fullSchema.select(columns) : fullSchema.selectCaseSensitive(columns);
}
if (projection != null {
return addRequiredColumns(projection);
}
return fullSchema;
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3664395698
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
Review Comment:
I believe for new tests we usually told folks to omit the `test` prefix because it's not really adding any value and is a legacy thing from JUnit3. Also test methods can be easily identified, since they either have a `@Test` or another annotation
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501032190
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
Review Comment:
This is intentional. Null projection means read all columns, and it's a supported case. This is the current semantics of the existing manifest reader as well.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501805084
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field with {@link MetadataColumns#ROW_POSITION} appended so the reader
+ * populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
Review Comment:
I'd lean toward keeping the loop. It derives the read schema from the canonical `schemaWithContentStats(...)`, so field IDs and ordering stay in one place. A separately hand-built read schema would have to be kept in lockstep ), which is duplication we should try to avoid.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3581844938
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // a minimal status-only tracking is force-added when the caller omits tracking
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
Review Comment:
Yes, the test preceding this? (`testPartitionFilterForceProjectsFilterFields`)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3583527549
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final boolean reuseContainers;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ boolean reuseContainers,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.reuseContainers = reuseContainers;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /**
+ * Returns tracked files that match this reader's configured filters. Files are copied unless the
+ * reader was built with {@link Builder#reuseContainers()}.
+ */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ if (reuseContainers) {
+ return entries.iterator();
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
Review Comment:
This does not match the expectation set by the method name. If this is filtering by partition, then it should do just that. The caller can handle this: `isManifest(file) || matchesPartition(file)`. That's more clear than returning `true` based on what you think the caller probably wants. Assuming how this is going to be called and when it will be used creates undocumented assumptions in the code that can be nasty bugs later on.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#issuecomment-5132145599
Thanks @anoopj!, great to see this go in.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540364599
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
Review Comment:
Add `@return`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670135754
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
Review Comment:
Changed to package private
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3581830184
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
Review Comment:
Just did a rebase and fixed this.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3575918725
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
Review Comment:
Moved to builder
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3589277481
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -243,6 +243,17 @@ public static StructType partitionType(Table table) {
"table partition", specs, allActiveFieldIds(table.schema(), specs));
}
+ /**
+ * Builds a unified partition type containing all partition fields from the given specs, including
+ * fields whose source columns are no longer present in the table schema.
+ *
+ * @param specs the partition specs to unify
+ * @return the constructed unified partition type
+ */
+ static StructType partitionType(Collection<PartitionSpec> specs) {
Review Comment:
Renamed to `unionPartitionTypes`
##########
core/src/main/java/org/apache/iceberg/TrackedFile.java:
##########
@@ -95,26 +96,40 @@ interface TrackedFile {
Types.ListType.ofRequired(136, Types.IntegerType.get()),
"Field ids used to determine row equality in equality delete files");
+ /**
+ * Returns the schema for the given partition and content stats types.
+ *
+ * <p>The partition and content stats fields are omitted when their types have no fields.
+ */
static Types.StructType schemaWithContentStats(
Review Comment:
That sounds good. Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3589324681
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final boolean reuseContainers;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ boolean reuseContainers,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.reuseContainers = reuseContainers;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /**
+ * Returns tracked files that match this reader's configured filters. Files are copied unless the
+ * reader was built with {@link Builder#reuseContainers()}.
+ */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ if (reuseContainers) {
Review Comment:
> If I understand correctly, the intent is to match the behavior of entries vs iterator for the v3 ManfiestReader
That is exactly it. I would imagine not doing copies would help scan planning performance a lot? That is why I added it. I have removed it for now. We can add it back based on profiling results later.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final boolean reuseContainers;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ boolean reuseContainers,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.reuseContainers = reuseContainers;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /**
+ * Returns tracked files that match this reader's configured filters. Files are copied unless the
+ * reader was built with {@link Builder#reuseContainers()}.
+ */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ if (reuseContainers) {
+ return entries.iterator();
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
Review Comment:
Fair enough. Changed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501719389
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
+ assertThat(actual.partition().size()).isEqualTo(0);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactly("keep.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(100L)
+ .fileSizeInBytes(1024L)
+ .partition(partition(2))
+ .specId(0)
+ .equalityIds(ImmutableList.of(1))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles()).isEmpty();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info =
+ ManifestInfoStruct.builder()
+ .addedFilesCount(1)
+ .existingFilesCount(0)
+ .deletedFilesCount(0)
+ .replacedFilesCount(0)
+ .addedRowsCount(1L)
+ .existingRowsCount(0L)
+ .deletedRowsCount(0L)
+ .replacedRowsCount(0L)
+ .minSequenceNumber(1L)
+ .build();
+ TrackedFile manifestRef =
+ TrackedFileBuilder.dataManifest(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("leaf.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(1L)
+ .fileSizeInBytes(100L)
+ .partition(partition(2))
+ .specId(0)
+ .manifestInfo(info)
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder("data-1.parquet", "leaf.parquet");
Review Comment:
Sounds good.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3555776209
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
Review Comment:
Added.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633659012
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
+ Schema projection = projection(fullSchema);
+ if (projection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for live filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (hasPartitionFilter()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ projectedIds.addAll(TypeUtil.getProjectedIds(unionPartitionType));
+ }
+
+ // list and map fields cannot be projected by ID; their element IDs carry the selection
+ projectedIds.removeIf(
Review Comment:
I don't understand why this is necessary. There are no map types in the schema, so we don't have to worry about that. For lists, wouldn't either the list's field ID or the list element's field ID select the full list?
It seems like this is working around some limitation, like how `TypeUtil.project` doesn't select full types. I'd like to know what wasn't working so we can the right solution.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648240900
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
Review Comment:
Yeah, it's a little misleading right now, but stats filtering should call this too.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646379392
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
Review Comment:
I collapsed the two maps into a single `Map<Integer, Pair<Evaluator, StructProjection>>` keyed by spec ID and removed the check.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647046864
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
Review Comment:
I see. I can agree with the reasoning of "because they are required by the reader internally".
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648038847
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,926 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
Review Comment:
I prefer to keep it this because it makes the tests more readable with local context. If we see more repeated usages, we can refactor this.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648248043
##########
core/src/test/java/org/apache/iceberg/TestTrackedFile.java:
##########
@@ -39,8 +39,8 @@ public class TestTrackedFile {
PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build().partitionType();
@Test
- public void schemaWithContentStatsFieldOrder() {
- Types.StructType type = TrackedFile.schemaWithContentStats(PARTITION_TYPE, CONTENT_STATS_TYPE);
+ public void schemaFieldOrder() {
+ Types.StructType type = TrackedFile.schema(PARTITION_TYPE, CONTENT_STATS_TYPE).asStruct();
Review Comment:
Should `CONTENT_STATS_TYPE` be a `StructType` instead of a `Schema`? That would cut down on changes.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648255064
##########
core/src/test/java/org/apache/iceberg/TestTrackedFileStruct.java:
##########
@@ -359,12 +355,12 @@ void serializationRoundTrip(RoundTripSerializer<TrackedFileStruct> serializer) t
FileContent.DATA,
FORMAT_VERSION_V4,
"s3://bucket/data/file.parquet",
- FileFormat.PARQUET,
- null, // PartitionData has its own serialization tests
+ FileFormat.PARQUET, // PartitionData has its own serialization tests
Review Comment:
This comment is misplaced. It should be attached to the `null` passed as `PartitionData`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648454958
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
Review Comment:
If `fileWithFullTracking` doesn't accept any arguments, it should be replaced with a constant.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648787957
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
Review Comment:
Renamed SPEC to ID_PARTITIONING.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646995231
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
Review Comment:
No. I switched to the builder for now. I can remove the builder and make the constructor public as a followup PR if you would like.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642035267
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
Review Comment:
Sounds reasonable.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633574484
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
Review Comment:
A `REPLACED` entry isn't really a tombstone since it's purpose is to signal that, unlike `DELETED`, a newer version of the entry is still live.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648978719
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
Review Comment:
Done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648943628
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
Review Comment:
Right the cast is gone.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "dramaticlly (via GitHub)" <gi...@apache.org>.
dramaticlly commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3546166511
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
Review Comment:
I hope https://github.com/apache/iceberg/pull/17118/ can help here where filter can now provide onKeep/onSkip callback and counters can be configured directly in the callback with more flexibility for the heterogeneous entry of TrackedFile
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540549377
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
Review Comment:
What about manifests?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668790058
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
Review Comment:
We should invlude the inverse of this to show there is a difference between teh modes. We're validating that case-insensitive works, but not that it's different from case-sensitive.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670070430
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(0)
+ .add(1, 1000, "id", Transforms.identity())
+ .build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById =
+ ImmutableMap.of(spec0.specId(), spec0, spec1.specId(), spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById =
+ dataFile("spec0-id1.parquet", spec0.specId(), unionPartition(unionType, 1, null));
+ TrackedFile prunedById =
+ dataFile("spec0-id2.parquet", spec0.specId(), unionPartition(unionType, 2, null));
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", spec1.specId(), unionPartition(unionType, null, "x"));
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithUnknownSpec(FileFormat format) throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", 5, partition(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithNullSpecId(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ assertThat(read.get(0))
+ .as("iterator() should copy each entry rather than yield one reused container")
+ .isNotSameAs(read.get(1));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnknownManifestFormatThrows(FileFormat format) throws IOException {
Review Comment:
yes, we don't need it because it is a negative test
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670080040
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
Review Comment:
Done
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
Review Comment:
Done
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670072556
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
Review Comment:
Applied
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670080824
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
+ Types.StructType replacement = Types.StructType.of(required(10, "x", IntegerType.get()));
+ Schema schema =
+ new Schema(
+ required(1, "id", IntegerType.get()),
+ required(2, "s", Types.StructType.of(required(3, "a", Types.LongType.get()))));
+
+ Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, (Type) replacement));
Review Comment:
Done
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
+ Types.StructType replacement = Types.StructType.of(required(10, "x", IntegerType.get()));
+ Schema schema =
+ new Schema(
+ required(1, "id", IntegerType.get()),
+ required(2, "s", Types.StructType.of(required(3, "a", Types.LongType.get()))));
+
+ Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, (Type) replacement));
+
+ assertThat(result.findField(1).type()).isEqualTo(IntegerType.get());
+ assertThat(result.findField(2).type()).isEqualTo(replacement);
+ }
+
+ @Test
+ public void testReplaceFieldTypesListElement() {
+ Schema schema =
+ new Schema(required(1, "list", Types.ListType.ofRequired(2, Types.StructType.of())));
+
+ Schema result =
+ TypeUtil.replaceFieldTypes(
+ schema,
+ ImmutableMap.of(2, (Type) Types.StructType.of(required(3, "x", IntegerType.get()))));
+
+ Types.ListType list = (Types.ListType) result.findField(1).type();
+ assertThat(list.elementType().asStructType().field(3).name()).isEqualTo("x");
+ assertThat(list.isElementRequired()).isTrue();
+ }
+
+ @Test
+ public void testReplaceFieldTypesNoMatchReturnsSameSchema() {
+ Schema schema = new Schema(required(1, "id", IntegerType.get()));
+ Schema result =
+ TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(99, (Type) Types.LongType.get()));
Review Comment:
Done
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668429349
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
Review Comment:
```suggestion
private static Stream<Arguments> selectiveReadModes() {
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668753425
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
Review Comment:
Same thing with `PARTITIONED_SPECS` as with `PARTITION_TYPE`, the names are too generic and don't represent the value they hold, which makes it harder to read the tests.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3482009991
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
Review Comment:
I think I know: `manifestLocation` is the same for all rows within the file, no need to have it per each row.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501342036
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
Review Comment:
Yes, your second comment is correct. A v4 manifest can mix data files, delete files, and manifest references in one file. So the counter depends on each entry's contentType and can only be selected inside the predicate. The current code is quite simple to undersand.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501330490
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
If a table goes from unpartitioned, to partitioned, new files also can be written in the unpartitioned space - this is a supported use case. So an unpartitioned file should not throw. Instead, it should **not** get filtered out by partition filtering, so that filters should apply to rows instead. e.g. table is partitioned by a `color` string column, and an unparitioned file could mix rows from different colors.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501813483
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
Review Comment:
Agreed on partition: once #17000 makes the partition field optional, I can update the test to expect null. For now, leaving the current assertions.
On `spec_id`: in this test the file is written with specId(0) and UNPARTITIONED_SPECS includes the unpartitioned spec (id 0), so it reads back as 0, not null. spec_id is null only for a file that has no spec at all.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3518990118
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ boolean fullTracking = true;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // read the full tracking struct only when the caller requests it; otherwise force-add a
Review Comment:
I just checked `ManifestReader` to see what it adds to the projection:
In `ManifestReader.open(projection)` it adds `record_count`, `first_row_id` and `_pos` to the projection unconditionally. Also indirectly through `ManifestEntry.wrapFileSchema()` it add further `status`, `snapshot_id`, `sequence_number` and `file_sequence_number`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3506521442
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,551 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // a minimal status-only tracking is force-added when the caller omits tracking
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
Review Comment:
Is there a test where we do a projection that doesn't include partition, and partition added to the projection because of the partition filtering?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
Review Comment:
Thanks for the explanation! Projecting stats makes total sense.
I think most of my comment on this area are for a single reason: for me this readSchema() function seems a bit more complicated than what it is for. What I have in mind is like this:
```
if (fileProjection == null) {
return TrackedFileStruct.READ_SCHEMA;
// this could be prepared with the desired Tracking schema, omitting stats, including partition unconditionally. Preferable a static field in TrackedFileStruct.
}
// construct the projected schema including the mandatory fields similarly as now
```
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
My point was that specId = null is a valid state, but we throw an exception here because of that because both the evaluator and the projection will be null.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3487472727
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
this name `V4ManifestReader` would be come stale when V5 rolls in. maybe `TrackedFileManifestReader` or just `TrackedFileReader`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3583512496
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,298 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final boolean reuseContainers;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ boolean reuseContainers,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.reuseContainers = reuseContainers;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /**
+ * Returns tracked files that match this reader's configured filters. Files are copied unless the
+ * reader was built with {@link Builder#reuseContainers()}.
+ */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ if (reuseContainers) {
Review Comment:
Ah, this is why it was confusing above. This is not what `reuseContainers` typically means. This is asking for a copy.
If I understand correctly, the intent is to match the behavior of `entries` vs `iterator` for the v3 `ManfiestReader`. Calling `entries` returns an iterator that doesn't copy because the caller is expected to do it. But calling `iterator` does copy because that's safer (side note, we also expect filters to be pushed down for `iterator`).
I think it's fine for now to allow turning the copy behavior off, but I think that it would be better to always copy and add the behavior to avoid it when we need that behavior. Maybe we won't need it and we don't need to make this class more complicated.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3583414104
##########
core/src/main/java/org/apache/iceberg/TrackedFile.java:
##########
@@ -95,26 +96,40 @@ interface TrackedFile {
Types.ListType.ofRequired(136, Types.IntegerType.get()),
"Field ids used to determine row equality in equality delete files");
+ /**
+ * Returns the schema for the given partition and content stats types.
+ *
+ * <p>The partition and content stats fields are omitted when their types have no fields.
+ */
static Types.StructType schemaWithContentStats(
Review Comment:
While we are changing this, I think the method should be renamed. It is not just adding content stats. How about just `schema`? I think `TrackedFile.schema(partitionType, statsType)` is clear.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668379504
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
Review Comment:
Shouldn't we also validate that the selection doesn't exclude required projected fields?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670178746
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema requestedProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base = TrackedFile.schema(unionPartitionType, Types.StructType.of());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a filter; files that cannot match the expression are skipped. */
+ Builder filter(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && requestedProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(String... newColumns) {
+ return select(Arrays.asList(newColumns));
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ requestedProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newProjection) {
Review Comment:
This is by design (there was a long thread with Ryan and Gabor) to be compatible with v3 reader. Added a test.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670140590
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
Review Comment:
Both this test and the select sibling now assert the force-projected fields actually come back on the returned record
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3677285327
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
+ */
+ static StructType partitionType(Schema schema, Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allActiveFieldIds(schema, specs));
Review Comment:
Improved this in Iceberg with https://github.com/apache/iceberg/pull/17262 and Iceberg Rust with https://github.com/apache/iceberg-rust/pull/2845 and https://github.com/apache/iceberg-rust/pull/2843
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647182454
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
Review Comment:
Thanks. Done. The test now compares the whole struct with `Comparators.forType(readType)` instead of field-by-field. There was one wrinkle though: the reader fills `row_position` (backing manifestPos) and manifestLocation, which the written file doesn't have, so I mirror those on the expected file before comparing.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633679336
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
Review Comment:
What about using `Iterable` instead? That is a weaker interface and we don't need the size of the columns.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
Review Comment:
What about using `Iterable` instead? That is a weaker interface and we don't need the size of the columns collection.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633616074
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
+ Schema projection = projection(fullSchema);
+ if (projection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for live filtering, row_position for
Review Comment:
liveness filtering?
Do we also need to ensure `record_count` is present?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633705300
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
Review Comment:
The `scanPlanning` case never discards columns in the `TrackedFile` struct. Are all of the columns needed?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3619784924
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
Review Comment:
Good catch. Fixed by switching to TypeUtil.project as you suggested. i had to make a couple of adjustments: 1) the partition filter join now adds the union partition type's nested field IDs 2) repeated fields (list/map) parent IDs are stripped from the set since project rejects container IDs (causing problems on fields like `split_offsets`)
On your points 2 and 3: force-adding the reader's own fields (status, content_type, and spec_id/partition under a filter) is intentional. Since v4 has no entry wrapper, so status lives in-row and live filtering needs it.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -370,34 +446,62 @@ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
public void testPartitionFilterKeepsManifestReferences() throws IOException {
TrackedFile keep = dataFile("data-1.parquet", partition(1));
TrackedFile prune = dataFile("data-2.parquet", partition(2));
- ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
- TrackedFile manifestRef =
- new TrackedFileStruct(
- addedTracking(),
- FileContent.DATA_MANIFEST,
- FORMAT_VERSION_V4,
- "leaf.parquet",
- FileFormat.PARQUET,
- partition(2),
- RECORD_COUNT,
- FILE_SIZE_IN_BYTES,
- 0,
- null,
- null,
- null,
- info,
- null,
- null,
- null);
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
- InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
try (V4ManifestReader reader =
newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
assertThat(reader)
.extracting(TrackedFile::location)
- .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
Review Comment:
Added
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -235,6 +248,69 @@ public void testProjectionRestrictsFields() throws IOException {
}
}
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location", "record_count"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // file_format and spec_id are null because they were not selected
Review Comment:
Good idea. Added `testSelectWithPartitionFilterProjectsFilterFields`
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -243,6 +243,17 @@ public static StructType partitionType(Table table) {
"table partition", specs, allActiveFieldIds(table.schema(), specs));
}
+ /**
+ * Builds a unified partition type containing all partition fields from the given specs, including
+ * fields whose source columns are no longer present in the table schema.
+ *
+ * @param specs the partition specs to unify
+ * @return the constructed unified partition type
+ */
+ static StructType unionPartitionTypes(Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
Review Comment:
Changed to "union partition" so the error message is distinguishable from partitionType(Table).
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,738 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
Review Comment:
Done
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646428680
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
+ return new V4ManifestReader(
+ file,
+ readSchema(hasPartitionFilter),
+ partitionEvaluators,
+ partitionProjections,
+ includeAll,
+ scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ Schema projection = fileProjection;
Review Comment:
Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648237174
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
Review Comment:
If scan metrics were the problem, I'd say skip. But we should not have code that cannot handle specific content types so an exception seems right to me here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648436757
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
Review Comment:
Tests that use this are not readable. A better name would help, like `ID_PARTITIONING`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648493751
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
Review Comment:
The test data used in this suite seems really inconsistent. Some places use constants, some places use factory methods, and some places embed constructor calls like this.
In earlier test suites, we had a set of `DataFile` constants, `FILE_A`, `FILE_B`, `EQ_DELETES_A`, etc. I think that strategy would help make this a lot cleaner. That would also allow you to cut down on constants. I don't see a lot of places where this suite is validating the constants used to produce the test records, so why make them constants?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648474446
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
Review Comment:
This is nearly identical to other cases. I think it just adds a metrics assertion. Can you dedup?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3575819071
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
Review Comment:
The code is correct because we don't handle pruning of manifests currently. I extracted a `incrementSkipCount()` method that is exhaustive such that it's clear.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
Review Comment:
I refactored this such that schemaWithContentStats() now omits partition and content stats when their types are empty. That removes the special casing here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640991120
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
Review Comment:
I kept project accepting null. It matches `ManifestReader.project()`, which also has no null check and treats a null projection as "read the full schema" (that's the path BaseFilesTable uses)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641791798
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,319 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeNonLive;
Review Comment:
`includeAll` looks cleaner to me, since it names the effect of no status filtering.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648952672
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
Review Comment:
Done. both specs use add(...) with explicit field IDs now
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3521129139
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
I think the spec needs to be a bit clear on this. I have a slight preference to make it optional for data/delete files as well, for truly unpartitioned cases. I will leave this thread open till we resolve this.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
Review Comment:
Yes, row lineage isn't wired up in this reader yet.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
Review Comment:
Removed
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
Review Comment:
That makes sense. Added content_type as always projected.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
Review Comment:
Yes, please see my comment above.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ boolean fullTracking = true;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // read the full tracking struct only when the caller requests it; otherwise force-add a
Review Comment:
I initially left them out so that inheritance can be a separate PR. I think it makes sense to add them here.
But I think we should probably not always project out the whole tracking. `dv_snapshot_id`, `replaced/deleted_positions` are required for CDF readers. Especially the latter two fields are fairly large bitmaps. We should probably not project them on the scan path.
I have updated the PR such that we always project out the fields we need for scan but not for CDF.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
Review Comment:
Changed. I was trying to be consistent in error messages with the current reader.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ boolean fullTracking = true;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // read the full tracking struct only when the caller requests it; otherwise force-add a
+ // minimal tracking carrying just the status used to filter live files
+ fullTracking = projectedIds.contains(TrackedFile.TRACKING.fieldId());
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // project spec_id for partition filtering
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ fullTracking ? TrackingStruct.BASE_TYPE : STATUS_TRACKING,
+ TrackedFile.TRACKING.doc()));
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
Review Comment:
I do agree: we will be projecting only the field IDs we need. This is just a placeholder for now, as the interfaces for content stats are being revamped.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ boolean fullTracking = true;
+ if (fileProjection != null) {
+ projectedIds =
+ fileProjection.asStruct().fields().stream()
+ .map(Types.NestedField::fieldId)
+ .collect(Collectors.toCollection(Sets::newHashSet));
+
+ // read the full tracking struct only when the caller requests it; otherwise force-add a
+ // minimal tracking carrying just the status used to filter live files
+ fullTracking = projectedIds.contains(TrackedFile.TRACKING.fieldId());
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // project spec_id for partition filtering
+ if (!partitionEvaluators.isEmpty()) {
Review Comment:
Good catch, fixed such that we will be force-projecting partition (alongside spec_id) when a filter is active. Also added testPartitionFilterForceProjectsFilterFields() as a test
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,275 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // minimal tracking projection used when the caller does not request tracking
+ private static final Types.StructType STATUS_TRACKING = Types.StructType.of(Tracking.STATUS);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
Review Comment:
Good point. Changed to `file.location()`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540510186
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
Review Comment:
Don't forget to remove obvious or unnecessary parts of comments, like "empty when no filtering is required".
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3652810608
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
Review Comment:
I've standardized the test data. Added shared record constants in the FILE_A/FILE_B/EQ_DELETES_A/EQ_DELETES_B style, which the partition-filter tests now reuse instead of building near-identical keep/prune files each time. Also dropped the scalar constants that weren't being validated
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3598548550
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,641 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schema(Types.StructType.of(), Types.StructType.of()).fields();
+ private static final int SORT_ORDER_ID_ORDINAL = ordinalOf(TrackedFile.SORT_ORDER_ID.fieldId());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+ ((StructLike) file).set(SORT_ORDER_ID_ORDINAL, SORT_ORDER_ID);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testTrackingProjectionOmitsChangeTrackingFields() throws IOException {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ TrackedFile file =
+ new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ TrackedFile manifestRef =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA_MANIFEST,
+ FORMAT_VERSION_V4,
+ "leaf.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testFileWithUnknownSpecThrows() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so pruning cannot resolve a spec for this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThatThrownBy(() -> Lists.newArrayList(reader))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not one of the known specs");
+ }
+ }
Review Comment:
Three tests would raise coverage on paths:
1. **Precondition throws.** `Builder.filterRows(null)` and `Builder.scanMetrics(null)` both `checkArgument`-throw, but neither is asserted. Two `assertThatThrownBy` cases would guard those.
2. **Row filter on an unpartitioned table.** `hasPartitionFilter()` returns false in two ways — `rowFilter == alwaysTrue()` *and* `partitionType.fields().isEmpty()`. The second branch isn't exercised: no test calls `.filterRows(...)` against `UNPARTITIONED_SPECS`. Expected behavior is every entry kept, no `skippedDataFiles`/`skippedDeleteFiles` increments. Easy to add adjacent to `testPartitionFilterPrunesNonMatchingFiles`.
3. **`DELETE_MANIFEST` on the manifest-passthrough path.** `testPartitionFilterKeepsManifestReferences` covers `DATA_MANIFEST` only. A one-line variant with `FileContent.DELETE_MANIFEST` closes the symmetric branch in `isManifest`.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,641 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schema(Types.StructType.of(), Types.StructType.of()).fields();
+ private static final int SORT_ORDER_ID_ORDINAL = ordinalOf(TrackedFile.SORT_ORDER_ID.fieldId());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+ ((StructLike) file).set(SORT_ORDER_ID_ORDINAL, SORT_ORDER_ID);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testTrackingProjectionOmitsChangeTrackingFields() throws IOException {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ TrackedFile file =
+ new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ TrackedFile manifestRef =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA_MANIFEST,
+ FORMAT_VERSION_V4,
+ "leaf.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testFileWithUnknownSpecThrows() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so pruning cannot resolve a spec for this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThatThrownBy(() -> Lists.newArrayList(reader))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not one of the known specs");
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, int specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add(toWriteRow(file, writeSchema));
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ /**
+ * Adapts a fully-populated tracked file to a write schema that may omit fields (partition and
+ * content_stats are omitted when empty).
+ */
+ private static StructLike toWriteRow(TrackedFile file, Schema writeSchema) {
Review Comment:
The Javadoc reflects an earlier design where empty partition/content_stats were **omitted** from the schema; the current design keeps them as `UnknownType` (always present in the logical schema, dropped by Parquet, written as null by Avro), so no remapping is needed.
Suggest folding this into a single simplification that also drops `SORT_ORDER_ID_ORDINAL` (L75), `ordinalOf` (L632), and `SCHEMA_FIELDS` (L73) — all three exist only to support this helper and one positional `set` in `testProjectionRestrictsFields`.
**Step 1** — replace the appender loop with a direct cast (`TrackedFileStruct` implements `StructLike`, and every test path here constructs one):
```java
for (TrackedFile file : files) {
appender.add((StructLike) file);
}
```
**Step 2** — inline `sortOrderId` into the constructor in `testProjectionRestrictsFields` so the positional `set(SORT_ORDER_ID_ORDINAL, ...)` at L218 goes away, mirroring `testTrackingProjectionOmitsChangeTrackingFields`:
```java
TrackedFile file =
new TrackedFileStruct(
addedTracking(),
FileContent.DATA,
FORMAT_VERSION_V4,
"s3://bucket/file.parquet",
FileFormat.PARQUET,
EMPTY_PARTITION_DATA,
RECORD_COUNT,
FILE_SIZE_IN_BYTES,
0,
null, // contentStats
SORT_ORDER_ID, // ← inline instead of positional set later
null, null, null, null, null);
```
**Step 3** — delete `toWriteRow`, `ordinalOf`, `SORT_ORDER_ID_ORDINAL`, and `SCHEMA_FIELDS`. Net removal ~30 lines.
If schema divergence gets reintroduced later, `StructProjection.create(sourceType, writeSchema.asStruct()).wrap((StructLike) file)` is the right tool at that point — but adding it now hides dead machinery.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3634879571
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
Review Comment:
`Schema.select()` doesn't accept `Iterable`: it needs to be a `Collection`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642055077
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
+ return new V4ManifestReader(
+ file,
+ readSchema(hasPartitionFilter),
+ partitionEvaluators,
+ partitionProjections,
+ includeAll,
+ scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ Schema projection = fileProjection;
Review Comment:
I'd prefer `requestedProjection` or something rather than `fileProjection`. Using "file" doesn't actually distinguish it from "projection" that is used (only in this method) as the requested fields.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
+ return new V4ManifestReader(
+ file,
+ readSchema(hasPartitionFilter),
+ partitionEvaluators,
+ partitionProjections,
+ includeAll,
+ scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ Schema projection = fileProjection;
+ if (columns != null) {
+ projection =
+ caseSensitive ? fullSchema.select(columns) : fullSchema.caseInsensitiveSelect(columns);
+ }
+
+ if (projection == null) {
Review Comment:
No need for this check because the config methods guarantee that `scanPlanning` is true or `columns` are non-null or `fileProjection` is set.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642113233
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
Review Comment:
Data and DV round trip?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642029324
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
Review Comment:
Sounds reasonable. That's an old API.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642026513
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
Review Comment:
This should be just `filter`, not `filterRows`. We don't have a distinction between filtering partitions and rows in this API.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642129856
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
Review Comment:
You'd return `out.toInputFile()`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642126204
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
Review Comment:
Needs `ContentStats` so we don't have to modify this later.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668333210
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
Review Comment:
Why are we using the term 'restricted'? This should be 'selective'. It's a little confusing because we're restricting, we're down-selecting.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670088654
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
Review Comment:
Done
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668474664
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
Review Comment:
It might be better to validate all but the required projections are omitted (seems like that should be possible).
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670125160
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
Review Comment:
The test is structured that way because we didn't incorporate content stats yet. We can change it when we do the followup cc @nastra
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670160680
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
Review Comment:
You are correct. That would have been a better choice. Keeping it here because the code has been reviewed. Will add the tests.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3671385261
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
Review Comment:
since this is a new test class being added I don't think it creates any additional churn and removing the prefix should be simple
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3606804878
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
Review Comment:
I don't think that `project` is the right method for configuration.
In the library, we typically use `project` to pass a specific schema to read. That schema is not modified if it is used because we assume that the caller knows what they are doing and used `project` on purpose.
We also use `select` to select columns by name. This has the same behavior as SQL: `select("a", "b")` projects columns `a` and `b`.
In `ManifestReader`, we had configuration methods for both (it was an early API) but the contract of `project` doesn't allow you to mess with that schema. The behavior was to use the selected columns (and potentially add more stats columns) if `select` was called, even if `project` was also called. If `select` was not called then `project` would be used.
`select` is used a lot more than `project` is used because that's the easy way to get the columns we want out of the file with readable code (`select(file_path, record_count, ...)`). Project is used for cases like metadata tables where we are showing users the data but not actually using it directly from the library.
I think that we should fix the API of the builder. For internal uses, `select` is the right method to implement. We can also add `project`, but if we do it should be mutually exclusive with `select`. If you call `select` then you can't use `project` and vice versa.
Stats are another dimension to the read schema. We want to take the filter that is passed in and project the stats structs required by that filter (the read schema method in `StatsUtil`). We also need a way for callers to request all stats or stats for a specific set of fields. The `copy` methods accept `Set<Integer>` to pass field IDs, but I think we probably want to configure this using field names. (Side note: generating these schemas requires knowing the table schema in this builder.)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3606694734
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
I don't think that the current logic here is correct.
If a file was written to an unpartitioned spec, then the spec ID will be null. If the spec is unpartitioned, then it cannot help in filtering. That means if the ID is null then we should return `true` because the file may match whatever filters are present.
In addition, we could have cases where a spec doesn't help at all. If I have a filter for `category_id = 5` and there is no partition on that source field, then there should be no evaluator. So if the evaluator is `null` then this should also return `true`.
The only time this should have a problem is when the spec ID is non-null and the evaluator is non-null, but the tuple projection is null because we can't produce the partition tuple to pass into the evalutor.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
I don't think that the current logic here is correct.
If a file was written to an unpartitioned spec, then the spec ID will be null. If the spec is unpartitioned, then it cannot help in filtering. That means if the ID is null then we should return `true` because the file may match whatever filters are present.
In addition, we could have cases where a spec doesn't help at all. If I have a filter for `category_id = 5` and there is no partition on that source field, then there should be no evaluator. So if the evaluator is `null` then this should also return `true`.
The only time this should have a problem is when the spec ID is non-null and the evaluator is non-null, but the tuple projection is null because we can't produce the partition tuple to pass into the evaluator.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3677798788
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
Review Comment:
Yes, will take care of this in the content stats PR cc @nastra who is going to work on it.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add((StructLike) file);
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ private V4ManifestReader.Builder newReader(
+ InputFile manifest, Map<Integer, PartitionSpec> specsById) {
+ return V4ManifestReader.builder(manifest, specsById);
+ }
+
+ private List<TrackedFile> read(InputFile manifest, Map<Integer, PartitionSpec> specsById)
Review Comment:
Yes, this is also defered to the content stats PR: cc @nastra
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
Review Comment:
We don't need to change this because this test doesn't write a manifest. It only asserts on builder-validation exceptions that fire before any read.
`writeManifest()` does write+read, so it uses `InMemoryOutputFile` as you suggested.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648867411
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
Review Comment:
Made it consistent: metrics assertions now live in the single comprehensive `testPartitionFilterPrunesFilesAndCountsSkips`. The other filter tests just assert which files survive, without metrics.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648865617
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
Review Comment:
Grouped all the partitioning tests together. The three misc tests that were wedged between them are moved below. Multi-spec filtering is covered by `testMultiSpecPartitionPruning`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648962863
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
Review Comment:
Renamed to testRowFilterKeepsFilesWithoutStats with a comment that we don't prune files. The stats-driven pruning will come with the stats integration.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648297822
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
Review Comment:
"Round trip" usually refers to serialization and is used when the value is unchanged after serialization/deserialization. This test is different because it writes a record and then checks specific things about the record that was read back, like row position and manifest location. I think at a minimum it should have a different name, like `testInheritedTrackingValues`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648407418
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
Review Comment:
This assertion isn't correct. This is checking a specific behavior (because we know how the code works) but not correctness: that files with 0 records are removed.
I think this can only be implemented once we have content stats filtering. If we are doing that in a separate PR, then we should make sure there is a test in that PR for a 0 record file.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648408820
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
Review Comment:
I think this should be identical to the `location` test using `project`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648460415
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
Review Comment:
The use of `read` here does not show the part that this test case is validating, which is a builder that does not have `scanPlanning`, `select`, or `project` called. I think this should show the builder configuration so the test can be understood reading it here.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648449049
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
Review Comment:
This is a good test! The assertion that the filter works correctly is the right strategy, instead of checking that the partition field was projected.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648544220
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
Review Comment:
I think that this test should either use the package-private `add` method in both cases, or use the public API in both cases. Since it is easier to produce exact specs using `add`, I think using it makes sense. But this should not specify the partition field ID here and not for `spec0`.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
Review Comment:
`spec0.specId()`?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3618050125
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -243,6 +243,17 @@ public static StructType partitionType(Table table) {
"table partition", specs, allActiveFieldIds(table.schema(), specs));
}
+ /**
+ * Builds a unified partition type containing all partition fields from the given specs, including
+ * fields whose source columns are no longer present in the table schema.
+ *
+ * @param specs the partition specs to unify
+ * @return the constructed unified partition type
+ */
+ static StructType unionPartitionTypes(Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
Review Comment:
nit on the type name, maybe "union partition"?
It is only used in exception error msg. Here is another caller in addition to L242 above.
```
public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec> specs) {
return buildPartitionProjectionType("grouping key", specs, commonActiveFieldIds(schema, specs));
}
```
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,738 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
Review Comment:
nit: ` ImmutableList.of(...)`
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -370,34 +446,62 @@ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
public void testPartitionFilterKeepsManifestReferences() throws IOException {
TrackedFile keep = dataFile("data-1.parquet", partition(1));
TrackedFile prune = dataFile("data-2.parquet", partition(2));
- ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
- TrackedFile manifestRef =
- new TrackedFileStruct(
- addedTracking(),
- FileContent.DATA_MANIFEST,
- FORMAT_VERSION_V4,
- "leaf.parquet",
- FileFormat.PARQUET,
- partition(2),
- RECORD_COUNT,
- FILE_SIZE_IN_BYTES,
- 0,
- null,
- null,
- null,
- info,
- null,
- null,
- null);
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
- InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
try (V4ManifestReader reader =
newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
assertThat(reader)
.extracting(TrackedFile::location)
- .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
Review Comment:
nit: should we also check the scan metrics like the one below?
```
assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
```
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -235,6 +248,69 @@ public void testProjectionRestrictsFields() throws IOException {
}
}
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location", "record_count"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // file_format and spec_id are null because they were not selected
Review Comment:
nit: can we add a coverage for partitioned table where these two fields are always selected?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
Review Comment:
Concretely, the current `project(Schema)` path modifies the caller's schema in three ways at `251:272:core/src/main/java/org/apache/iceberg/V4ManifestReader.java`:
1. A narrower `tracking` sub-projection is widened to full `Tracking.scanSchema()` — `TypeUtil.getProjectedIds` returns both the parent `TRACKING.fieldId` and any nested ids, and `TypeUtil.select` uses `selectFullTypes=true` (`119:123:api/src/main/java/org/apache/iceberg/types/TypeUtil.java`), so parent-in-set short-circuits back to the whole struct.
2. `TRACKING` and `CONTENT_TYPE` are force-added at L264-265 even if the caller omitted them.
3. `SPEC_ID` and `PARTITION_ID` are force-added when a row filter is active (L267-268).
Worth noting: `TypeUtil.project` (`75:87:api/src/main/java/org/apache/iceberg/types/TypeUtil.java`) uses `selectFullTypes=false`, so it *does* preserve a narrower sub-projection. `readSchema()` can use `TypeUtil.project` to avoid the projection widening.
parent struct widening problem will be especially problematic when content stats are plumbed in, since there could be dozens or hundreds of column stats.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3481845257
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field with {@link MetadataColumns#ROW_POSITION} appended so the reader
+ * populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
Review Comment:
These Tracking schemas are kind of confusing. Let me know if I get it wrong!
So `Tracking.schema()` is the physical representation of the data, what we expect to be written, or in other words, this is the write schema.
`TrackingStruct.BASE_TYPE` is the logical representation including field(s) that are physically not persisted, or in other words this is the read schema.
Naively asking, since we are on the read path, can't we simply use the read schema from `TrackingStruct` instead of constructing it here from the physical schema?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
Review Comment:
`DELETION_VECTOR` is for data files not for manifests. In general, this makes me wonder how much specific this reader class for manifests as the name of the class suggests, or is it general for all content types.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
Review Comment:
We populate `Tracking.manifestPos` using a metadata column `ROW_POSITION`, while we populate `Tracking.manifestLocation` manually here. For the latter, is there a reason we can't use `MetadataColumns.FILE_PATH` to be consistent?
We could get rid of the custom setter `TrackingStruct.setManifestlocation` method too and let it flow through `internalSet` `getByPos` methods.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
Review Comment:
Instead of checking here, should we rely on the builders enforcing this invariant?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3487462888
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
Review Comment:
I thought we want to drop tuple-based pruning entirely and push predicates against partition-transform-expression columns in `content_stats`. Under that model the partition tuple is only needed to match data files to equality-delete files.
I am planning to bring up the discussion in Monday's sync.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
this name `V4ManifestReader` would be come stale when V5 rolls in. maybe `TrackedFileManifestReader`.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
Review Comment:
nit: `v4` -> `v4+`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3555896071
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
Review Comment:
Done. I was following the original `ManifestReader` as the model. The reader is now just a `CloseableIterable` that applies the configured partition/live filters. I also added a `reuseContainers` option for scan planning.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3540536696
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // Tracking fields read on the scan path. Omits the change-tracking fields (dv_snapshot_id,
+ // deleted_positions, replaced_positions) that a scan does not need. row_position backs
+ // Tracking.manifestPos.
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files. Makes defensive copies before returning. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
Review Comment:
Shouldn't an empty partition type already be handled by the schema generation in the previous statement?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641783464
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,319 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeNonLive;
Review Comment:
I know we've struggled to find a good name for this. Tombstone and non-live aren't quite simple enough. What about instead of focusing on what is being added, we focus on the end state? That is, this flag means we don't filter by status. We can use `includeAll` instead of `includeNonLive` since the live entries are also included.
What do you think about changing this to `includeAll` or something like that?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642017028
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
Review Comment:
I agree on the case sensitivity choice. Good catch.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642101502
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
Review Comment:
`SPEC.specId()`?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642131112
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add((StructLike) file);
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ private V4ManifestReader.Builder newReader(
Review Comment:
This doesn't return a reader and appears to wrap a single function call. Probably best to remove it.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3664474541
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(0)
+ .add(1, 1000, "id", Transforms.identity())
+ .build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById =
+ ImmutableMap.of(spec0.specId(), spec0, spec1.specId(), spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById =
+ dataFile("spec0-id1.parquet", spec0.specId(), unionPartition(unionType, 1, null));
+ TrackedFile prunedById =
+ dataFile("spec0-id2.parquet", spec0.specId(), unionPartition(unionType, 2, null));
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", spec1.specId(), unionPartition(unionType, null, "x"));
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithUnknownSpec(FileFormat format) throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", 5, partition(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsFileWithNullSpecId(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 2))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ assertThat(read.get(0))
+ .as("iterator() should copy each entry rather than yield one reused container")
+ .isNotSameAs(read.get(1));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnknownManifestFormatThrows(FileFormat format) throws IOException {
Review Comment:
I don't think this one needs to be a parameterized test because the `format` isn't used here
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3661466710
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
Review Comment:
Non-blocker as result would be correct, but it's also overly restrictive. If there's a partition filter that has fields compatible with the tracked file's spec, then some amount of filtering could still be performed. This would trigger a lot of over-reads for schema evolution.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646980488
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
Review Comment:
Good point. Renamed to `testStatusfiltering`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647203293
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add((StructLike) file);
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ private V4ManifestReader.Builder newReader(
Review Comment:
Removed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648425648
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
Review Comment:
Use `select` to produce the schema instead of building it like this.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648777118
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
Review Comment:
Agree. That is certainly more future proof. I changed the assertion such that we will validate just the status.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648831079
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
Review Comment:
Done. Case-insensitive select is now the third mode in the merged test.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668775437
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
Review Comment:
Hmm, is this test actually testing anything? I guess technically it produces the correct result, but we're not actually evaluating the filter.
I guess this shields against breaking this behavior in the future, but it's not actually testing what we intend it to test just yet.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3669824747
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
Review Comment:
Good point. Added `testReplaceFieldTypesPrimitive`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3671897319
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
Review Comment:
Fixed. I was thinking of a followup where we cleaned up all v4 test code we already merged.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648520205
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
Review Comment:
Good comment, but I think it means there's a problem with this test.
This is basically saying that we're constructing incorrect tracked files to check that a specific test is being used in the implementation: that `FileContent.DATA_MANIFEST` and `FileContent.DELETE_MANIFEST` are allowed through even if they match. That should not be the behavior of a generic `manifestRef` factory method!
I'm also not sure that this is a good idea. This is testing a particular implementation, when it would be reasonable to remove the `isManifest` method and just rely on `spec_id=null` for manifests. If a manifest has a spec and a partition, then it is probably partitioned and we arguably should use that information.
This goes back to the idea I've expressed in a few other comments: we want to focus on testing correct behavior, not on testing the specific way that behavior is achieved. In this case, the partition for a file has a definition and we don't need to special case manifests.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648523685
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
Review Comment:
It's a bit inconsistent that this test also has metrics assertions but other filter tests don't. I think whether metrics are validated in their own cases or in all tests should be a choice that we follow consistently.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648945992
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
Review Comment:
Done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3669873209
##########
core/src/test/java/org/apache/iceberg/TestTrackedFileStruct.java:
##########
@@ -33,13 +33,9 @@
class TestTrackedFileStruct {
private static final int FORMAT_VERSION_V4 = 4;
- private static final Types.StructType PARTITION_TYPE =
- Types.StructType.of(
- Types.NestedField.optional(1000, "id_bucket", Types.IntegerType.get()),
- Types.NestedField.optional(1001, "category", Types.StringType.get()));
private static final List<Types.NestedField> FIELDS =
Review Comment:
Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670165310
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
Review Comment:
You are correct. I will send a followup PR to clean this up. (too much churn in this PR)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668333210
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
Review Comment:
Why are we using the term 'restricted'? This should be 'selective'. It's a little confusing because we're not restricting, we're down-selecting.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668713217
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
Review Comment:
What we're asserting here doesn't match the description. it says must still project spec_id and partition, but we aren't checking that?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670090612
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
Review Comment:
Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670217743
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
Review Comment:
I don't think there's an over-read here beyond the unavoidable case. Inclusive projection is per-predicate, so `id = 1 AND data = 'z' `against a spec that partitions on `id` (but not `data`) still prunes by `id`. So any field compatible with a spec does contribute to filtering for that spec's files.
The only files kept unfiltered are those whose spec partitions on none of the filter's columns, where there's no partition info to prune on - this is the same as v3 ManifestReader. Added `testPartialFilterStillPrunesOnCompatibleField` to verify this.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633662546
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
+ Schema projection = projection(fullSchema);
+ if (projection == null) {
+ return fullSchema;
+ }
+
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for live filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (hasPartitionFilter()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ projectedIds.add(TrackedFile.PARTITION_ID);
+ projectedIds.addAll(TypeUtil.getProjectedIds(unionPartitionType));
+ }
+
+ // list and map fields cannot be projected by ID; their element IDs carry the selection
+ projectedIds.removeIf(
+ id -> {
+ Types.NestedField field = fullSchema.findField(id);
+ return field != null && (field.type().isListType() || field.type().isMapType());
+ });
+
+ // project instead of select to preserve narrow struct projections from the caller
+ return TypeUtil.project(fullSchema, projectedIds);
+ }
+
+ private Schema projection(Schema fullSchema) {
Review Comment:
What this method is doing is a bit confusing because it accepts a schema but may return a completely different file projection. I think it would be more clear if this were not a helper method, since it could return a completely different field.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633741331
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
Review Comment:
Creating the base schema here seems like an awkward result of waiting for content stats to be done in a separate PR. The metadata schema for a table should be known when the builder is created, which means that we can simplify a bit of the logic. We can create the base schema for `select` and pass it into the builder. And the `select(String...)` method can apply the selection immediately to produce `fileProjection`. Then this method only needs to fix up the schema using `getProjectedIds` and running `TypeUtil.project`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3583433705
##########
core/src/main/java/org/apache/iceberg/TrackedFileStruct.java:
##########
@@ -34,7 +34,10 @@
class TrackedFileStruct extends SupportsIndexProjection implements TrackedFile, Serializable {
private static final Types.StructType EMPTY_STRUCT_TYPE = Types.StructType.of();
- private static final Types.StructType BASE_TYPE =
+ // Package-private only so tests can look up positional ordinals. Unlike
+ // TrackedFile.schemaWithContentStats, the base layout always includes the partition and
+ // content_stats positions.
Review Comment:
This is suspicious to me. We don't want tests to be looking up positions here.
My guess is that the change to omit fields in `schema` caused test cases to fail. But we chose to use that schema for a reason. To make it match, we could replace the partition type with `UnknownType`. Or we could find another solution.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3598156949
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(partitionType, spec.partitionType()));
+ }
+ }
+
+ return new V4ManifestReader(
+ file, readSchema(), partitionEvaluators, partitionProjections, onlyLive, scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !partitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
Review Comment:
Two loops here could go away.
**Loop at 240-249 (replacing `TRACKING`'s type with `SCAN_TRACKING`)** doesn't need to exist at all — build the right shape up front instead of building the wrong shape and rewriting it. Give `TrackedFile.schema` an overload that takes the tracking type:
```java
// in TrackedFile.java
static Types.StructType schema(
Types.StructType partitionType, Types.StructType contentStatsType) {
return schema(Tracking.schema(), partitionType, contentStatsType);
}
static Types.StructType schema(
Types.StructType trackingType,
Types.StructType partitionType,
Types.StructType contentStatsType) {
return Types.StructType.of(
Types.NestedField.required(TRACKING.fieldId(), TRACKING.name(), trackingType, TRACKING.doc()),
CONTENT_TYPE,
FORMAT_VERSION,
LOCATION,
// ...rest unchanged
);
}
```
**Loop at 256-259 (collecting projected field IDs)** is `TypeUtil.getProjectedIds`:
```java
Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(fileProjection));
```
Pairs with the `Tracking.scanSchema()` suggestion above. `readSchema()` collapses to:
```java
private Schema readSchema() {
Schema fullSchema = new Schema(
TrackedFile.schema(Tracking.scanSchema(), partitionType, Types.StructType.of()).fields());
if (fileProjection == null) {
return fullSchema;
}
Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(fileProjection));
projectedIds.add(TrackedFile.TRACKING.fieldId());
projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
if (hasPartitionFilter()) {
projectedIds.add(TrackedFile.SPEC_ID.fieldId());
projectedIds.add(TrackedFile.PARTITION_ID);
}
return TypeUtil.select(fullSchema, projectedIds);
}
```
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
Review Comment:
Should we keep this on the `Tracking` interface? That way, it is easier to keep the two in sync when a new field is added — `schema()` and the scan projection sit next to each other in one file, and whoever adds a new `Tracking` field has to make an explicit choice about whether it belongs on the scan path.
Something like the following in `Tracking.java`, just below `schema()`:
```java
/** Returns the subset of tracking fields projected on the scan path. */
static Types.StructType scanSchema() {
return Types.StructType.of(
STATUS,
SNAPSHOT_ID,
SEQUENCE_NUMBER,
FILE_SEQUENCE_NUMBER,
FIRST_ROW_ID,
MetadataColumns.ROW_POSITION);
}
```
Then `V4ManifestReader` drops the private `SCAN_TRACKING` constant and uses `Tracking.scanSchema()` directly where it currently references `SCAN_TRACKING` (in `readSchema()`).
One caveat: this pulls `MetadataColumns` into `Tracking.java`, which today doesn't reference it. Arguably a plus — it makes the "scan projection includes a synthesized metadata column" fact explicit at the definition site rather than tucked inside the reader.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3481917632
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
Review Comment:
`DELETION_VECTOR` is for data files not for manifests. In general, this makes me wonder how much specific this reader class for manifests as the name of the class suggests, or is it general for all content types.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks merged PR #16958:
URL: https://github.com/apache/iceberg/pull/16958
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648330069
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
Review Comment:
`TrackedFile.tracking()` can be called directly. Does this need to cast to `TrackedFileStruct` first?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648960245
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
Review Comment:
Done. testDefaultReadsFullTracking now builds the reader inline so the no-scanPlanning/select/project configuration is visible in the test body
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648959644
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
Review Comment:
replaced fileWithFullTracking() with a FILE_WITH_FULL_TRACKING constant.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648943628
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
Review Comment:
You're right. removed the cast
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "dramaticlly (via GitHub)" <gi...@apache.org>.
dramaticlly commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3647457321
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,926 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
Review Comment:
```suggestion
TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
```
can probably simplify as projected location is part of dataFile helper
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
Review Comment:
non-blocking: is there a way to wire this skip count to the actual filter? Currently looks like a dead code due to short circuit logic in `entry -> isManifest(entry) || matchesPartition(entry)` and incrementSkipCount is only called within matchesPartition.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,926 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
Review Comment:
nit: want to check if this warrant a quick helper for `equalityDelete(location, equalityIds)` as it can be used in both `testEqualityDeleteRoundTrip` and `testPartitionFilterCountsSkippedDeleteFiles`. Or maybe combine the 2 tests ?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648224871
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
Review Comment:
It isn't needed if the caller doesn't request it. The `project` case is used by Spark metadata tables, which could request any user-driven projection. The required columns here are added to ensure that we can correctly produce any column that has been requested, not because we think there is a minimum set of useful columns. For instance, status is always needed for producing live entries and record_count is used when evaluating row filters.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648481147
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
Review Comment:
I see there's a metrics test just below. I think it would be fine if you wanted to write a manifest, skip several values, and validate metrics in one go. I think this test is just too similar to the partitioning one.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648816300
##########
core/src/test/java/org/apache/iceberg/TestTrackedFile.java:
##########
@@ -39,8 +39,8 @@ public class TestTrackedFile {
PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build().partitionType();
@Test
- public void schemaWithContentStatsFieldOrder() {
- Types.StructType type = TrackedFile.schemaWithContentStats(PARTITION_TYPE, CONTENT_STATS_TYPE);
+ public void schemaFieldOrder() {
+ Types.StructType type = TrackedFile.schema(PARTITION_TYPE, CONTENT_STATS_TYPE).asStruct();
Review Comment:
It is already a StructType
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648044548
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,926 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
Review Comment:
Good idea. Done.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648558762
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterCountsSkippedDeleteFiles(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ partition(2),
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterKeepsManifestReferences(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles(FileFormat format) throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @Test
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).filter(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid filter: null");
+
+ assertThatThrownBy(
+ () -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(format, unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById).filter(Expressions.equal("id", 1)).build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testIteratorReturnsLiveCopies(FileFormat format) throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
Review Comment:
It is better to use `as` to explain assertions instead of comments, so that the test output shows what went wrong.
```java
assertThat(read.get(0))
.as("TrackedFiles from iterator should not be a single reused instance")
.isNotSameAs(read.get(1));
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648827835
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
Review Comment:
Done. I merged the three single-record read tests into one `@MethodSource` test, `testRestrictedReadReturnsOnlyRequestedFields`, parameterized over (format, read-mode)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668742096
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
Review Comment:
I'm guessing this behavior is to be consistent with previous readers, but it seems like not materializing the empty partition creates a special case we'll have to deal with when working with mixed partitions.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670174613
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
+ private final Map<Integer, Type> replacementsById;
+
+ ReplaceTypeById(Map<Integer, Type> replacementsById) {
+ this.replacementsById = replacementsById;
+ }
+
+ @Override
+ public Type schema(Schema schema, Type structResult) {
+ return structResult;
+ }
+
+ @Override
+ public Type struct(Types.StructType struct, List<Type> fieldResults) {
+ List<Types.NestedField> fields = struct.fields();
+ List<Types.NestedField> newFields = Lists.newArrayListWithExpectedSize(fields.size());
+ boolean hasChanged = false;
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ Type fieldReplacement = fieldResults.get(i);
+ Types.NestedField field = fields.get(i);
+ if (field.type() != fieldReplacement) {
+ hasChanged = true;
+ newFields.add(Types.NestedField.from(field).ofType(fieldReplacement).build());
Review Comment:
I checked, and defaults are already handled correctly because it turns out `NestedField` re-validates them against the new type. Added tests for both: testReplaceFieldTypesPreservesDefaultsOnCompatibleType (default survives an int to long promotion) and testReplaceFieldTypesRejectsDefaultIncompatibleWithType (int to string throws).
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3668429349
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
Review Comment:
```suggestion
private static Stream<Arguments> selectiveReadModes() {
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670085468
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
Review Comment:
Good call! Reworked the assertions to cover both directions.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670073386
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
Review Comment:
Renamed to `selective...`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670191480
##########
api/src/main/java/org/apache/iceberg/types/TypeUtil.java:
##########
@@ -157,6 +157,24 @@ public static Schema selectNot(Schema schema, Set<Integer> fieldIds) {
return project(schema, projectedIds);
}
+ /**
+ * Returns a copy of the schema with the type of each field in {@code replacementsById} replaced
+ * by its mapped type. Fields not in the map are unchanged.
+ *
+ * @param schema a schema
+ * @param replacementsById a map from field ID to the type that should replace the field's type
+ * @return a schema with the replaced field types
+ */
+ public static Schema replaceFieldTypes(Schema schema, Map<Integer, Type> replacementsById) {
+ Types.StructType struct = visit(schema, new ReplaceTypeById(replacementsById)).asStructType();
+ if (struct.equals(schema.asStruct())) {
+ return schema;
+ }
+
+ return new Schema(
+ schema.schemaId(), struct.fields(), schema.getAliases(), schema.identifierFieldIds());
Review Comment:
replaceFieldTypes only swaps field types. It rebuilds each changed field with NestedField.from(field).ofType(replacement), which preserves the field ID, name, and optionality, and it carries identifierFieldIds through to the new Schema. So "drops an identifier field" and "makes it optional" aren't reachable through this API because the field and its required-ness are untouched. The one reachable case is making an identifier field non-primitive, and that's already caught: the new Schema constructor runs validateIdentifierField, which rejects it.
Added tests in both directions
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633543619
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
Review Comment:
When `this.fileProjection=null`, it does signal reading the full schema. That doesn't mean that we need to accept `.project(null)`. The field starts in the builder as null, so the case can be triggered by not calling `project` or similar methods.
So I think that Gabor is right to point this out. Do we want to allow null? That depends on whether we have cases where it makes sense to pass a null through, so the caller doesn't have to break method chaining.
```java
Builder builder = V4ManifestReader.builder(...);
// We don't like forcing callers to do this
if (myProjection != null) {
builder.project(null);
}
return builder.build();
```
I think it is generally better to accept null to avoid code like the example above, but in this case I don't see why a caller would have to check. This method is primarily used by metadata tables that receive a specific projection from the Spark read path, so it we don't expect callers to use this if they were passed a null value.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3598009148
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
Review Comment:
Should we keep this on the `Tracking` interface? That way, it is easier to keep the two in sync when a new field is added — `schema()` and the scan projection sit next to each other in one file, and whoever adds a new `Tracking` field has to make an explicit choice about whether it belongs on the scan path.
Something like the following in `Tracking.java`, just below `schema()`:
```java
/** Returns the subset of tracking fields projected on the scan path. */
static Types.StructType scanReadSchema() {
return Types.StructType.of(
STATUS,
SNAPSHOT_ID,
SEQUENCE_NUMBER,
FILE_SEQUENCE_NUMBER,
FIRST_ROW_ID,
MetadataColumns.ROW_POSITION);
}
```
Then `V4ManifestReader` drops the private `SCAN_TRACKING` constant and uses `Tracking.scanSchema()` directly where it currently references `SCAN_TRACKING` (in `readSchema()`).
One caveat: this pulls `MetadataColumns` into `Tracking.java`, which today doesn't reference it. Arguably a plus — it makes the "scan projection includes a synthesized metadata column" fact explicit at the definition site rather than tucked inside the reader.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3616208831
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
Fixed as suggested. `matchesPartition()` now returns true when specId is null and when there is no evaluator for the spec.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(partitionType, spec.partitionType()));
+ }
+ }
+
+ return new V4ManifestReader(
+ file, readSchema(), partitionEvaluators, partitionProjections, onlyLive, scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !partitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
Review Comment:
Thanks for the great suggestion. I have incorporated it - I think the code is much simpler.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,641 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schema(Types.StructType.of(), Types.StructType.of()).fields();
+ private static final int SORT_ORDER_ID_ORDINAL = ordinalOf(TrackedFile.SORT_ORDER_ID.fieldId());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+ ((StructLike) file).set(SORT_ORDER_ID_ORDINAL, SORT_ORDER_ID);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testTrackingProjectionOmitsChangeTrackingFields() throws IOException {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ TrackedFile file =
+ new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ TrackedFile manifestRef =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA_MANIFEST,
+ FORMAT_VERSION_V4,
+ "leaf.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testFileWithUnknownSpecThrows() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so pruning cannot resolve a spec for this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThatThrownBy(() -> Lists.newArrayList(reader))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not one of the known specs");
+ }
+ }
Review Comment:
Aded all three
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
Review Comment:
Done.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
Review Comment:
Done. build() now skips creating the evaluator and projection when the projected filter is alwaysTrue.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
Review Comment:
Renamed.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
Review Comment:
That sounds good to me. I went with `includeTombstones()` which is standard database terminology. Let me know if that sounds reasonable.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,641 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schema(Types.StructType.of(), Types.StructType.of()).fields();
+ private static final int SORT_ORDER_ID_ORDINAL = ordinalOf(TrackedFile.SORT_ORDER_ID.fieldId());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+ ((StructLike) file).set(SORT_ORDER_ID_ORDINAL, SORT_ORDER_ID);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, and spec_id are null because they were not projected
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testTrackingProjectionOmitsChangeTrackingFields() throws IOException {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ TrackedFile file =
+ new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ TrackedFile manifestRef =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA_MANIFEST,
+ FORMAT_VERSION_V4,
+ "leaf.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keep.location(), manifestRef.location());
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).liveOnly().build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testFileWithUnknownSpecThrows() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so pruning cannot resolve a spec for this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThatThrownBy(() -> Lists.newArrayList(reader))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessageContaining("not one of the known specs");
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, int specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
+ tempDir
+ .resolve(
+ "manifest-" + System.nanoTime() + "." + format.name().toLowerCase(Locale.ROOT))
+ .toString());
+ try (FileAppender<StructLike> appender =
+ InternalData.write(format, out).schema(writeSchema).named("tracked_file").build()) {
+ for (TrackedFile file : files) {
+ appender.add(toWriteRow(file, writeSchema));
+ }
+ }
+
+ return fileIO.newInputFile(out.location());
+ }
+
+ /**
+ * Adapts a fully-populated tracked file to a write schema that may omit fields (partition and
+ * content_stats are omitted when empty).
+ */
+ private static StructLike toWriteRow(TrackedFile file, Schema writeSchema) {
Review Comment:
Done. Changed it such that `writeManifest` appends the struct directly now that the schema always carries partition/content_stats
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
+ Types.StructType.of(
+ Tracking.STATUS,
+ Tracking.SNAPSHOT_ID,
+ Tracking.SEQUENCE_NUMBER,
+ Tracking.FILE_SEQUENCE_NUMBER,
+ Tracking.FIRST_ROW_ID,
+ MetadataColumns.ROW_POSITION);
+
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean onlyLive;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean onlyLive,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.onlyLive = onlyLive;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: spec ID %s is not one of the known specs %s in manifest %s",
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean onlyLive = false;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.partitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns only files whose tracking {@link Tracking#isLive() is live}. */
+ Builder liveOnly() {
+ this.onlyLive = true;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
Review Comment:
Thank you for the feedback. The `select`/`project` semantics you described above makes sense to me. The builder now follows this model. I added a `select(Collection<String>)` as the primary configuration API for internal callers and kept `project(Schema)` and made them mutually exclusive.
On stats: deriving the stats schema from bound filter needs the table schema in builder, so we will do that in the content stats reader followup PR.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641379415
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
Review Comment:
yeah, it was `liveOnly` initially, but Ryan wanted to make the default such that we only return live by default. So if callers need non-live files (e.g. for CDF), they need to call `includeNonLive()`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3642128409
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectWithPartitionFilterProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testForScanPlanningOmitsChangeTrackingFields() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testDefaultReadsFullTracking() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @TestTemplate
+ public void testPartitionFilterForceProjectsFilterFields() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "delete.parquet",
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader).isEmpty();
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() throws IOException {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ // a real manifest reference has a null spec_id and no partition tuple; these refs carry a
+ // spec and a tuple that fails the filter so that pruning would be detected if the manifest
+ // passthrough broke
+ TrackedFile dataManifestRef = manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ TrackedFile deleteManifestRef = manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ InputFile manifest =
+ writeManifest(
+ PARTITION_TYPE, ImmutableList.of(keep, prune, dataManifestRef, deleteManifestRef));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ keep.location(), dataManifestRef.location(), deleteManifestRef.location());
+ }
+
+ // the manifest references bypass the filter instead of being evaluated and skipped
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testRowFilterOnUnpartitionedTableKeepsAllFiles() throws IOException {
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testInvalidBuilderArguments() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).filterRows(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid row filter: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).scanMetrics(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid scan metrics: null");
+
+ assertThatThrownBy(() -> newReader(manifest, UNPARTITIONED_SPECS).select(null))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("Invalid columns: null");
+ }
+
+ @TestTemplate
+ public void testCaseInsensitivePartitionFilter() throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @TestTemplate
+ public void testMultiSpecPartitionPruning() throws IOException {
+ PartitionSpec spec0 =
+ PartitionSpec.builderFor(TABLE_SCHEMA).withSpecId(0).identity("id").build();
+ PartitionSpec spec1 =
+ PartitionSpec.builderFor(TABLE_SCHEMA)
+ .withSpecId(1)
+ .add(2, 1001, "data", Transforms.identity())
+ .build();
+ Map<Integer, PartitionSpec> specsById = ImmutableMap.of(0, spec0, 1, spec1);
+ Types.StructType unionType = Partitioning.unionPartitionTypes(specsById.values());
+
+ TrackedFile keepById = dataFile("spec0-id1.parquet", unionPartition(unionType, 1, null), 0);
+ TrackedFile prunedById = dataFile("spec0-id2.parquet", unionPartition(unionType, 2, null), 0);
+ TrackedFile keptOtherSpec =
+ dataFile("spec1-data.parquet", unionPartition(unionType, null, "x"), 1);
+
+ InputFile manifest =
+ writeManifest(unionType, ImmutableList.of(keepById, prunedById, keptOtherSpec));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, specsById)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ // spec0 entries are pruned by id; the spec1 entry is not partitioned by id so it survives
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(keepById.location(), keptOtherSpec.location());
+ }
+ }
+
+ @TestTemplate
+ public void testIteratorReturnsLiveCopies() throws IOException {
+ TrackedFile added1 = dataFile("s3://bucket/added-1.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile added2 = dataFile("s3://bucket/added-2.parquet", EMPTY_PARTITION_DATA);
+ List<TrackedFile> files =
+ ImmutableList.of(
+ added1, added2, fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ List<TrackedFile> read = Lists.newArrayList(reader);
+ assertThat(read)
+ .hasSize(2)
+ .extracting(TrackedFile::location)
+ .containsExactly(added1.location(), added2.location());
+ // iterator() copies each entry, so the collected instances are independent of the reused
+ // container (they would be the same object if iterator() did not copy)
+ assertThat(read.get(0)).isNotSameAs(read.get(1));
+ }
+ }
+
+ @TestTemplate
+ public void testUnknownManifestFormatThrows() throws IOException {
+ InputFile badFile =
+ fileIO.newInputFile(tempDir.resolve("manifest-" + System.nanoTime() + ".txt").toString());
+
+ try (V4ManifestReader reader = newReader(badFile, UNPARTITIONED_SPECS).build()) {
+ assertThatThrownBy(reader::iterator)
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessageContaining("Cannot determine format of manifest");
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithUnknownSpec() throws IOException {
+ // spec ID 5 is not in PARTITIONED_SPECS, so no partition filter applies to this file
+ TrackedFile file = dataFile("orphan.parquet", partition(1), 5);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ // the filter would prune partition id=1 under spec 0, but cannot be applied to spec 5
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsFileWithNullSpecId() throws IOException {
+ TrackedFile file = dataFile("no-spec.parquet", null, null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 2)).build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(file.location());
+ }
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition) {
+ return dataFile(location, partition, 0);
+ }
+
+ private static TrackedFile dataFile(String location, PartitionData partition, Integer specId) {
+ return new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ specId,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithFullTracking() {
+ Tracking tracking =
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}); // replaced positions
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile manifestRef(FileContent content, String location) {
+ ManifestInfo info = new ManifestInfoStruct(1, 0, 0, 0, 1L, 0L, 0L, 0L, 1L, null, null);
+ return new TrackedFileStruct(
+ addedTracking(),
+ content,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ partition(2),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ info,
+ null,
+ null,
+ null);
+ }
+
+ private static TrackedFile fileWithStatus(EntryStatus status, String location) {
+ Tracking tracking = new TrackingStruct(status, SNAPSHOT_ID, 3L, 3L, null, null, null, null);
+ return new TrackedFileStruct(
+ tracking,
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ location,
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+ }
+
+ private static Tracking addedTracking() {
+ return new TrackingStruct(EntryStatus.ADDED, SNAPSHOT_ID, null, null, null, null, null, null);
+ }
+
+ private static DeletionVector deletionVector(
+ String location, long offset, long sizeInBytes, long cardinality) {
+ DeletionVectorStruct dv = new DeletionVectorStruct(DeletionVector.schema());
+ dv.set(0, location);
+ dv.set(1, offset);
+ dv.set(2, sizeInBytes);
+ dv.set(3, cardinality);
+ return dv;
+ }
+
+ private static PartitionData partition(int id) {
+ PartitionData partition = new PartitionData(PARTITION_TYPE);
+ partition.set(0, id);
+ return partition;
+ }
+
+ private static PartitionData unionPartition(Types.StructType unionType, Integer id, String data) {
+ PartitionData partition = new PartitionData(unionType);
+ partition.set(0, id);
+ partition.set(1, data);
+ return partition;
+ }
+
+ private InputFile writeManifest(Types.StructType partitionType, Iterable<TrackedFile> files)
+ throws IOException {
+ Schema writeSchema =
+ new Schema(TrackedFile.schema(partitionType, Types.StructType.of()).fields());
+ OutputFile out =
+ fileIO.newOutputFile(
Review Comment:
It's usually better to use `InMemoryOutputFile` rather than creating local files.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646399078
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base =
+ new Schema(TrackedFile.schema(unionPartitionType, Types.StructType.of()).fields());
Review Comment:
Done. TrackedFile.schema now returns a Schema, matching ManifestEntry.getSchema.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501038050
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
Review Comment:
That sounds like a good idea. Switched the builder to compute and store partitionType in the constructor.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501618426
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
Review Comment:
Yes, we only rely on status now, and projecting only that.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501009698
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
Review Comment:
Fixed. I think both conventions are used by the project. Agree, `checkArgument` is probably better because it throws an `IllegalArgumentsException` instead of NPE.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646937390
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
Review Comment:
They didn't. Reordered the constructor args so partition comes after spec_id, matching the schema/field order
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648969286
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,304 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema requestedProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base = TrackedFile.schema(unionPartitionType, Types.StructType.of());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a filter; files that cannot match the expression are skipped. */
+ Builder filter(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && requestedProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ requestedProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.requestedProjection = newProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters = Maps.newHashMap();
+ if (rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ Evaluator evaluator = new Evaluator(spec.partitionType(), partFilter, caseSensitive);
+ StructProjection projection =
+ StructProjection.create(unionPartitionType, spec.partitionType());
+ partitionFilters.put(spec.specId(), Pair.of(evaluator, projection));
+ }
+ }
+ }
+
+ boolean hasPartitionFilter = !partitionFilters.isEmpty();
+ return new V4ManifestReader(
+ file, readSchema(hasPartitionFilter), partitionFilters, includeAll, scanMetrics);
+ }
+
+ private Schema readSchema(boolean hasPartitionFilter) {
+ if (scanPlanning) {
+ // scan planning does not read the change-tracking fields omitted by SCAN_TYPE
+ return TypeUtil.replaceFieldTypes(
+ fullSchema, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.SCAN_TYPE));
+ }
+
+ if (columns != null) {
+ Schema selected =
+ caseSensitive ? fullSchema.select(columns) : fullSchema.caseInsensitiveSelect(columns);
+ return addRequiredColumns(selected, hasPartitionFilter);
+ }
+
+ if (requestedProjection != null) {
+ return addRequiredColumns(requestedProjection, hasPartitionFilter);
+ }
+
+ return fullSchema;
+ }
+
+ private Schema addRequiredColumns(Schema projection, boolean hasPartitionFilter) {
+ Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(projection));
+
+ // fields the reader consumes internally: status for liveness filtering, row_position for
+ // manifestPos, and content type to distinguish entry kinds
+ projectedIds.add(Tracking.STATUS.fieldId());
+ projectedIds.add(MetadataColumns.ROW_POSITION.fieldId());
+ projectedIds.add(TrackedFile.CONTENT_TYPE.fieldId());
+ if (rowFilter != Expressions.alwaysTrue()) {
Review Comment:
Agreed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3646959364
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,893 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ partition(7),
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ assertThat(actual.formatVersion()).isEqualTo(FORMAT_VERSION_V4);
+ assertThat(actual.location()).isEqualTo("s3://bucket/data/file.parquet");
+ assertThat(actual.fileFormat()).isEqualTo(FileFormat.PARQUET);
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ assertThat(actual.fileSizeInBytes()).isEqualTo(FILE_SIZE_IN_BYTES);
+ assertThat(actual.specId()).isEqualTo(0);
+ assertThat(actual.sortOrderId()).isEqualTo(SORT_ORDER_ID);
+ assertThat(actual.keyMetadata()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2, 3}));
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.partition().get(0, Integer.class)).isEqualTo(7);
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().snapshotId()).isEqualTo(SNAPSHOT_ID);
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(DV_LOCATION);
+ assertThat(actual.deletionVector().offset()).isEqualTo(DV_OFFSET);
+ assertThat(actual.deletionVector().sizeInBytes()).isEqualTo(DV_SIZE_IN_BYTES);
+ assertThat(actual.deletionVector().cardinality()).isEqualTo(DV_CARDINALITY);
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ SORT_ORDER_ID,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @TestTemplate
+ public void testRowFilterForcesRecordCount() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filterRows(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @TestTemplate
+ public void testSelectRestrictsFields() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).select(ImmutableList.of("location")).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testCaseInsensitiveSelect() throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @TestTemplate
+ public void testProjectionPreservesNarrowTrackingProjection() throws IOException {
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @TestTemplate
+ public void testSelectListColumn() throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ EMPTY_PARTITION_DATA,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
Review Comment:
I'm on the fence about `location`. We are force projecting `status` and `content_type` because they are required by the reader internally. I'm inclined to think that other callers should include `location` in the projection if they care about it.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648942628
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
Review Comment:
Done. switched the single-element reads to Iterables.getOnlyElement(...) throughout
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648941839
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
Review Comment:
Renamed to `testReadsWrittenFile`. Agreed "round trip" implies serialization. I went with `testReadsWrittenFile` rather than `testInheritedTrackingValues` since the comparison now uses a status-only tracking projection and doesn't assert inherited values
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648870485
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select(ImmutableList.of("location")))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ Schema projection =
+ new Schema(
+ Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(), "tracking", Types.StructType.of(Tracking.STATUS)));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectListColumn(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("split_offsets"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.splitOffsets()).containsExactly(50L, 100L);
+ assertThat(actual.location()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Lists.newArrayList(reader).get(0).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(fileWithFullTracking()));
+
+ // without a projection, the reader returns the full schema for copying to other manifests,
+ // including the change-tracking fields
+ Tracking actual = read(manifest, UNPARTITIONED_SPECS).get(0).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(keep.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesNonMatchingFiles(FileFormat format) throws IOException {
Review Comment:
Deduped. Combined them all into `testPartitionFilterPrunesFilesAndCountsSkips`
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3633608007
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
Review Comment:
The name of this method isn't accurate. A row filter is not a partition filter, it is a row filter that we may be able to project to produce a partition filter. Just having partition fields doesn't mean that a partition filter can be produced.
I think that this should check whether any partition spec ID is associated with a partition filter after projecting the row filter. Looking at the current usage, that means we should turn this into a local boolean:
```java
boolean hasPartitionFilter = !partitionEvaluators.isEmpty();
Schema readSchema = readSchema(hasPartitionFilter);
```
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3640943581
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkArgument(newScanMetrics != null, "Invalid scan metrics: null");
+ this.scanMetrics = newScanMetrics;
+ return this;
+ }
+
+ V4ManifestReader build() {
+ Map<Integer, Evaluator> partitionEvaluators = Maps.newHashMap();
+ Map<Integer, StructProjection> partitionProjections = Maps.newHashMap();
+ if (hasPartitionFilter()) {
+ for (PartitionSpec spec : specsById.values()) {
+ Expression partFilter = Projections.inclusive(spec, caseSensitive).project(rowFilter);
+ if (partFilter != Expressions.alwaysTrue()) {
+ partitionEvaluators.put(
+ spec.specId(), new Evaluator(spec.partitionType(), partFilter, caseSensitive));
+ partitionProjections.put(
+ spec.specId(), StructProjection.create(unionPartitionType, spec.partitionType()));
+ }
+ }
+ }
+
+ return new V4ManifestReader(
+ file,
+ readSchema(),
+ partitionEvaluators,
+ partitionProjections,
+ includeTombstones,
+ scanMetrics);
+ }
+
+ private boolean hasPartitionFilter() {
+ return rowFilter != Expressions.alwaysTrue() && !unionPartitionType.fields().isEmpty();
+ }
+
+ private Schema readSchema() {
+ Types.StructType trackingType =
+ scanPlanning ? TrackingStruct.SCAN_TYPE : TrackingStruct.BASE_TYPE;
+ Schema fullSchema =
+ new Schema(
+ TrackedFile.schema(trackingType, unionPartitionType, Types.StructType.of()).fields());
Review Comment:
Done. the full schema is now built once in the builder constructor instead of inside readSchema. Content stats are still an empty struct until that PR, but construction no longer depends on it, and select/project resolve against that pre-built schema
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3648415861
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,909 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.FieldSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final int SORT_ORDER_ID = 1;
+ private static final String DV_LOCATION = "s3://bucket/dv.puffin";
+ private static final long DV_OFFSET = 100L;
+ private static final long DV_SIZE_IN_BYTES = 50L;
+ private static final long DV_CARDINALITY = 5L;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // row_position is appended after the tracking schema fields by the reader
+ private static final int MANIFEST_POS_ORDINAL = Tracking.schema().fields().size();
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRoundTrip(FileFormat format) throws IOException {
+ DeletionVector dv = deletionVector(DV_LOCATION, DV_OFFSET, DV_SIZE_IN_BYTES, DV_CARDINALITY);
+
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ SPEC.specId(),
+ partition(7),
+ null,
+ SORT_ORDER_ID,
+ dv,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ // the reader fills row_position (manifestPos) and manifestLocation, which the written file
+ // does not have; mirror them on the expected file before comparing
+ TrackingStruct expectedTracking = (TrackingStruct) ((TrackedFileStruct) file).tracking();
+ expectedTracking.set(MANIFEST_POS_ORDINAL, 0L);
+ expectedTracking.setManifestLocation(manifest.location());
+
+ Types.StructType readType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE))
+ .asStruct();
+ assertThat(Comparators.forType(readType).compare((StructLike) file, (StructLike) actual))
+ .isEqualTo(0);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking and content_type are always projected, even though the caller omitted them
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // sort_order_id, file_format, spec_id, and record_count are null because they were not
+ // projected and no row filter forces them
+ assertThat(actual.sortOrderId()).isNull();
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.recordCount()).isEqualTo(-1L);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectRestrictsFields(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("location"))
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ // tracking status and content_type are joined in even though not selected
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.contentType()).isEqualTo(FileContent.DATA);
+ // only status is joined from tracking, not the other tracking fields
+ assertThat(actual.tracking().snapshotId()).isNull();
+ // file_format and spec_id are null because they were not selected
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitiveSelect(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select(ImmutableList.of("LOCATION"))
+ .caseSensitive(false)
+ .build()) {
+ TrackedFile actual = Lists.newArrayList(reader).get(0);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isNull();
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
Review Comment:
Use `InMemoryOutputFile`?
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "danielcweeks (via GitHub)" <gi...@apache.org>.
danielcweeks commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3661412826
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
Review Comment:
Minor oversight here: we only test for struct/list, but not a primitive field (it does work, but there's no test)
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3624210111
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
Review Comment:
It's not clear whether we should throw or just skip scan metrics.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641379415
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,314 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
Review Comment:
yeah, it was `liveOnly` initially, but Ryan wanted to make the default such that we only return live by default. So if callers need non-live, caller need to call `includeNonLive()`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "rdblue (via GitHub)" <gi...@apache.org>.
rdblue commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3641987580
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
Review Comment:
I'm closing this to help reviews since we discussed it a few weeks ago.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3555857111
##########
core/src/main/java/org/apache/iceberg/Partitioning.java:
##########
@@ -238,9 +238,18 @@ public static StructType groupingKeyType(Schema schema, Collection<PartitionSpec
* @return the constructed unified partition type
*/
public static StructType partitionType(Table table) {
- Collection<PartitionSpec> specs = table.specs().values();
- return buildPartitionProjectionType(
- "table partition", specs, allActiveFieldIds(table.schema(), specs));
+ return partitionType(table.schema(), table.specs().values());
+ }
+
+ /**
+ * Builds a unified partition type from a schema and its specs, unioning every partition field
+ * whose source column is present in the schema.
+ *
+ * @param schema the schema used to determine which partition fields are active
+ * @param specs the partition specs to unify
+ */
+ static StructType partitionType(Schema schema, Collection<PartitionSpec> specs) {
+ return buildPartitionProjectionType("table partition", specs, allActiveFieldIds(schema, specs));
Review Comment:
Fixed. `partitionType` now unions all partition fields across specs and the reader's builder no longer takes a table schema. I left the existing `partitionType(Table)` unchanged since fixing it has wider implications; we can revisit separately. Added a test that a partition field survives dropping its source column.
I agree the output type is only underivable for identity and truncate, but `PartitionSpec.partitionType()` currently returns `unknown` whenever the source column is missing so today even a bucket field degrades. If it makes sense, I can do a follow-up that only falls back to unknown for source-dependent transforms, which shrinks this to the rare case you described. I also did some code reading in Iceberg rust, which seems to have a hard failure, possibly because `unknown` type is not supported yet in Iceberg Rust.
BTW +1 to storing the output type in metadata. v4 seems like the right time to add it since we're already revising the spec. It seems like a good overall improvement. Happy to write that up.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3598009148
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ // tracking fields read on the scan path; row_position backs Tracking.manifestPos
+ private static final Types.StructType SCAN_TRACKING =
Review Comment:
Should we keep this on the `Tracking` interface? That way, it is easier to keep the two in sync when a new field is added — `schema()` and the scan projection sit next to each other in one file, and whoever adds a new `Tracking` field has to make an explicit choice about whether it belongs on the scan path.
Something like the following in `Tracking.java`, just below `schema()`:
```java
/** Returns the subset of tracking fields projected on the scan path. */
static Types.StructType scanSchema() {
return Types.StructType.of(
STATUS,
SNAPSHOT_ID,
SEQUENCE_NUMBER,
FILE_SEQUENCE_NUMBER,
FIRST_ROW_ID,
MetadataColumns.ROW_POSITION);
}
```
Then `V4ManifestReader` drops the private `SCAN_TRACKING` constant and uses `Tracking.scanSchema()` directly where it currently references `SCAN_TRACKING` (in `readSchema()`).
One caveat: this pulls `MetadataColumns` into `Tracking.java`, which today doesn't reference it. Arguably a plus — it makes the "scan projection includes a synthesized metadata column" fact explicit at the definition site rather than tucked inside the reader.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3622644314
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
Review Comment:
nit: `Cannot use select(Collection<String>) with project(Schema)`
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
+ Types.StructType replacement = Types.StructType.of(required(10, "x", IntegerType.get()));
+ Schema schema =
+ new Schema(
+ required(1, "id", IntegerType.get()),
+ required(2, "s", Types.StructType.of(required(3, "a", Types.LongType.get()))));
+
+ Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, (Type) replacement));
+
+ assertThat(result.findField(1).type()).isEqualTo(IntegerType.get());
+ assertThat(result.findField(2).type()).isEqualTo(replacement);
+ }
+
+ @Test
+ public void testReplaceFieldTypesListElement() {
+ Schema schema =
+ new Schema(required(1, "list", Types.ListType.ofRequired(2, Types.StructType.of())));
+
+ Schema result =
+ TypeUtil.replaceFieldTypes(
+ schema,
+ ImmutableMap.of(2, (Type) Types.StructType.of(required(3, "x", IntegerType.get()))));
Review Comment:
```suggestion
ImmutableMap.of(2, Types.StructType.of(required(3, "x", IntegerType.get()))));
```
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
+ Types.StructType replacement = Types.StructType.of(required(10, "x", IntegerType.get()));
+ Schema schema =
+ new Schema(
+ required(1, "id", IntegerType.get()),
+ required(2, "s", Types.StructType.of(required(3, "a", Types.LongType.get()))));
+
+ Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, (Type) replacement));
Review Comment:
```suggestion
Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, replacement));
```
unnecessary cast here and in the other tests
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
+ private final Map<Integer, Type> replacementsById;
+
+ ReplaceTypeById(Map<Integer, Type> replacementsById) {
+ this.replacementsById = replacementsById;
+ }
+
+ @Override
+ public Type schema(Schema schema, Type structResult) {
+ return structResult;
+ }
+
+ @Override
+ public Type struct(Types.StructType struct, List<Type> fieldResults) {
+ List<Types.NestedField> fields = struct.fields();
+ List<Types.NestedField> newFields = Lists.newArrayListWithExpectedSize(fields.size());
+ boolean hasChanged = false;
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ Type fieldReplacement = fieldResults.get(i);
+ Types.NestedField field = fields.get(i);
+ if (field.type() != fieldReplacement) {
+ hasChanged = true;
+ newFields.add(Types.NestedField.from(field).ofType(fieldReplacement).build());
Review Comment:
do we need to handle initial/write defaults here when we're changing the type? What happens if the original type is int with some defaults but we change the type to string? I think we should have a test for this scenario
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private final Schema fullSchema;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeAll = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema requestedProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.specsById = specsById;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ Schema base = TrackedFile.schema(unionPartitionType, Types.StructType.of());
+ // the read schema carries row_position (via BASE_TYPE) so the reader can fill manifestPos
+ this.fullSchema =
+ TypeUtil.replaceFieldTypes(
+ base, ImmutableMap.of(TrackedFile.TRACKING.fieldId(), TrackingStruct.BASE_TYPE));
+ }
+
+ /** Sets a filter; files that cannot match the expression are skipped. */
+ Builder filter(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns all entries without filtering by {@link Tracking#isLive() liveness}. */
+ Builder includeAll() {
+ this.includeAll = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && requestedProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(String... newColumns) {
+ return select(Arrays.asList(newColumns));
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ requestedProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newProjection) {
Review Comment:
nit: `project(null)` would read everything. If that is a supported case, then we should have a test for it or add a `newProjection != null` check
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
Review Comment:
minor: I think it might be worth pulling this out into a separate PR in order to reduce complexity in this one and harden the impl + have more extensive tests (especially around default value handling)
##########
api/src/test/java/org/apache/iceberg/types/TestTypeUtil.java:
##########
@@ -1037,4 +1038,41 @@ public void testIndexStatsNames() {
.containsEntry(24, "addresses_value") // the leaf takes precedence
.hasSize(22);
}
+
+ @Test
+ public void testReplaceFieldTypes() {
+ Types.StructType replacement = Types.StructType.of(required(10, "x", IntegerType.get()));
+ Schema schema =
+ new Schema(
+ required(1, "id", IntegerType.get()),
+ required(2, "s", Types.StructType.of(required(3, "a", Types.LongType.get()))));
+
+ Schema result = TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(2, (Type) replacement));
+
+ assertThat(result.findField(1).type()).isEqualTo(IntegerType.get());
+ assertThat(result.findField(2).type()).isEqualTo(replacement);
+ }
+
+ @Test
+ public void testReplaceFieldTypesListElement() {
+ Schema schema =
+ new Schema(required(1, "list", Types.ListType.ofRequired(2, Types.StructType.of())));
+
+ Schema result =
+ TypeUtil.replaceFieldTypes(
+ schema,
+ ImmutableMap.of(2, (Type) Types.StructType.of(required(3, "x", IntegerType.get()))));
+
+ Types.ListType list = (Types.ListType) result.findField(1).type();
+ assertThat(list.elementType().asStructType().field(3).name()).isEqualTo("x");
+ assertThat(list.isElementRequired()).isTrue();
+ }
+
+ @Test
+ public void testReplaceFieldTypesNoMatchReturnsSameSchema() {
+ Schema schema = new Schema(required(1, "id", IntegerType.get()));
+ Schema result =
+ TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(99, (Type) Types.LongType.get()));
Review Comment:
```suggestion
TypeUtil.replaceFieldTypes(schema, ImmutableMap.of(99, Types.LongType.get()));
```
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeTombstones;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ boolean includeTombstones,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.includeTombstones = includeTombstones;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeTombstones) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Evaluator evaluator = partitionEvaluators.get(specId);
+ if (evaluator == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ StructProjection projection = partitionProjections.get(specId);
+ Preconditions.checkState(
+ projection != null,
+ "Cannot produce partition tuple for spec ID %s in manifest %s",
+ specId,
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
+ switch (content) {
+ case DATA:
+ scanMetrics.skippedDataFiles().increment();
+ break;
+ case EQUALITY_DELETES:
+ scanMetrics.skippedDeleteFiles().increment();
+ break;
+ case DATA_MANIFEST:
+ scanMetrics.skippedDataManifests().increment();
+ break;
+ case DELETE_MANIFEST:
+ scanMetrics.skippedDeleteManifests().increment();
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported content type: " + content);
+ }
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Cannot determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema)
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it in
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private static boolean isManifest(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ return content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST;
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Types.StructType unionPartitionType;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private boolean includeTombstones = false;
+ private boolean scanPlanning = false;
+ private Collection<String> columns = null;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.unionPartitionType = Partitioning.unionPartitionTypes(specsById.values());
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkArgument(expr != null, "Invalid row filter: null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ /** Returns deleted and replaced files in addition to {@link Tracking#isLive() live} files. */
+ Builder includeTombstones() {
+ this.includeTombstones = true;
+ return this;
+ }
+
+ /** Configures the reader to select the minimal fields needed for scan planning. */
+ Builder forScanPlanning() {
+ Preconditions.checkState(
+ columns == null && fileProjection == null,
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ this.scanPlanning = true;
+ return this;
+ }
+
+ /** Selects columns to read by name; fields needed by the reader are always read. */
+ Builder select(Collection<String> newColumns) {
+ Preconditions.checkArgument(newColumns != null, "Invalid columns: null");
+ Preconditions.checkState(
+ !scanPlanning, "Cannot use select(Collection<String>) with forScanPlanning()");
+ Preconditions.checkState(
+ fileProjection == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+ this.columns = newColumns;
+ return this;
+ }
+
+ /** Sets the exact schema to read; used in place of {@link #select(Collection)}. */
+ Builder project(Schema newFileProjection) {
+ Preconditions.checkState(!scanPlanning, "Cannot use project(Schema) with forScanPlanning()");
+ Preconditions.checkState(
+ columns == null,
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
Review Comment:
nit: since we're inside `project` maybe the error msg should be `Cannot use project(Schema) with select(...)` to be slightly more consistent around what gets mentioned first
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,310 @@
+/*
+ * 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.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+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.Maps;
+import org.apache.iceberg.relocated.com.google.common.collect.Sets;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.Pair;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Schema readSchema;
+ private final boolean includeAll;
+ private final ScanMetrics scanMetrics;
+
+ // partition filters keyed by spec ID; empty when no partition filter applies
+ private final Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters;
+
+ private V4ManifestReader(
+ InputFile file,
+ Schema readSchema,
+ Map<Integer, Pair<Evaluator, StructProjection>> partitionFilters,
+ boolean includeAll,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.readSchema = readSchema;
+ this.partitionFilters = partitionFilters;
+ this.includeAll = includeAll;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(InputFile file, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, specsById);
+ }
+
+ /** Returns copies of the tracked files that match this reader's configured filters. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionFilters.isEmpty()) {
+ // manifests have no partition, so the partition filter cannot apply to them
+ entries =
+ CloseableIterable.filter(entries, entry -> isManifest(entry) || matchesPartition(entry));
+ }
+
+ if (!includeAll) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return CloseableIterable.transform(entries, TrackedFile::copy).iterator();
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ Integer specId = trackedFile.specId();
+ if (specId == null) {
+ // a file without a spec is not partitioned and may match the filter
+ return true;
+ }
+
+ Pair<Evaluator, StructProjection> partitionFilter = partitionFilters.get(specId);
+ if (partitionFilter == null) {
+ // the row filter does not project to a partition filter for this spec
+ return true;
+ }
+
+ Evaluator evaluator = partitionFilter.first();
+ StructProjection projection = partitionFilter.second();
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ incrementSkipCount(trackedFile.contentType());
+ }
+
+ return matches;
+ }
+
+ private void incrementSkipCount(FileContent content) {
Review Comment:
I think this can be shortened/simplified via
```
private void incrementSkipCount(FileContent content) {
switch (content) {
case DATA -> scanMetrics.skippedDataFiles().increment();
case EQUALITY_DELETES -> scanMetrics.skippedDeleteFiles().increment();
case DATA_MANIFEST -> scanMetrics.skippedDataManifests().increment();
case DELETE_MANIFEST -> scanMetrics.skippedDeleteManifests().increment();
default -> throw new UnsupportedOperationException("Unsupported content type: " + content);
}
}
```
##########
api/src/main/java/org/apache/iceberg/types/ReplaceTypeById.java:
##########
@@ -0,0 +1,107 @@
+/*
+ * 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.types;
+
+import java.util.List;
+import java.util.Map;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+
+class ReplaceTypeById extends TypeUtil.SchemaVisitor<Type> {
+ private final Map<Integer, Type> replacementsById;
+
+ ReplaceTypeById(Map<Integer, Type> replacementsById) {
+ this.replacementsById = replacementsById;
+ }
+
+ @Override
+ public Type schema(Schema schema, Type structResult) {
+ return structResult;
+ }
+
+ @Override
+ public Type struct(Types.StructType struct, List<Type> fieldResults) {
+ List<Types.NestedField> fields = struct.fields();
+ List<Types.NestedField> newFields = Lists.newArrayListWithExpectedSize(fields.size());
+ boolean hasChanged = false;
+
+ for (int i = 0; i < fields.size(); i += 1) {
+ Type fieldReplacement = fieldResults.get(i);
+ Types.NestedField field = fields.get(i);
+ if (field.type() != fieldReplacement) {
+ hasChanged = true;
+ newFields.add(Types.NestedField.from(field).ofType(fieldReplacement).build());
+ } else {
+ newFields.add(field);
+ }
+ }
+
+ if (hasChanged) {
+ return Types.StructType.of(newFields);
+ }
+
+ return struct;
+ }
+
+ @Override
+ public Type field(Types.NestedField field, Type fieldResult) {
+ return replacementsById.getOrDefault(field.fieldId(), fieldResult);
+ }
+
+ @Override
+ public Type list(Types.ListType list, Type elementResult) {
+ Type elementReplacement = replacementsById.getOrDefault(list.elementId(), elementResult);
+ if (list.elementType() != elementReplacement) {
+ if (list.isElementRequired()) {
+ return Types.ListType.ofRequired(list.elementId(), elementReplacement);
+ } else {
+ return Types.ListType.ofOptional(list.elementId(), elementReplacement);
+ }
+ }
+
+ return list;
+ }
+
+ @Override
+ public Type map(Types.MapType map, Type keyResult, Type valueResult) {
Review Comment:
do we have a test that verifies replacement on maps?
##########
api/src/main/java/org/apache/iceberg/types/TypeUtil.java:
##########
@@ -157,6 +157,24 @@ public static Schema selectNot(Schema schema, Set<Integer> fieldIds) {
return project(schema, projectedIds);
}
+ /**
+ * Returns a copy of the schema with the type of each field in {@code replacementsById} replaced
+ * by its mapped type. Fields not in the map are unchanged.
+ *
+ * @param schema a schema
+ * @param replacementsById a map from field ID to the type that should replace the field's type
+ * @return a schema with the replaced field types
+ */
+ public static Schema replaceFieldTypes(Schema schema, Map<Integer, Type> replacementsById) {
+ Types.StructType struct = visit(schema, new ReplaceTypeById(replacementsById)).asStructType();
+ if (struct.equals(schema.asStruct())) {
+ return schema;
+ }
+
+ return new Schema(
+ schema.schemaId(), struct.fields(), schema.getAliases(), schema.identifierFieldIds());
Review Comment:
what happens if the replacement drops an identifier field or makes it optional/non-primitive? I think we should have some tests for this scenario
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "nastra (via GitHub)" <gi...@apache.org>.
nastra commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3664384621
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
Review Comment:
`V4ManifestReader.Builder` gets exposed outside its defined visibility scope. Making the test class package-private fixes this. Also looks like `description` isn't used here
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670133274
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testMultiSpecPartitionPruning(FileFormat format) throws IOException {
Review Comment:
Renamed to `testFilterMatchesFilesAcrossDisjointSpecs`
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterPrunesFilesAndCountsSkips(FileFormat format) throws IOException {
+ // FILE_A and EQ_DELETES_A match the filter; FILE_B and EQ_DELETES_B are pruned; manifest
+ // references have no partition and are always kept
+ InputFile manifest =
+ writeManifest(
+ format,
+ PARTITION_TYPE,
+ ImmutableList.of(
+ FILE_A,
+ FILE_B,
+ EQ_DELETES_A,
+ EQ_DELETES_B,
+ DATA_MANIFEST_REF,
+ DELETE_MANIFEST_REF));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder(
+ FILE_A.location(),
+ EQ_DELETES_A.location(),
+ DATA_MANIFEST_REF.location(),
+ DELETE_MANIFEST_REF.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value())
+ .as("one data file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDeleteFiles().value())
+ .as("one delete file is pruned by the partition filter")
+ .isEqualTo(1L);
+ assertThat(metrics.skippedDataManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ assertThat(metrics.skippedDeleteManifests().value())
+ .as("manifests have no partition and are not pruned")
+ .isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterKeepsFilesWithoutStats(FileFormat format) throws IOException {
+ // with no content stats to evaluate, the row filter cannot prune any file
+ TrackedFile file1 = dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA);
+ TrackedFile file2 = dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file1, file2));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .filter(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader)
+ .extracting(TrackedFile::location)
+ .containsExactly(file1.location(), file2.location());
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(0L);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testCaseInsensitivePartitionFilter(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .filter(Expressions.equal("ID", 1))
+ .caseSensitive(false)
Review Comment:
Good idea. Added the inverse.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670151515
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
+ ImmutableList.of(FileFormat.AVRO, FileFormat.PARQUET);
+
+ // a data file whose tracking carries every inheritable and change-tracking value set
+ private static final TrackedFile FILE_WITH_FULL_TRACKING =
+ new TrackedFileStruct(
+ new TrackingStruct(
+ EntryStatus.ADDED,
+ SNAPSHOT_ID,
+ 5L, // data sequence number
+ 6L, // file sequence number
+ 7L, // dv snapshot id
+ 8L, // first row id
+ new byte[] {1, 2}, // deleted positions
+ new byte[] {3, 4}), // replaced positions
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null);
+
+ // shared data files: FILE_A is in partition id=1, FILE_B in partition id=2
+ private static final TrackedFile FILE_A = dataFile("data-a.parquet", partition(1));
+ private static final TrackedFile FILE_B = dataFile("data-b.parquet", partition(2));
+ private static final TrackedFile EQ_DELETES_A = deleteFile("eq-deletes-a.parquet", partition(1));
+ private static final TrackedFile EQ_DELETES_B = deleteFile("eq-deletes-b.parquet", partition(2));
+ private static final TrackedFile DATA_MANIFEST_REF =
+ manifestRef(FileContent.DATA_MANIFEST, "data-leaf.parquet");
+ private static final TrackedFile DELETE_MANIFEST_REF =
+ manifestRef(FileContent.DELETE_MANIFEST, "delete-leaf.parquet");
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testReadsWrittenFile(FileFormat format) throws IOException {
+ TrackedFile file =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.DATA,
+ FORMAT_VERSION_V4,
+ "s3://bucket/data/file.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ ID_PARTITIONING.specId(),
+ partition(7),
+ null,
+ 1, // sort order id
+ DV,
+ null,
+ ByteBuffer.wrap(new byte[] {1, 2, 3}),
+ ImmutableList.of(50L, 100L),
+ null);
+
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, PARTITIONED_SPECS));
+
+ // compare with tracking reduced to status: the reader fills status-independent tracking
+ // fields (row position, sequence numbers via inheritance) that the written file does not have
+ Types.StructType comparisonType =
+ TypeUtil.replaceFieldTypes(
+ TrackedFile.schema(PARTITION_TYPE, Types.StructType.of()),
+ ImmutableMap.of(
+ TrackedFile.TRACKING.fieldId(), Types.StructType.of(Tracking.STATUS)))
+ .asStruct();
+ assertThat((StructLike) actual)
+ .usingComparator(Comparators.forType(comparisonType))
+ .isEqualTo((StructLike) file);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testEqualityDeleteRoundTrip(FileFormat format) throws IOException {
+ TrackedFile delete =
+ new TrackedFileStruct(
+ addedTracking(),
+ FileContent.EQUALITY_DELETES,
+ FORMAT_VERSION_V4,
+ "s3://bucket/eq-delete.parquet",
+ FileFormat.PARQUET,
+ RECORD_COUNT,
+ FILE_SIZE_IN_BYTES,
+ 0,
+ EMPTY_PARTITION_DATA,
+ null,
+ null,
+ null,
+ null,
+ null,
+ null,
+ ImmutableList.of(1, 2));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testStatusFiltering(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ }
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).includeAll().build()) {
+ assertThat(reader)
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testManifestLocationAndPosition(FileFormat format) throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @ParameterizedTest(name = "{0} / {2}")
+ @MethodSource("restrictedReadModes")
+ public void testRestrictedReadReturnsOnlyRequestedFields(
+ FileFormat format, Consumer<V4ManifestReader.Builder> configureRead, String description)
+ throws IOException {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/live.parquet", EMPTY_PARTITION_DATA),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, files);
+
+ V4ManifestReader.Builder builder = V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS);
+ configureRead.accept(builder);
+ try (V4ManifestReader reader = builder.build()) {
+ // content_type and status are projected for liveness filtering, so only the live entry
+ // survives even though the caller requested only location
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo("s3://bucket/live.parquet");
+ // fields the caller did not request are not read
+ assertThat(actual.fileFormat()).isNull();
+ assertThat(actual.specId()).isNull();
+ assertThat(actual.sortOrderId()).isNull();
+ }
+ }
+
+ private static Stream<Arguments> restrictedReadModes() {
+ Map<String, Consumer<V4ManifestReader.Builder>> modes =
+ ImmutableMap.of(
+ "project",
+ builder -> builder.project(new Schema(TrackedFile.LOCATION)),
+ "select",
+ builder -> builder.select("location"),
+ "case-insensitive select",
+ builder -> builder.select("LOCATION").caseSensitive(false));
+ return FORMATS.stream()
+ .flatMap(
+ format ->
+ modes.entrySet().stream()
+ .map(mode -> Arguments.of(format, mode.getValue(), mode.getKey())));
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testRowFilterForcesRecordCount(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ // record_count is read when evaluating a row filter against file metrics, so it is projected
+ // even though the caller selected only location
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ TrackedFile actual = Iterables.getOnlyElement(reader);
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.recordCount()).isEqualTo(RECORD_COUNT);
+ }
+ }
+
+ @Test
+ public void testProjectionModesAreMutuallyExclusive() {
+ InputFile manifest = fileIO.newInputFile(tempDir.resolve("manifest.avro").toString());
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot select columns using both select(Collection<String>) and project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .select("location"))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use select(Collection<String>) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .select("location")
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .forScanPlanning()
+ .project(new Schema(TrackedFile.LOCATION)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Cannot use project(Schema) with forScanPlanning()");
+
+ assertThatThrownBy(
+ () ->
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS)
+ .project(new Schema(TrackedFile.LOCATION))
+ .forScanPlanning())
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage(
+ "Cannot use forScanPlanning() with select(Collection<String>) or project(Schema)");
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testProjectionPreservesNarrowTrackingProjection(FileFormat format)
+ throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).select("tracking.status").build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ // the narrow tracking projection is not widened to the full tracking type
+ assertThat(actual.snapshotId()).isNull();
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testForScanPlanningOmitsChangeTrackingFields(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).forScanPlanning().build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ // scan-relevant tracking fields are projected
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ // change-tracking fields are omitted from the scan projection
+ assertThat(actual.dvSnapshotId()).isNull();
+ assertThat(actual.deletedPositions()).isNull();
+ assertThat(actual.replacedPositions()).isNull();
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testDefaultReadsFullTracking(FileFormat format) throws IOException {
+ InputFile manifest =
+ writeManifest(format, EMPTY_PARTITION, ImmutableList.of(FILE_WITH_FULL_TRACKING));
+
+ // without scanPlanning, select, or project, the reader returns the full schema for copying to
+ // other manifests, including the change-tracking fields
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, UNPARTITIONED_SPECS).build()) {
+ Tracking actual = Iterables.getOnlyElement(reader).tracking();
+ assertThat(actual.status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.snapshotId()).isEqualTo(SNAPSHOT_ID);
+ assertThat(actual.dataSequenceNumber()).isEqualTo(5L);
+ assertThat(actual.fileSequenceNumber()).isEqualTo(6L);
+ assertThat(actual.firstRowId()).isEqualTo(8L);
+ assertThat(actual.dvSnapshotId()).isEqualTo(7L);
+ assertThat(actual.deletedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {1, 2}));
+ assertThat(actual.replacedPositions()).isEqualTo(ByteBuffer.wrap(new byte[] {3, 4}));
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testPartitionFilterForceProjectsFilterFields(FileFormat format) throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller projects only location; the reader must still project the fields the partition
+ // filter reads (content_type, spec_id, partition) or every row would be pruned
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .project(projection)
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testSelectWithPartitionFilterProjectsFilterFields(FileFormat format)
+ throws IOException {
+ InputFile manifest = writeManifest(format, PARTITION_TYPE, ImmutableList.of(FILE_A, FILE_B));
+
+ // the caller selects only location; the reader must still project spec_id and partition
+ // for the partition filter or every row would be pruned
+ try (V4ManifestReader reader =
+ V4ManifestReader.builder(manifest, PARTITIONED_SPECS)
+ .select("location")
+ .filter(Expressions.equal("id", 1))
+ .build()) {
+ assertThat(reader).extracting(TrackedFile::location).containsExactly(FILE_A.location());
+ }
+ }
+
+ @ParameterizedTest
+ @FieldSource("FORMATS")
+ public void testUnpartitioned(FileFormat format) throws IOException {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(format, EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = Iterables.getOnlyElement(read(manifest, UNPARTITIONED_SPECS));
+ // unpartitioned manifests omit the partition field, which is read as null
+ assertThat(actual.partition()).isNull();
Review Comment:
yes, this is consistent with v2/v3 behavior. Good news is that it doesn't leak into mixed partitions. The reader builds its read schema from the union partition type across all specs in the manifest. The null partition case only occurs when that union is empty. With mixed spes, the union is non empty so even a file with an unpartitioned spec produces a PartitionData over the union type. So there is no special case scenario.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3670127539
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Collection;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.function.Consumer;
+import java.util.stream.Stream;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.inmemory.InMemoryOutputFile;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+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.transforms.Transforms;
+import org.apache.iceberg.types.Comparators;
+import org.apache.iceberg.types.TypeUtil;
+import org.apache.iceberg.types.Types;
+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.Arguments;
+import org.junit.jupiter.params.provider.FieldSource;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+ private static final long RECORD_COUNT = 100L;
+ private static final long FILE_SIZE_IN_BYTES = 1024L;
+ private static final DeletionVector DV =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec ID_PARTITIONING =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = ID_PARTITIONING.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(ID_PARTITIONING.specId(), ID_PARTITIONING);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<FileFormat> FORMATS =
Review Comment:
Renamed.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3482009991
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
Review Comment:
I think I know: `manifestLocation` is the same for all rows within the file, no need to have it per each row.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "stevenzwu (via GitHub)" <gi...@apache.org>.
stevenzwu commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3487472727
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
this name `V4ManifestReader` would be come stale when V5 rolls in. maybe `TrackedFileManifestReader` or just `TrackedFilereader`.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "gaborkaszab (via GitHub)" <gi...@apache.org>.
gaborkaszab commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3497515325
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
Review Comment:
nit: `Invalid row filter: null` instead?
Also, I recall we use `checkArgument` instead of `checkNotNull`
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
+ return this;
+ }
+
+ Builder scanMetrics(ScanMetrics newScanMetrics) {
+ Preconditions.checkNotNull(newScanMetrics, "Scan metrics cannot be null");
Review Comment:
same comments as for `filterRows`
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
Review Comment:
nit: this is rather a TODO not a code comment
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
Review Comment:
Is there anything else needed from tracking? Not exactly sure how much projection gives us, but can't we project TRACKING.STATUS.fieldId() if nothing else is needed?
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
Review Comment:
is the `catch` needed? Can't we cay the test throws `IOException`? Same for other tests
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
+ private final Map<Integer, PartitionSpec> specsById;
+ private Expression rowFilter = Expressions.alwaysTrue();
+ private boolean caseSensitive = true;
+ private Schema fileProjection = null;
+ private ScanMetrics scanMetrics = ScanMetrics.noop();
+
+ private Builder(InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ this.file = file;
+ this.tableSchema = tableSchema;
+ this.specsById = specsById;
+ }
+
+ /** Sets a row filter; files that cannot match the expression are skipped. */
+ Builder filterRows(Expression expr) {
+ Preconditions.checkNotNull(expr, "Row filter cannot be null");
+ this.rowFilter = expr;
+ return this;
+ }
+
+ Builder caseSensitive(boolean isCaseSensitive) {
+ this.caseSensitive = isCaseSensitive;
+ return this;
+ }
+
+ Builder project(Schema newFileProjection) {
+ this.fileProjection = newFileProjection;
Review Comment:
nit: precondition for != null?
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
Review Comment:
Would it make sense to verify a couple of other fields being null because not projected?
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
+ assertThat(actual.partition().size()).isEqualTo(0);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterPrunesNonMatchingFiles() {
+ TrackedFile keep = dataFile("keep.parquet", partition(1));
+ TrackedFile prune = dataFile("prune.parquet", partition(2));
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactly("keep.parquet");
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(1L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterCountsSkippedDeleteFiles() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(100L)
+ .fileSizeInBytes(1024L)
+ .partition(partition(2))
+ .specId(0)
+ .equalityIds(ImmutableList.of(1))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(delete));
+
+ ScanMetrics metrics = ScanMetrics.of(new DefaultMetricsContext());
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS)
+ .filterRows(Expressions.equal("id", 1))
+ .scanMetrics(metrics)
+ .build()) {
+ assertThat(reader.allFiles()).isEmpty();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+
+ assertThat(metrics.skippedDeleteFiles().value()).isEqualTo(1L);
+ assertThat(metrics.skippedDataFiles().value()).isEqualTo(0L);
+ }
+
+ @TestTemplate
+ public void testPartitionFilterKeepsManifestReferences() {
+ TrackedFile keep = dataFile("data-1.parquet", partition(1));
+ TrackedFile prune = dataFile("data-2.parquet", partition(2));
+ ManifestInfo info =
+ ManifestInfoStruct.builder()
+ .addedFilesCount(1)
+ .existingFilesCount(0)
+ .deletedFilesCount(0)
+ .replacedFilesCount(0)
+ .addedRowsCount(1L)
+ .existingRowsCount(0L)
+ .deletedRowsCount(0L)
+ .replacedRowsCount(0L)
+ .minSequenceNumber(1L)
+ .build();
+ TrackedFile manifestRef =
+ TrackedFileBuilder.dataManifest(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("leaf.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(1L)
+ .fileSizeInBytes(100L)
+ .partition(partition(2))
+ .specId(0)
+ .manifestInfo(info)
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(keep, prune, manifestRef));
+
+ try (V4ManifestReader reader =
+ newReader(manifest, PARTITIONED_SPECS).filterRows(Expressions.equal("id", 1)).build()) {
+ assertThat(reader.allFiles())
+ .extracting(TrackedFile::location)
+ .containsExactlyInAnyOrder("data-1.parquet", "leaf.parquet");
Review Comment:
nit: instead of the string literals we could use `location()`
Found this elsewhere too.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
Review Comment:
This class implements and returns a `CloseableIterable<TrackedFile>` so we don't really keep `TrackedFile` internal in my opinion. Following this design we can name this `TrackedFileReader`.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
Review Comment:
Taking a second look, for this probably we should know the contentType beforehand, but it depends on the TrackedFile entry.
Just an idea: would it make sense to introduce a `CloseableIterable.filter(counter, iterable, pred)` version where counter is not a Counter type but "entry -> Counter" function?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
Review Comment:
Can we use the `CloseableIterable.filter(skipCounter, iterable, pred)` method to take care of the counters and the filtering? Like how we do it in `ManifestReader`:
```
CloseableIterable.filter(
content == FileType.DATA_FILES
? scanMetrics.skippedDataFiles()
: scanMetrics.skippedDeleteFiles(),
onlyLive ? filterLiveEntries(entries) : entries,
entry ->
entry != null
&& evaluator.eval(entry.file().partition())
&& metricsEvaluator.eval(entry.file())
&& inPartitionSet(entry.file()));
```
Maybe constructing a predicate for partition filter and use `CloseableIterable.filter`?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
Review Comment:
nit: shorter comment? `Always project tracking for status`
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
Review Comment:
nit: maybe a TODO that ContentStats is not covered now?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
Review Comment:
Trying to wrap my head around this partition filtering: `specId` is null if the file was written when the table was unpartitioned, if Im not mistaken. Do we want to throw an exception here if there are such files and the user provided a `rowFilter`?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field from the read schema, which includes {@code ROW_POSITION} so the
+ * reader populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
+ return Types.NestedField.required(
+ TrackedFile.TRACKING.fieldId(),
+ TrackedFile.TRACKING.name(),
+ TrackingStruct.BASE_TYPE,
+ TrackedFile.TRACKING.doc());
+ }
+
+ static class Builder {
+ private final InputFile file;
+ private final Schema tableSchema;
Review Comment:
`tableSchema` is needed to construct the partitionType if I'm not mistaken. Can we construct it in the constructor of the builder and not keep track of the schema but the partitionType instead?
Or alternatively, can we expect the user to construct that and pass it to the builder?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
Review Comment:
nit: maybe with stream api?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
Review Comment:
nit: maybe `Project spec_id for partition filtering`?
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
Review Comment:
We can still read the partition even if unpartitioned. As we discussed lately, it will be null. I don't think this branch of the `if` is needed.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
Review Comment:
This branch is because temporarily we don't read stats. I'm wondering what it would take to avoid this branch and read the stats even if we don't use them.
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
Review Comment:
this comment is redundant with the one at the beginning of the test. This one should be enough and could be simplified:
`sort_order_id is null because not projected`
##########
core/src/test/java/org/apache/iceberg/TestV4ManifestReader.java:
##########
@@ -0,0 +1,570 @@
+/*
+ * 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.io.UncheckedIOException;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileAppender;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.metrics.DefaultMetricsContext;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.transforms.Transforms;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.TestTemplate;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.io.TempDir;
+
+@ExtendWith(ParameterizedTestExtension.class)
+public class TestV4ManifestReader {
+ private static final long SNAPSHOT_ID = 42L;
+ private static final int FORMAT_VERSION_V4 = 4;
+
+ private static final Schema TABLE_SCHEMA =
+ new Schema(
+ optional(1, "id", Types.IntegerType.get()), optional(2, "data", Types.StringType.get()));
+ private static final PartitionSpec SPEC =
+ PartitionSpec.builderFor(TABLE_SCHEMA).identity("id").build();
+ private static final Types.StructType PARTITION_TYPE = SPEC.partitionType();
+ private static final Types.StructType EMPTY_PARTITION = Types.StructType.of();
+ private static final PartitionData EMPTY_PARTITION_DATA = new PartitionData(EMPTY_PARTITION);
+ private static final Map<Integer, PartitionSpec> PARTITIONED_SPECS =
+ ImmutableMap.of(SPEC.specId(), SPEC);
+ private static final Map<Integer, PartitionSpec> UNPARTITIONED_SPECS =
+ ImmutableMap.of(PartitionSpec.unpartitioned().specId(), PartitionSpec.unpartitioned());
+
+ private static final List<Types.NestedField> SCHEMA_FIELDS =
+ TrackedFile.schemaWithContentStats(Types.StructType.of(), Types.StructType.of()).fields();
+
+ @Parameter private FileFormat format;
+
+ @Parameters(name = "format = {0}")
+ protected static List<FileFormat> parameters() {
+ return Arrays.asList(FileFormat.AVRO, FileFormat.PARQUET);
+ }
+
+ @TempDir private Path tempDir;
+
+ private final FileIO fileIO = new TestTables.LocalFileIO();
+
+ @TestTemplate
+ public void testRoundTrip() {
+ DeletionVector dv =
+ DeletionVectorStruct.builder()
+ .location("s3://bucket/dv.puffin")
+ .offset(100L)
+ .sizeInBytes(50L)
+ .cardinality(5L)
+ .build();
+
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/data/file.parquet", partition(7))
+ .sortOrderId(1)
+ .deletionVector(dv)
+ .keyMetadata(ByteBuffer.wrap(new byte[] {1, 2, 3}))
+ .splitOffsets(ImmutableList.of(50L, 100L))
+ .build();
+
+ InputFile manifest = writeManifest(PARTITION_TYPE, ImmutableList.of(file));
+
+ List<TrackedFile> read = read(manifest, PARTITIONED_SPECS);
+ assertThat(read).hasSize(1);
+ TrackedFile actual = read.get(0);
+
+ assertThat(actual.contentType()).isEqualTo(file.contentType());
+ assertThat(actual.formatVersion()).isEqualTo(file.formatVersion());
+ assertThat(actual.location()).isEqualTo(file.location());
+ assertThat(actual.fileFormat()).isEqualTo(file.fileFormat());
+ assertThat(actual.recordCount()).isEqualTo(file.recordCount());
+ assertThat(actual.fileSizeInBytes()).isEqualTo(file.fileSizeInBytes());
+ assertThat(actual.specId()).isEqualTo(file.specId());
+ assertThat(actual.sortOrderId()).isEqualTo(file.sortOrderId());
+ assertThat(actual.keyMetadata()).isEqualTo(file.keyMetadata());
+ assertThat(actual.splitOffsets()).isEqualTo(file.splitOffsets());
+ assertThat(actual.partition().get(0, Integer.class))
+ .isEqualTo(file.partition().get(0, Integer.class));
+
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(file.tracking().status());
+ assertThat(actual.tracking().snapshotId()).isEqualTo(file.tracking().snapshotId());
+
+ assertThat(actual.deletionVector()).isNotNull();
+ assertThat(actual.deletionVector().location()).isEqualTo(file.deletionVector().location());
+ assertThat(actual.deletionVector().offset()).isEqualTo(file.deletionVector().offset());
+ assertThat(actual.deletionVector().sizeInBytes())
+ .isEqualTo(file.deletionVector().sizeInBytes());
+ assertThat(actual.deletionVector().cardinality())
+ .isEqualTo(file.deletionVector().cardinality());
+ }
+
+ @TestTemplate
+ public void testEqualityDeleteRoundTrip() {
+ TrackedFile delete =
+ TrackedFileBuilder.equalityDelete(SNAPSHOT_ID)
+ .formatVersion(FORMAT_VERSION_V4)
+ .location("s3://bucket/eq-delete.parquet")
+ .fileFormat(FileFormat.PARQUET)
+ .recordCount(10L)
+ .fileSizeInBytes(128L)
+ .partition(EMPTY_PARTITION_DATA)
+ .specId(0)
+ .equalityIds(ImmutableList.of(1, 2))
+ .build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(delete));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.contentType()).isEqualTo(FileContent.EQUALITY_DELETES);
+ assertThat(actual.equalityIds()).containsExactly(1, 2);
+ }
+
+ @TestTemplate
+ public void testLiveFilesExcludesDeletedAndReplaced() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ fileWithStatus(EntryStatus.ADDED, "s3://bucket/added.parquet"),
+ fileWithStatus(EntryStatus.EXISTING, "s3://bucket/existing.parquet"),
+ fileWithStatus(EntryStatus.MODIFIED, "s3://bucket/modified.parquet"),
+ fileWithStatus(EntryStatus.DELETED, "s3://bucket/deleted.parquet"),
+ fileWithStatus(EntryStatus.REPLACED, "s3://bucket/replaced.parquet"));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ try (V4ManifestReader reader = newReader(manifest, UNPARTITIONED_SPECS).build()) {
+ assertThat(reader.allFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(
+ EntryStatus.ADDED,
+ EntryStatus.EXISTING,
+ EntryStatus.MODIFIED,
+ EntryStatus.DELETED,
+ EntryStatus.REPLACED);
+
+ assertThat(reader.liveFiles())
+ .extracting(file -> file.tracking().status())
+ .containsExactly(EntryStatus.ADDED, EntryStatus.EXISTING, EntryStatus.MODIFIED);
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testManifestLocationAndPosition() {
+ List<TrackedFile> files =
+ ImmutableList.of(
+ dataFile("s3://bucket/a.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/b.parquet", EMPTY_PARTITION_DATA),
+ dataFile("s3://bucket/c.parquet", EMPTY_PARTITION_DATA));
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, files);
+
+ List<TrackedFile> read = read(manifest, UNPARTITIONED_SPECS);
+ assertThat(read)
+ .allSatisfy(
+ file -> assertThat(file.tracking().manifestLocation()).isEqualTo(manifest.location()));
+ assertThat(read).extracting(file -> file.tracking().manifestPos()).containsExactly(0L, 1L, 2L);
+ }
+
+ @TestTemplate
+ public void testProjectionRestrictsFields() {
+ // sort_order_id is written but not projected below, so it must not be read back
+ TrackedFile file =
+ dataFileBuilder("s3://bucket/file.parquet", EMPTY_PARTITION_DATA).sortOrderId(7).build();
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ Schema projection = new Schema(TrackedFile.LOCATION);
+ try (V4ManifestReader reader =
+ newReader(manifest, UNPARTITIONED_SPECS).project(projection).build()) {
+ TrackedFile actual = Lists.newArrayList(reader.allFiles()).get(0);
+ assertThat(actual.location()).isEqualTo("s3://bucket/file.parquet");
+ // tracking is always projected even when the caller omits it
+ assertThat(actual.tracking()).isNotNull();
+ assertThat(actual.tracking().status()).isEqualTo(EntryStatus.ADDED);
+ assertThat(actual.tracking().manifestPos()).isEqualTo(0L);
+ // sort_order_id was written but not projected, so it should not be read
+ assertThat(actual.sortOrderId()).isNull();
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ @TestTemplate
+ public void testUnpartitioned() {
+ TrackedFile file = dataFile("s3://bucket/file.parquet", EMPTY_PARTITION_DATA);
+
+ InputFile manifest = writeManifest(EMPTY_PARTITION, ImmutableList.of(file));
+
+ TrackedFile actual = read(manifest, UNPARTITIONED_SPECS).get(0);
+ assertThat(actual.partition()).isNotNull();
Review Comment:
For unpartitioned entry ,the partition should be null, and also spec_id I believe, once [the relevant PR](https://github.com/apache/iceberg/pull/17000) is merged.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
+ // content_stats are omitted for now
+ } else if (field.fieldId() == TrackedFile.PARTITION_ID && unpartitioned) {
+ // unpartitioned manifests omit the partition field
+ } else {
+ fields.add(field);
+ }
+ }
+
+ return new Schema(fields);
+ }
+
+ /**
+ * Builds the tracking field with {@link MetadataColumns#ROW_POSITION} appended so the reader
+ * populates the manifest position of each entry.
+ */
+ private static Types.NestedField trackingWithRowPosition() {
Review Comment:
I think the reason this is still needed is that we use the write schema (`TrackedFile.schemaWithContentStats()`) on the read path and as a result we have to iterate the fields and replace `Tracking to hold 'logical' field(s) too. I'm not sure we have other occasions where we do the same for other types, but seems more complicated than necessary. Can't we simply have a method that produces the read schema for us including logical fields in `Tracking`.
I believe we could then get rid of the whole for loop on fields to replace/omit some of them. It would be as simple as:
```
private Schema readSchema() {
if (fileProjection != null) {
// construct and return a schema using the projection + the mandatory fields
} else {
return someMethodToGetReadSchema();
}
}
```
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,283 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4 manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ Preconditions.checkState(
+ tracking != null,
+ "Invalid tracked file: tracking is required but was missing in manifest %s",
+ file.location());
+
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
Review Comment:
I guess the difficulty here is that for InternalData API we don't have a way to pass the constants map to the underlying reader, right?
Would it worth considering as an improvement? For me both manifestLocation and manifestPos seems regular metadata columns, we just don't have the plumbing currently to make the former act like a metadata column.
I wonder what others say. Probably is an overkill at this point.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org
Re: [PR] Core: Add v4 manifest reader [iceberg]
Posted by "anoopj (via GitHub)" <gi...@apache.org>.
anoopj commented on code in PR #16958:
URL: https://github.com/apache/iceberg/pull/16958#discussion_r3501755532
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
Review Comment:
The intent here is actually to avoid reading stats we don't us. `content_stats` is the heaviest part of a manifest entry, so reading it when nothing consumes it is wasted I/O. That's the same reason v3's ManifestReader drops stats unless a filter needs them. So I'd lean away from reading them unconditionally; the end state is to read content_stats only when projected/needed, not always. This branch is the interim stand-in for that until content-stats reading is implemented.
##########
core/src/main/java/org/apache/iceberg/V4ManifestReader.java:
##########
@@ -0,0 +1,276 @@
+/*
+ * 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.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.io.CloseableGroup;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.CloseableIterator;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.metrics.ScanMetrics;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+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.Types;
+import org.apache.iceberg.util.StructProjection;
+
+/** Reader that reads a v4+ manifest file as {@link TrackedFile}s. */
+class V4ManifestReader extends CloseableGroup implements CloseableIterable<TrackedFile> {
+ private final InputFile file;
+ private final Types.StructType partitionType;
+ private final Schema fileProjection;
+ private final ScanMetrics scanMetrics;
+
+ // partition pruning state, keyed by spec ID; empty when no filtering is required
+ private final Map<Integer, Evaluator> partitionEvaluators;
+ private final Map<Integer, StructProjection> partitionProjections;
+
+ private V4ManifestReader(
+ InputFile file,
+ Types.StructType partitionType,
+ Map<Integer, Evaluator> partitionEvaluators,
+ Map<Integer, StructProjection> partitionProjections,
+ Schema fileProjection,
+ ScanMetrics scanMetrics) {
+ this.file = file;
+ this.partitionType = partitionType;
+ this.partitionEvaluators = partitionEvaluators;
+ this.partitionProjections = partitionProjections;
+ this.fileProjection = fileProjection;
+ this.scanMetrics = scanMetrics;
+ }
+
+ static Builder builder(
+ InputFile file, Schema tableSchema, Map<Integer, PartitionSpec> specsById) {
+ return new Builder(file, tableSchema, specsById);
+ }
+
+ /** Returns all tracked files in this manifest, regardless of status. */
+ CloseableIterable<TrackedFile> allFiles() {
+ return files(false /* all files */);
+ }
+
+ /** Returns tracked files whose tracking {@link Tracking#isLive() is live}. */
+ CloseableIterable<TrackedFile> liveFiles() {
+ return files(true /* only live files */);
+ }
+
+ /** Returns live tracked files, each as an independent copy. */
+ @Override
+ public CloseableIterator<TrackedFile> iterator() {
+ return CloseableIterable.transform(liveFiles(), TrackedFile::copy).iterator();
+ }
+
+ private CloseableIterable<TrackedFile> files(boolean onlyLive) {
+ CloseableIterable<TrackedFile> entries = CloseableIterable.transform(open(), this::prepare);
+ if (!partitionEvaluators.isEmpty()) {
+ entries = CloseableIterable.filter(entries, this::matchesPartition);
+ }
+
+ if (onlyLive) {
+ entries = CloseableIterable.filter(entries, entry -> entry.tracking().isLive());
+ }
+
+ return entries;
+ }
+
+ private boolean matchesPartition(TrackedFile trackedFile) {
+ FileContent content = trackedFile.contentType();
+ if (content == FileContent.DATA_MANIFEST || content == FileContent.DELETE_MANIFEST) {
+ // manifest references are expanded later and are not pruned by the partition filter
+ return true;
+ }
+
+ Integer specId = trackedFile.specId();
+ Evaluator evaluator = specId != null ? partitionEvaluators.get(specId) : null;
+ StructProjection projection = specId != null ? partitionProjections.get(specId) : null;
+ Preconditions.checkState(
+ evaluator != null && projection != null,
+ "Cannot apply partition filter: file %s has spec ID %s, not one of the known specs %s "
+ + "in manifest %s",
+ trackedFile.location(),
+ specId,
+ partitionEvaluators.keySet(),
+ file.location());
+
+ boolean matches = evaluator.eval(projection.wrap(trackedFile.partition()));
+ if (!matches) {
+ if (content == FileContent.DATA) {
+ scanMetrics.skippedDataFiles().increment();
+ } else {
+ scanMetrics.skippedDeleteFiles().increment();
+ }
+ }
+
+ return matches;
+ }
+
+ private CloseableIterable<TrackedFile> open() {
+ FileFormat format = FileFormat.fromFileName(file.location());
+ Preconditions.checkArgument(
+ format != null, "Unable to determine format of manifest: %s", file.location());
+
+ CloseableIterable<TrackedFile> reader =
+ InternalData.read(format, file)
+ .project(readSchema())
+ .setRootType(TrackedFileStruct.class)
+ .setCustomType(TrackedFile.TRACKING.fieldId(), TrackingStruct.class)
+ .setCustomType(TrackedFile.DELETION_VECTOR.fieldId(), DeletionVectorStruct.class)
+ .setCustomType(TrackedFile.MANIFEST_INFO.fieldId(), ManifestInfoStruct.class)
+ .setCustomType(TrackedFile.PARTITION_ID, PartitionData.class)
+ .reuseContainers()
+ .build();
+ addCloseable(reader);
+ return reader;
+ }
+
+ private TrackedFile prepare(TrackedFile trackedFile) {
+ Tracking tracking = trackedFile.tracking();
+ // manifestLocation is not stored in the manifest; the reader fills it from the file location.
+ // manifestPos is filled from ROW_POSITION while reading the tracking struct.
+ if (tracking instanceof TrackingStruct) {
+ ((TrackingStruct) tracking).setManifestLocation(file.location());
+ }
+
+ return trackedFile;
+ }
+
+ private Schema readSchema() {
+ // content_stats is not projected yet, so build the schema with an empty stats type
+ Types.StructType fullType =
+ TrackedFile.schemaWithContentStats(partitionType, Types.StructType.of());
+ boolean unpartitioned = partitionType.fields().isEmpty();
+
+ Set<Integer> projectedIds = null;
+ if (fileProjection != null) {
+ projectedIds = Sets.newHashSet();
+ for (Types.NestedField field : fileProjection.asStruct().fields()) {
+ projectedIds.add(field.fieldId());
+ }
+
+ // tracking carries the status used to filter live files and is always projected
+ projectedIds.add(TrackedFile.TRACKING.fieldId());
+
+ // spec_id is required to resolve each entry's partition spec when pruning
+ if (!partitionEvaluators.isEmpty()) {
+ projectedIds.add(TrackedFile.SPEC_ID.fieldId());
+ }
+ }
+
+ List<Types.NestedField> fields = Lists.newArrayList();
+ for (Types.NestedField field : fullType.fields()) {
+ if (projectedIds != null && !projectedIds.contains(field.fieldId())) {
+ continue;
+ }
+
+ if (field.fieldId() == TrackedFile.TRACKING.fieldId()) {
+ fields.add(trackingWithRowPosition());
+ } else if (field.fieldId() == TrackedFile.CONTENT_STATS_ID) {
Review Comment:
The intent here is actually to avoid reading stats we don't use. `content_stats` is the heaviest part of a manifest entry, so reading it when nothing consumes it is wasted I/O. That's the same reason v3's ManifestReader drops stats unless a filter needs them. So I'd lean away from reading them unconditionally; the end state is to read content_stats only when projected/needed, not always. This branch is the interim stand-in for that until content-stats reading is implemented.
--
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: issues-unsubscribe@iceberg.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org