hello-stephen commented on code in PR #71373:
URL: https://github.com/apache/doris/pull/71373#discussion_r4786578093


##########
fe/fe-iceberg-common/src/main/java/org/apache/doris/connector/iceberg/IcebergMvPartitionSnapshot.java:
##########
@@ -0,0 +1,233 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 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.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";
+                        partitions.putIfAbsent(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()));
+    }
+
+    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) {
+            return true;
+        }
+        return (type.typeId() == Type.TypeID.DATE || type.typeId() == 
Type.TypeID.TIMESTAMP)
+                && ("year".equals(transform) || "month".equals(transform)
+                        || "day".equals(transform) || 
"hour".equals(transform));
+    }
+
+    private static IcebergMvPartitionSnapshot unsupported(String reason) {
+        return new IcebergMvPartitionSnapshot(false, reason, null, -1, 0, 
Collections.emptyList());
+    }
+
+    public boolean isSupported() {
+        return supported;
+    }
+
+    public String getUnsupportedReason() {
+        return unsupportedReason;
+    }
+
+    public Type getSourceType() {
+        return sourceType;
+    }
+
+    public long getSnapshotId() {
+        return snapshotId;
+    }
+
+    public long getUpdateTimeMicros() {
+        return updateTimeMicros;
+    }
+
+    public List<Partition> getPartitions() {
+        return partitions;
+    }
+
+    public static final class Partition {
+        private final String name;
+        private final int specId;
+        private final String value;
+        private final String transform;
+
+        private Partition(String name, int specId, String value, String 
transform) {
+            this.name = name;
+            this.specId = specId;
+            this.value = value;
+            this.transform = transform;
+        }
+
+        public String getName() {
+            return name;
+        }
+
+        public int getSpecId() {
+            return specId;
+        }
+
+        public String getValue() {
+            return value;
+        }
+
+        public String getRangeTransform() {
+            // Iceberg identity(DATE) and day(DATE) both contain epoch-day 
integers, including NULL.
+            return "identity".equals(transform) ? "day" : transform;

Review Comment:
   [P2] Handle the last representable DATE in identity partitions
   
   The new identity DATE path accepts a partition containing `9999-12-31`, then 
treats it as a day bucket. `IcebergUtils.getPartitionRange` adds one day for 
the exclusive upper bound, producing `+10000-01-01`, which Doris rejects when 
creating the partition key. CREATE or refresh of a partitioned MV then fails 
even though the source DATE is valid. Represent the exclusive end with 
`MAXVALUE` when it falls beyond the last representable date, and cover 
`9999-12-31` in the identity evolution tests.



##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java:
##########
@@ -580,6 +584,7 @@ private void beforeMTMVRefresh() throws AnalysisException, 
DdlException {
             if (tableIf instanceof MvccTable) {
                 MvccTable mvccTable = (MvccTable) tableIf;
                 MvccSnapshot mvccSnapshot = 
mvccTable.loadSnapshot(Optional.empty(), Optional.empty());
+                mvccSnapshot = 
mvccTable.materializePartitionViewForMtmv(mvccSnapshot);

Review Comment:
   [P2] Materialize partition views only for PCT inputs
   
   This runs for every Iceberg dependency, including a complete-refresh MV 
without `PARTITION BY` and a non-PCT Iceberg dimension in a partitioned MV. 
Those paths use `getTableSnapshot()` for freshness. With an HMS Iceberg input 
they can otherwise plan the scan without building this range map. On a 
partition-cache miss, this now reads and retains the full partition view and 
can abort the refresh on a partition-only error. Keep pinning every base 
snapshot and limit materialization to the tables participating in partition 
change tracking.



##########
fe/fe-core/src/main/java/org/apache/doris/job/extensions/mtmv/MTMVTask.java:
##########
@@ -223,7 +223,11 @@ public void run() throws JobException {
                 if (mtmv.getMvPartitionInfo().getPartitionType() != 
MTMVPartitionType.SELF_MANAGE) {
                     Set<MTMVRelatedTableIf> pctTables = 
mtmv.getMvPartitionInfo().getPctTables();
                     for (MTMVRelatedTableIf pctTable : pctTables) {
-                        if (!pctTable.isValidRelatedTable()) {
+                        Optional<MvccSnapshot> snapshot = pctTable instanceof 
MvccTable
+                                ? Optional.ofNullable(snapshots.get(new 
MvccTableInfo((MvccTable) pctTable)))
+                                : Optional.empty();
+                        // Qualification must describe the same files that 
alignment and execution read.
+                        if (!pctTable.isValidRelatedTable(snapshot)) {

Review Comment:
   [P1] Keep one Iceberg snapshot through schema-change refresh
   
   A partitioned MV over a Doris view of an Iceberg table with retained DATE 
identity and day specs can publish stale rows as fresh. An `ALTER VIEW` marks 
the MV `SCHEMA_CHANGE`. If an Iceberg append to an existing date becomes 
visible after the task pins its snapshot, `ensureMTMVQueryUsable` reparses the 
query and replaces the statement context that held that pin. Alignment and 
`MTMVRefreshContext` then use the newer snapshot, while this check and `exec()` 
still use the original task pin. The overwrite misses the appended row but 
records the newer snapshot ID for the same partition, so a later AUTO refresh 
can skip it. Preserve the task's pinned context during reanalysis, or restore 
it before alignment and freshness capture.



##########
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)) {
+                icebergPartitions = authenticator.execute(() -> 
loadIcebergPartition(table, snapshotId));
+            } else {
+                IcebergMvPartitionSnapshot projection = authenticator.execute(

Review Comment:
   [P2] Keep MV manifest enumeration out of ordinary Iceberg scan binding
   
   On a cold partition cache, a plain `SELECT` that filters to one date on a 
native Iceberg DATE-identity table reaches this loader through 
`LogicalFileScan.initialSelectedPartitions` and 
`ExternalTable.initSelectedPartitions`. This reads every live manifest to build 
the MV range map before `IcebergScanNode` can apply the filter. The physical 
Iceberg scan does its own file selection and receives no selected-partition map 
from that binding step. Load the evolved projection where MV partition mapping 
or rewrite freshness needs it and keep ordinary binding on Iceberg's scan path.



-- 
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]

Reply via email to