hello-stephen commented on code in PR #71365: URL: https://github.com/apache/doris/pull/71365#discussion_r4794165058
########## fe/fe-iceberg-common/src/main/java/org/apache/doris/connector/iceberg/IcebergMvPartitionSnapshot.java: ########## @@ -0,0 +1,297 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.iceberg; + +import org.apache.iceberg.ContentFile; +import org.apache.iceberg.ManifestContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.PartitionField; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.CloseableIterator; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types.NestedField; + +import java.io.IOException; +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Snapshot-bound partition compatibility shared by Iceberg MV adapters. Call under the catalog's IO context. */ +public final class IcebergMvPartitionSnapshot { + private final boolean supported; + private final String unsupportedReason; + private final Type sourceType; + private final long snapshotId; + private final long updateTimeMicros; + private final List<Partition> partitions; + + private IcebergMvPartitionSnapshot(boolean supported, String unsupportedReason, Type sourceType, + long snapshotId, long updateTimeMicros, List<Partition> partitions) { + this.supported = supported; + this.unsupportedReason = unsupportedReason; + this.sourceType = sourceType; + this.snapshotId = snapshotId; + this.updateTimeMicros = updateTimeMicros; + this.partitions = Collections.unmodifiableList(partitions); + } + + /** Preserve the existing fine-grained freshness path for tables supported before partition evolution. */ + public static boolean supportsAllSpecs(Table table) { + Integer sourceId = null; + for (PartitionSpec spec : table.specs().values()) { + if (!supportsSpec(table, spec, false)) { + return false; + } + int id = spec.fields().get(0).sourceId(); + if (sourceId != null && sourceId != id) { + return false; + } + sourceId = id; + } + return sourceId != null; + } + + public static boolean qualifies(Table table, long snapshotId) { + return scan(table, snapshotId, false).isSupported(); + } + + public static IcebergMvPartitionSnapshot load(Table table, long snapshotId) { + return scan(table, snapshotId, true); + } + + private static IcebergMvPartitionSnapshot scan(Table table, long pinnedSnapshotId, boolean collectPartitions) { + PartitionSpec defaultSpec = table.spec(); + if (!supportsSpec(table, defaultSpec, true)) { + return unsupported("Unsupported default partition spec " + defaultSpec.specId()); + } + int sourceId = defaultSpec.fields().get(0).sourceId(); + // MV keys bind top-level columns through a comma-separated name contract. Nested leaves and + // names altered by splitting/trimming must not bind another column with a matching name. + NestedField source = table.schema().asStruct().field(sourceId); + if (source == null || source.name().contains(",") || !source.name().equals(source.name().trim())) { + return unsupported("Partition source cannot be bound to one top-level MV column"); + } + // An existing MV remains bound to its original source column across later partition evolution. + // Dropping all old files must not silently allow changing that source to a different field ID. + for (PartitionSpec spec : table.specs().values()) { + for (PartitionField field : spec.fields()) { + if (field.sourceId() != sourceId) { + return unsupported("Partition source changed in spec " + spec.specId()); + } + } + } + Type sourceType = table.schema().findType(sourceId); + Snapshot snapshot = pinnedSnapshotId >= 0 ? table.snapshot(pinnedSnapshotId) : table.currentSnapshot(); + if (snapshot == null) { + if (pinnedSnapshotId >= 0) { + throw new IllegalArgumentException("Cannot find Iceberg snapshot " + pinnedSnapshotId); + } + return new IcebergMvPartitionSnapshot(true, "", sourceType, -1, 0, Collections.emptyList()); + } + Map<String, Partition> partitions = new LinkedHashMap<>(); + for (ManifestFile manifest : snapshot.allManifests(table.io())) { + // Retained manifests can contain only deleted entries. Unknown counts are not proof of emptiness. + if (!manifest.hasAddedFiles() && !manifest.hasExistingFiles()) { + continue; + } + PartitionSpec spec = table.specs().get(manifest.partitionSpecId()); + boolean supportedSpec = supportsSpec(table, spec, true); + if (!collectPartitions && supportedSpec) { + continue; + } + try (ManifestReader<?> reader = manifest.content() == ManifestContent.DATA Review Comment: [P3] Qualify incompatible specs before collecting partition tuples With a current `day(event_date)` spec and older unpartitioned files still live, the manifest list can present many supported manifests before the first incompatible one. This loop decodes the supported entries and discards their tuples on rejection. On a cold or disabled cache, the FE's LIST fallback then scans PARTITIONS for the same snapshot. Check the live entries of potentially incompatible manifests first so the unsupported result reaches the fallback without the extra walk. ########## fe/fe-iceberg-common/src/main/java/org/apache/doris/connector/iceberg/IcebergMvPartitionSnapshot.java: ########## @@ -0,0 +1,297 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.iceberg; + +import org.apache.iceberg.ContentFile; +import org.apache.iceberg.ManifestContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.PartitionField; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.CloseableIterator; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types.NestedField; + +import java.io.IOException; +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Snapshot-bound partition compatibility shared by Iceberg MV adapters. Call under the catalog's IO context. */ +public final class IcebergMvPartitionSnapshot { + private final boolean supported; + private final String unsupportedReason; + private final Type sourceType; + private final long snapshotId; + private final long updateTimeMicros; + private final List<Partition> partitions; + + private IcebergMvPartitionSnapshot(boolean supported, String unsupportedReason, Type sourceType, + long snapshotId, long updateTimeMicros, List<Partition> partitions) { + this.supported = supported; + this.unsupportedReason = unsupportedReason; + this.sourceType = sourceType; + this.snapshotId = snapshotId; + this.updateTimeMicros = updateTimeMicros; + this.partitions = Collections.unmodifiableList(partitions); + } + + /** Preserve the existing fine-grained freshness path for tables supported before partition evolution. */ + public static boolean supportsAllSpecs(Table table) { + Integer sourceId = null; + for (PartitionSpec spec : table.specs().values()) { + if (!supportsSpec(table, spec, false)) { + return false; + } + int id = spec.fields().get(0).sourceId(); + if (sourceId != null && sourceId != id) { + return false; + } + sourceId = id; + } + return sourceId != null; + } + + public static boolean qualifies(Table table, long snapshotId) { + return scan(table, snapshotId, false).isSupported(); + } + + public static IcebergMvPartitionSnapshot load(Table table, long snapshotId) { + return scan(table, snapshotId, true); + } + + private static IcebergMvPartitionSnapshot scan(Table table, long pinnedSnapshotId, boolean collectPartitions) { + PartitionSpec defaultSpec = table.spec(); + if (!supportsSpec(table, defaultSpec, true)) { + return unsupported("Unsupported default partition spec " + defaultSpec.specId()); + } + int sourceId = defaultSpec.fields().get(0).sourceId(); + // MV keys bind top-level columns through a comma-separated name contract. Nested leaves and + // names altered by splitting/trimming must not bind another column with a matching name. + NestedField source = table.schema().asStruct().field(sourceId); + if (source == null || source.name().contains(",") || !source.name().equals(source.name().trim())) { + return unsupported("Partition source cannot be bound to one top-level MV column"); + } + // An existing MV remains bound to its original source column across later partition evolution. + // Dropping all old files must not silently allow changing that source to a different field ID. + for (PartitionSpec spec : table.specs().values()) { + for (PartitionField field : spec.fields()) { + if (field.sourceId() != sourceId) { + return unsupported("Partition source changed in spec " + spec.specId()); + } + } + } + Type sourceType = table.schema().findType(sourceId); + Snapshot snapshot = pinnedSnapshotId >= 0 ? table.snapshot(pinnedSnapshotId) : table.currentSnapshot(); + if (snapshot == null) { + if (pinnedSnapshotId >= 0) { + throw new IllegalArgumentException("Cannot find Iceberg snapshot " + pinnedSnapshotId); + } + return new IcebergMvPartitionSnapshot(true, "", sourceType, -1, 0, Collections.emptyList()); + } + Map<String, Partition> partitions = new LinkedHashMap<>(); + for (ManifestFile manifest : snapshot.allManifests(table.io())) { + // Retained manifests can contain only deleted entries. Unknown counts are not proof of emptiness. + if (!manifest.hasAddedFiles() && !manifest.hasExistingFiles()) { + continue; + } + PartitionSpec spec = table.specs().get(manifest.partitionSpecId()); + boolean supportedSpec = supportsSpec(table, spec, true); + if (!collectPartitions && supportedSpec) { + continue; + } + try (ManifestReader<?> reader = manifest.content() == ManifestContent.DATA + ? ManifestFiles.read(manifest, table.io(), table.specs()) + : ManifestFiles.readDeleteManifest(manifest, table.io(), table.specs())) { + reader.select(Collections.singletonList("partition")); + try (CloseableIterator<? extends ContentFile<?>> files = reader.iterator()) { + while (files.hasNext()) { + ContentFile<?> file = files.next(); + if (!supportedSpec) { + return unsupported("Live files use unsupported partition spec " + + manifest.partitionSpecId()); + } + PartitionField field = spec.fields().get(0); + Object value = file.partition().get(0, spec.javaClasses()[0]); + String text = value == null ? null : value.toString(); + // PARTITIONS aggregates identical tuples across specs, hiding some live spec IDs (NULL + // is a common example). Keep each spec/tuple until the adapter merges equivalent ranges. + // Legacy time-transform names end in an integer or null. The suffix keeps the modes + // distinct even with user-named fields, forcing refresh if spec cleanup changes the mode. + String name = "spec_" + spec.specId() + "/" + field.name() + "=" + text + "#mv"; + if (!partitions.containsKey(name)) { + if (!hasRepresentableRange(text, field.transform().toString(), Review Comment: [P2] Guard year-zero partition ordinals written before the upgrade Create an empty unpartitioned Iceberg table, add `hour(ts)`, and insert `0000-01-01 12:00:00` with the old Doris writer. The manifest records January 2 noon because the old transform used Doris day numbering, while the Parquet payload records January 1 noon using the Gregorian calendar. This check accepts the persisted January 2 tuple, and a complete refresh applies a January 2 predicate to the January 1 row. The new writer fixes future inserts. Validate affected old tuples against trustworthy file metadata or keep them ineligible until the files are rewritten. Add coverage using a pre-upgrade file and manifest. ########## fe/fe-iceberg-common/src/main/java/org/apache/doris/connector/iceberg/IcebergMvPartitionSnapshot.java: ########## @@ -0,0 +1,297 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package org.apache.doris.connector.iceberg; + +import org.apache.iceberg.ContentFile; +import org.apache.iceberg.ManifestContent; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.ManifestFiles; +import org.apache.iceberg.ManifestReader; +import org.apache.iceberg.PartitionField; +import org.apache.iceberg.PartitionSpec; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.CloseableIterator; +import org.apache.iceberg.types.Type; +import org.apache.iceberg.types.Types.NestedField; + +import java.io.IOException; +import java.time.DateTimeException; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Snapshot-bound partition compatibility shared by Iceberg MV adapters. Call under the catalog's IO context. */ +public final class IcebergMvPartitionSnapshot { + private final boolean supported; + private final String unsupportedReason; + private final Type sourceType; + private final long snapshotId; + private final long updateTimeMicros; + private final List<Partition> partitions; + + private IcebergMvPartitionSnapshot(boolean supported, String unsupportedReason, Type sourceType, + long snapshotId, long updateTimeMicros, List<Partition> partitions) { + this.supported = supported; + this.unsupportedReason = unsupportedReason; + this.sourceType = sourceType; + this.snapshotId = snapshotId; + this.updateTimeMicros = updateTimeMicros; + this.partitions = Collections.unmodifiableList(partitions); + } + + /** Preserve the existing fine-grained freshness path for tables supported before partition evolution. */ + public static boolean supportsAllSpecs(Table table) { + Integer sourceId = null; + for (PartitionSpec spec : table.specs().values()) { + if (!supportsSpec(table, spec, false)) { + return false; + } + int id = spec.fields().get(0).sourceId(); + if (sourceId != null && sourceId != id) { + return false; + } + sourceId = id; + } + return sourceId != null; + } + + public static boolean qualifies(Table table, long snapshotId) { + return scan(table, snapshotId, false).isSupported(); + } + + public static IcebergMvPartitionSnapshot load(Table table, long snapshotId) { + return scan(table, snapshotId, true); + } + + private static IcebergMvPartitionSnapshot scan(Table table, long pinnedSnapshotId, boolean collectPartitions) { + PartitionSpec defaultSpec = table.spec(); + if (!supportsSpec(table, defaultSpec, true)) { + return unsupported("Unsupported default partition spec " + defaultSpec.specId()); + } + int sourceId = defaultSpec.fields().get(0).sourceId(); + // MV keys bind top-level columns through a comma-separated name contract. Nested leaves and + // names altered by splitting/trimming must not bind another column with a matching name. + NestedField source = table.schema().asStruct().field(sourceId); + if (source == null || source.name().contains(",") || !source.name().equals(source.name().trim())) { + return unsupported("Partition source cannot be bound to one top-level MV column"); + } + // An existing MV remains bound to its original source column across later partition evolution. + // Dropping all old files must not silently allow changing that source to a different field ID. + for (PartitionSpec spec : table.specs().values()) { + for (PartitionField field : spec.fields()) { + if (field.sourceId() != sourceId) { + return unsupported("Partition source changed in spec " + spec.specId()); + } + } + } + Type sourceType = table.schema().findType(sourceId); + Snapshot snapshot = pinnedSnapshotId >= 0 ? table.snapshot(pinnedSnapshotId) : table.currentSnapshot(); + if (snapshot == null) { + if (pinnedSnapshotId >= 0) { + throw new IllegalArgumentException("Cannot find Iceberg snapshot " + pinnedSnapshotId); + } + return new IcebergMvPartitionSnapshot(true, "", sourceType, -1, 0, Collections.emptyList()); + } + Map<String, Partition> partitions = new LinkedHashMap<>(); + for (ManifestFile manifest : snapshot.allManifests(table.io())) { + // Retained manifests can contain only deleted entries. Unknown counts are not proof of emptiness. + if (!manifest.hasAddedFiles() && !manifest.hasExistingFiles()) { + continue; + } + PartitionSpec spec = table.specs().get(manifest.partitionSpecId()); + boolean supportedSpec = supportsSpec(table, spec, true); + if (!collectPartitions && supportedSpec) { + continue; + } + try (ManifestReader<?> reader = manifest.content() == ManifestContent.DATA + ? ManifestFiles.read(manifest, table.io(), table.specs()) + : ManifestFiles.readDeleteManifest(manifest, table.io(), table.specs())) { + reader.select(Collections.singletonList("partition")); + try (CloseableIterator<? extends ContentFile<?>> files = reader.iterator()) { + while (files.hasNext()) { + ContentFile<?> file = files.next(); + if (!supportedSpec) { + return unsupported("Live files use unsupported partition spec " + + manifest.partitionSpecId()); + } + PartitionField field = spec.fields().get(0); + Object value = file.partition().get(0, spec.javaClasses()[0]); + String text = value == null ? null : value.toString(); + // PARTITIONS aggregates identical tuples across specs, hiding some live spec IDs (NULL + // is a common example). Keep each spec/tuple until the adapter merges equivalent ranges. + // Legacy time-transform names end in an integer or null. The suffix keeps the modes + // distinct even with user-named fields, forcing refresh if spec cleanup changes the mode. + String name = "spec_" + spec.specId() + "/" + field.name() + "=" + text + "#mv"; + if (!partitions.containsKey(name)) { + if (!hasRepresentableRange(text, field.transform().toString(), + sourceType.typeId() == Type.TypeID.DATE)) { + return unsupported("Partition range is outside the safe Doris temporal domain"); + } + partitions.put(name, new Partition(name, spec.specId(), text, + field.transform().toString())); + } + } + } + } catch (IOException e) { + // A partial partition map must never be published as a complete, fresh MV view. + throw new RuntimeIOException(e, "Cannot read Iceberg MV partitions at snapshot %s", + snapshot.snapshotId()); + } + } + return new IcebergMvPartitionSnapshot(true, "", sourceType, snapshot.snapshotId(), + snapshot.timestampMillis() * 1000, new ArrayList<>(partitions.values())); + } + + /** Whether both closed-open endpoints can be expressed as Doris temporal partition keys. */ + public static boolean hasRepresentableRange(String value, String transform) { + return hasRepresentableRange(value, transform, false); + } + + private static boolean hasRepresentableRange(String value, String transform, boolean dateSource) { + if (value == null) { + return true; + } + try { + long ordinal = Long.parseLong(value); + LocalDateTime epoch = LocalDateTime.of(1970, 1, 1, 0, 0); + LocalDateTime lower; + LocalDateTime upper; + switch (transform) { + case "hour": + lower = epoch.plusHours(ordinal); + upper = lower.plusHours(1); + break; + case "identity": + case "day": + lower = epoch.plusDays(ordinal); + upper = lower.plusDays(1); + break; + case "month": + lower = epoch.plusMonths(ordinal); + upper = lower.plusMonths(1); + break; + case "year": + lower = epoch.plusYears(ordinal); + upper = lower.plusYears(1); + break; + default: + return false; + } + // DATE codecs differ across supported engine versions before March of year 0. A file's + // metrics/partition may then describe a different day (or January's last day as February). + // Keep these newly admitted fine-grained DATE ranges out of MV tracking on both branches. + if (dateSource && lower.getYear() == 0 && lower.getMonthValue() <= 2 + && !"year".equals(transform)) { + return false; + } + // Java/Iceberg include 0000-02-29, but Doris rejects it even as an exclusive endpoint. + // Only the domain's final exclusive boundary can be represented by MAXVALUE. + return isDorisDate(lower) && (isDorisDate(upper) Review Comment: [P2] Account for timestamps that decode to NULL inside valid ranges After evolving an empty unpartitioned table to `month(ts)`, add an externally written nullable Parquet timestamp at Gregorian `0000-02-29`. Both February range endpoints pass this check. A permissive scan decodes that timestamp as NULL, as covered by `NullableYearZeroLeapDayBecomesNullInPermissiveMode`. Complete refresh applies `ts >= '0000-02-01' AND ts < '0000-03-01'` to the decoded row and drops it. Reject ranges that can contain this value unless file metadata proves it is absent, or account for the converted NULL when assigning MV 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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
