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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions core/src/main/java/org/apache/iceberg/Partitioning.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment thread
anoopj marked this conversation as resolved.
* @return the constructed unified partition type
*/
static StructType unionPartitionTypes(Collection<PartitionSpec> specs) {
return buildPartitionProjectionType("table partition", specs, allFieldIds(specs));
}

/**
* Checks if any of the specs in a table is partitioned.
*
Expand Down Expand Up @@ -347,6 +358,14 @@ private static boolean compatibleTransforms(Transform<?, ?> t1, Transform<?, ?>
|| t2.equals(Transforms.alwaysNull());
}

// collects IDs of all partition fields used across specs
private static Set<Integer> allFieldIds(Collection<PartitionSpec> specs) {
return FluentIterable.from(specs)
.transformAndConcat(PartitionSpec::fields)
.transform(PartitionField::fieldId)
.toSet();
}

// collects IDs of all partition field used across specs that are in the current schema
private static Set<Integer> allActiveFieldIds(Schema schema, Collection<PartitionSpec> specs) {
return FluentIterable.from(specs)
Expand Down
21 changes: 18 additions & 3 deletions core/src/main/java/org/apache/iceberg/TrackedFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.iceberg.types.Type;
import org.apache.iceberg.types.Types;

/** A file tracked by a manifest. */
Expand Down Expand Up @@ -95,7 +96,13 @@ 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 Types.StructType.of(
TRACKING,
Expand All @@ -106,9 +113,13 @@ static Types.StructType schemaWithContentStats(
RECORD_COUNT,
FILE_SIZE_IN_BYTES,
SPEC_ID,
Types.NestedField.optional(PARTITION_ID, PARTITION_NAME, partitionType, PARTITION_DOC),
Types.NestedField.optional(
CONTENT_STATS_ID, CONTENT_STATS_NAME, contentStatsType, CONTENT_STATS_DOC),
PARTITION_ID, PARTITION_NAME, typeOrUnknown(partitionType), PARTITION_DOC),
Types.NestedField.optional(
CONTENT_STATS_ID,
CONTENT_STATS_NAME,
typeOrUnknown(contentStatsType),
CONTENT_STATS_DOC),
SORT_ORDER_ID,
DELETION_VECTOR,
MANIFEST_INFO,
Expand All @@ -117,6 +128,10 @@ static Types.StructType schemaWithContentStats(
EQUALITY_IDS);
}

private static Type typeOrUnknown(Types.StructType structType) {
return structType.fields().isEmpty() ? Types.UnknownType.get() : structType;
}

/** Returns the tracking information for this entry. */
Tracking tracking();

Expand Down
7 changes: 4 additions & 3 deletions core/src/main/java/org/apache/iceberg/TrackedFileStruct.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,11 @@ class TrackedFileStruct extends SupportsIndexProjection implements TrackedFile,
/** Used by internal readers to instantiate this class with a projection schema. */
TrackedFileStruct(Types.StructType projection) {
super(BASE_TYPE, projection);
// partition type may be null if the field was not projected
// partition type may be null if the field was not projected, or unknown for unpartitioned
// manifests
Type partType = projection.fieldType("partition");
if (partType != null) {
this.partitionData = new PartitionData(partType.asNestedType().asStructType());
if (partType != null && partType.isStructType()) {
this.partitionData = new PartitionData(partType.asStructType());
}
}

Expand Down
272 changes: 272 additions & 0 deletions core/src/main/java/org/apache/iceberg/V4ManifestReader.java
Original file line number Diff line number Diff line change
@@ -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> {

@stevenzwu stevenzwu Jun 28, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this name V4ManifestReader would become stale when V5 rolls in. maybe TrackedFileManifestReader or just TrackedFileReader.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is actually a good point. Leaving it open to hear from others.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TrackedFile is internal in the sense that it is not a public interface (at least not yet). This class TrackedFileReader would probably only be package private.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a good point, but I don't have a name suggestion that is better right now. Let's keep it in mind.

// tracking fields read on the scan path; row_position backs Tracking.manifestPos
private static final Types.StructType SCAN_TRACKING =

@stevenzwu stevenzwu Jul 16, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

/** 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.

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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The specID is a required field, so it should not be null. Even unpartitioned data has a spec (the unpartitioned spec).

Also, any spec that exists within the table metadata is valid and can be written to directly (it isn't limited to older data written and then spec being evolved).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

specId must be null for leaf manifest entry in the root manifest file, as a leaf manifest file can contain data file entries with mixed spec. It doesn't make sense to populate a single specId. Leaf manifest file entry should only have partition_summary field populated.

Hence the evaluation and preconditions check seem to only apply to data file entries in a leaf manifest file.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I hope #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

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() {
Comment thread
stevenzwu marked this conversation as resolved.
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe a TODO that ContentStats is not covered now?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally we don't add many TODOs in the code (I got past feedback on this).

@rdblue rdblue Jul 8, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, not for things that are currently being worked on. The TODO should not catch anything. Tests should catch when something is missing.

.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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

manifestLocation might be able to be populated via constant map. But we didn't populate the manifestPos field, which may have to be populated via a setter method in this reader.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think that we should worry much about this right now. I think @gaborkaszab is right that this should be set by the readers, but we don't have that done yet so we have left setManifestLocation in place.

This and inheritance are going to change a bit, but we need the basic structure in place before we can do that.

}

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: precondition for != null?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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() {

@stevenzwu stevenzwu Jul 16, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

// 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:

Set<Integer> projectedIds = Sets.newHashSet(TypeUtil.getProjectedIds(fileProjection));

Pairs with the Tracking.scanSchema() suggestion above. readSchema() collapses to:

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);
}

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);
}
}
}
19 changes: 19 additions & 0 deletions core/src/test/java/org/apache/iceberg/TestPartitioning.java
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,25 @@ public void testPartitionTypeIgnoreInactiveFields() {
assertThat(actualType).isEqualTo(StructType.of());
}

@Test
public void testUnionPartitionTypesRetainsDroppedSourceFields() {
TestTables.TestTable table =
TestTables.create(
tableDir, "test", SCHEMA, BY_DATA_CATEGORY_BUCKET_SPEC, V2_FORMAT_VERSION);

table.updateSpec().removeField("category_bucket").commit();
table.updateSchema().deleteColumn("category").commit();

// fields with dropped source columns are retained to preserve partition tuple equality;
// their type is unknown because it cannot be determined without the source column
StructType actualType = Partitioning.unionPartitionTypes(table.specs().values());
assertThat(actualType)
.isEqualTo(
StructType.of(
NestedField.optional(1000, "data", Types.StringType.get()),
NestedField.optional(1001, "category_bucket", Types.UnknownType.get())));
}

@Test
public void testGroupingKeyTypeWithSpecEvolutionInV1Tables() {
TestTables.TestTable table =
Expand Down
Loading
Loading