hello-stephen commented on code in PR #71373:
URL: https://github.com/apache/doris/pull/71373#discussion_r4794226552
##########
fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java:
##########
@@ -2345,13 +2338,29 @@ static IcebergPartitionInfo
loadPartitionInfo(ExternalTable dorisTable, Table ta
static IcebergPartitionInfo loadPartitionInfo(String displayName, Table
table,
long snapshotId, long schemaId, ExecutionAuthenticator
authenticator,
boolean enableMappingVarbinary, boolean enableMappingTimestampTz)
throws AnalysisException {
- if (snapshotId == IcebergUtils.UNKNOWN_SNAPSHOT_ID) {
- return IcebergPartitionInfo.empty();
+ if (snapshotId == IcebergUtils.UNKNOWN_SNAPSHOT_ID &&
isLegacySupportedRelatedTable(table)) {
+ return new IcebergPartitionInfo(Collections.emptyMap(),
Collections.emptyMap(), Collections.emptyMap());
}
List<IcebergPartition> icebergPartitions;
List<Column> partitionColumns;
try {
- icebergPartitions = authenticator.execute(() ->
loadIcebergPartition(table, snapshotId));
+ if (IcebergMvPartitionSnapshot.supportsAllSpecs(table)) {
Review Comment:
[P2] Reject nested partition sources before building legacy MV ranges
A partitioned MV over `OLAP o JOIN HMS Iceberg i ON o.id = i.id` can be
partitioned by `o.d` while Iceberg uses `day(payload.ts)` on a nested
timestamp. CREATE asks for the partition type of both inputs before checking
which relation owns the MV partition column. This legacy branch accepts the
single temporal spec and skips the fallback’s top-level source check. The
schema builder resolves zero top-level partition columns, then
`getPartitionRange` indexes that empty list and aborts CREATE even though only
OLAP needs partition tracking. Apply the source-binding check before building
legacy ranges, or skip eligibility for relations outside PCT.
##########
fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergSnapshotCacheValue.java:
##########
@@ -140,6 +142,16 @@ private IcebergSnapshotCacheValue(IcebergPartitionInfo
partitionInfo, IcebergSna
}
}
+ public boolean isValidRelatedTable() {
+ // Spec compatibility alone cannot admit bounds outside the engine
calendar.
+ return getPartitionInfo().isValidRelatedTable();
Review Comment:
[P2] Reuse the pinned Iceberg partition view during CREATE
With `meta.cache.iceberg.partition.enable=false` or a view too large for the
cache, CREATE of a partitioned MV over an evolved HMS Iceberg table can
enumerate all live manifests four times against one snapshot.
`PartitionIncrementMaintainer`, `MTMVPartitionDefinition` and `CreateMTMVInfo`
each ask for the partition type, and the descriptor generator also loads the
partition items. Each call reaches the same uncached supplier. Materialize the
view once on the CREATE statement’s pin and use it for eligibility and
descriptor generation.
##########
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
Review Comment:
[P2] Check retained timestamp ordinals from older writers
Create an unpartitioned Iceberg table, add `hour(ts)` before writing any
files, and insert `0000-01-01 12:00:00` with the release-base BE. Its partition
transform records January 2 at noon because Doris day numbering omits the
Gregorian leap day in year zero. The Parquet payload still contains January 1
at noon. After upgrade, the fallback accepts the retained hourly ordinal
through this DATE-only check. The MV refresh injects the January 2 bounds and
omits the row even on COMPLETE. Verify that day/hour labels agree with the
file’s timestamp domain before admitting those files for PCT, and cover
retained old-writer files.
##########
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)
+ || upper.equals(LocalDateTime.of(10000, 1, 1, 0, 0)));
+ } catch (DateTimeException | ArithmeticException e) {
+ return false;
+ }
+ }
+
+ private static boolean isDorisDate(LocalDateTime value) {
+ return value.getYear() >= 0 && value.getYear() <= 9999
+ && !(value.getYear() == 0 && value.getMonthValue() == 2 &&
value.getDayOfMonth() == 29);
+ }
+
+ private static boolean supportsSpec(Table table, PartitionSpec spec,
boolean allowDateIdentity) {
+ if (spec == null || spec.fields().size() != 1) {
+ return false;
+ }
+ PartitionField field = spec.fields().get(0);
+ Type type = spec.schema().findType(field.sourceId());
+ if (type == null ||
!type.equals(table.schema().findType(field.sourceId()))) {
+ return false;
+ }
+ String transform = field.transform().toString();
+ if (allowDateIdentity && "identity".equals(transform) && type.typeId()
== Type.TypeID.DATE) {
Review Comment:
[P1] Fence DATE identity PCT during mixed-FE upgrades
A new leader can build a partitioned MV over `OLAP o INNER JOIN HMS Iceberg
i ON o.d = i.d` with OLAP ranges A and B and DATE-identity Iceberg rows only in
B. After an Iceberg append to A and `REFRESH TABLE`, a readable older FE can
replay the MV and plan an A-filtered query before the next MV refresh. Its
Iceberg cache never builds a partition map for identity. The old freshness
check sees empty current and saved Iceberg names for A, skips the
table-snapshot comparison for that PCT input, and can rewrite to the MV and
omit the new join row. Gate the new PCT layouts on compatible query-serving FEs
or ensure older planners reject these MVs.
--
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]