Gabriel39 commented on code in PR #71373:
URL: https://github.com/apache/doris/pull/71373#discussion_r4794058357


##########
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:
   The direct DATE-identity boundary was fixed in 
5f900bb66cd317d131561ec9e98fcb833d93535f and remains covered in 
aaa5876972852879d421a6601c0c25739fade531: 9999-12-31 has a MAXVALUE exclusive 
upper bound. The real-manifest evolution test reaches actual FE range 
construction. #71365 has equivalent bounds and now versions the plugin contract 
as API 43. Generic DATE_TRUNC rollup of MAXVALUE remains the existing 
unsupported policy.



##########
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(
+                        () -> IcebergMvPartitionSnapshot.load(table, 
snapshotId));
+                if (!projection.isSupported()) {
+                    return IcebergPartitionInfo.empty();

Review Comment:
   Fixed in aaa5876972852879d421a6601c0c25739fade531. The shared PCT freshness 
path checks the captured snapshot's partition-tracking eligibility before 
comparing name sets, so unsupported empty maps cannot prove freshness. The 
verdict is cached once per related table per refresh context. The regression 
first proves MV use for B, evolves the identity source to an incompatible 
unpartitioned layout, appends A, then requires MV rejection and the explicit A 
row with union compensation disabled. It passed on this branch's own FE/BE; 
#71365 carries the same guard and SQL.



##########
fe/fe-core/src/main/java/org/apache/doris/mtmv/MTMVPlanUtil.java:
##########
@@ -385,6 +385,24 @@ public static DataType getDataType(Slot s, int i, 
ConnectContext ctx, String par
     }
 
     public static MTMVAnalyzeQueryInfo analyzeQueryWithSql(MTMV mtmv, 
ConnectContext ctx) throws UserException {
+        // SQL parsing replaces the context; the caller still owns its 
captured pins and metadata leases.
+        StatementContext caller = ctx.getStatementContext();
+        try {
+            return analyzeQueryWithSqlInternal(mtmv, ctx);

Review Comment:
   Fixed in aaa5876972852879d421a6601c0c25739fade531. The temporary parser 
context inherits the caller's materialized snapshots before source binding, 
without transferring statement-resource ownership. The task warms persisted PCT 
inputs, plus newly discovered candidates during partitioned SCHEMA_CHANGE, 
before acquiring base-table locks. The schema-analysis test checks the pin 
inside analysis on success and failure; the task test covers newly discovered 
candidates. Equivalent changes are in #71365.



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