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


##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergScanPlanProvider.java:
##########
@@ -2098,7 +2099,7 @@ private PerFileScratch computePerFileInvariants(Table 
table, Schema scanSchema,
         file.firstRowId = firstRowId;
         file.lastUpdatedSequenceNumber = lastUpdatedSequenceNumber;
         file.rawDataPath = rawDataPath;
-        file.normalizedPath = uriNormalizer.apply(rawDataPath);
+        file.normalizedPath = normalizeFileLocation(dataFile, uriNormalizer);

Review Comment:
   Fixed in b2e860659f4e11df5ab98bcdd066e38c17b09d01.
   
   Both the SDK and cached DeleteFileIndex paths now resolve data-file and 
deletion-vector target identities before indexing/matching, using each entry's 
producing manifest. Hadoop and default ResolvingFileIO routes qualify legacy 
roots in their actual filesystem namespace through the authenticated factory. 
The original ContentFile objects and native original_file_path remain unchanged 
for legacy position-delete payload matching.
   
   Sixteen SDK-backed collision cases cover V2/V3 upgrades, legacy/new targets, 
cache off/on, eager/streamed planning, direct Hadoop and 
resolving/authentication/REST decorators. The initial eight collision probes 
reproduce the wrong associations before the fix. The final candidate passes all 
114 V4 cases and 20 JNI cases; combined related runs have 1012 passes, zero 
failures/errors and two previously disabled cases. Required FE Checkstyle 
passed. This uses Hadoop's local filesystem qualification in unit tests; live 
KDC/HDFS is not claimed.



##########
fe/fe-iceberg-common/src/main/java/org/apache/doris/connector/iceberg/IcebergV4FileIO.java:
##########
@@ -0,0 +1,463 @@
+// 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 com.fasterxml.jackson.core.JsonGenerator;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import com.github.benmanes.caffeine.cache.LoadingCache;
+import org.apache.iceberg.ContentFile;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.InternalData;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestListFile;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.TableMetadataParser;
+import org.apache.iceberg.avro.AvroIterable;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.InputFile;
+import org.apache.iceberg.io.OutputFile;
+import org.apache.iceberg.util.JsonUtil;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.io.UncheckedIOException;
+import java.security.DigestOutputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.regex.Pattern;
+
+/** Serializable, borrowed read view for table-relative format v4 locations. */
+public final class IcebergV4FileIO implements FileIO {
+    private static final long serialVersionUID = 1L;
+    private static final Pattern SCHEME = 
Pattern.compile("^[a-zA-Z][a-zA-Z0-9+.-]*:.*", Pattern.DOTALL);
+    private final FileIO delegate;
+    private final String tableLocation;
+    private final Map<String, MetadataLocation> taskLocations;
+    private final transient TableMetadata metadata;
+    private transient LoadingCache<String, Integer> manifestVersions;
+    private transient LoadingCache<Long, MetadataHeader> snapshotHeaders;
+    private transient ConcurrentMap<String, MetadataLocation> 
metadataLocations;
+
+    public IcebergV4FileIO(FileIO delegate, String tableLocation) {
+        this(delegate, tableLocation, null);
+    }
+
+    public IcebergV4FileIO(FileIO delegate, String tableLocation, 
TableMetadata metadata) {
+        this(delegate, tableLocation, metadata, Map.of());
+    }
+
+    private IcebergV4FileIO(FileIO delegate, String tableLocation,
+            TableMetadata metadata, Map<String, MetadataLocation> 
taskLocations) {
+        this.delegate = Objects.requireNonNull(delegate, "delegate");
+        this.tableLocation = tableLocation;
+        this.metadata = metadata;
+        this.taskLocations = Map.copyOf(taskLocations);
+    }
+
+    public FileIO delegate() {
+        return delegate;
+    }
+
+    public IcebergV4FileIO withDelegate(FileIO replacement) {
+        IcebergV4FileIO view = new IcebergV4FileIO(replacement, tableLocation, 
metadata, taskLocations);
+        // Per-consumer authentication changes the IO delegate, not this 
statement's frozen path provenance.
+        view.metadataLocations = locations();
+        return view;
+    }
+
+    /** Bind just this task's concrete reference; neither metadata JSON nor 
snapshot history crosses the wire. */
+    public IcebergV4FileIO forManifest(ManifestFile file) {
+        prepareManifest(file);
+        MetadataLocation location = locations().get(file.path());
+        return new IcebergV4FileIO(delegate, tableLocation, null,
+                location == null ? Map.of() : Map.of(file.path(), location));
+    }
+
+    public IcebergV4FileIO forManifestList(ManifestListFile file, long 
snapshotId) {
+        if (!file.location().startsWith("/")) {
+            return new IcebergV4FileIO(delegate, tableLocation);
+        }
+        snapshotHeader(file.location(), snapshotId);
+        return new IcebergV4FileIO(delegate, tableLocation, null,
+                Map.of(file.location(), locations().get(file.location())));
+    }
+
+    public static String resolve(String tableLocation, String path) {
+        Objects.requireNonNull(path, "path");
+        if (isAbsolute(path)) {
+            return path;
+        }
+        if (tableLocation == null || tableLocation.isEmpty()) {
+            throw new IllegalArgumentException("Relative Iceberg v4 path 
requires a table location: " + path);
+        }
+        // Duplicate separators are part of an object-store key, including at 
the concatenation boundary.
+        return tableLocation + "/" + path;
+    }
+
+    private static boolean isAbsolute(String path) {
+        return SCHEME.matcher(path).matches();
+    }
+
+    public String resolveLocation(String path) {
+        return resolve(tableLocation, path);
+    }
+
+    public String resolveContentFile(ContentFile<?> file) {
+        return isAbsolute(file.location()) || isLegacyEntry(file)
+                ? file.location() : resolve(tableLocation, file.location());
+    }
+
+    private boolean isLegacyEntry(ContentFile<?> file) {
+        String manifest = file.manifestLocation();
+        // Encoding alone is insufficient: the SDK can also write a V4 
manifest using Avro.
+        return manifest != null && FileFormat.fromFileName(manifest) == 
FileFormat.AVRO
+                && versions().get(manifest) < 4;
+    }
+
+    private synchronized LoadingCache<String, Integer> versions() {
+        if (manifestVersions == null) {
+            // Keep only small version numbers; never serialize a query's 
cache into every metadata task.
+            manifestVersions = 
Caffeine.newBuilder().maximumSize(256).build(this::readManifestVersion);
+        }
+        return manifestVersions;
+    }
+
+    private int readManifestVersion(String manifest) {
+        MetadataLocation reference = manifest.startsWith("/") ? 
locations().get(manifest) : null;
+        if (manifest.startsWith("/") && reference == null) {
+            throw new IllegalStateException("Manifest reference has not been 
bound: " + manifest);
+        }
+        String location = reference == null ? resolve(tableLocation, manifest) 
: reference.location;
+        return readHeader(delegate.newInputFile(location), 
FileFormat.AVRO).version;
+    }
+
+    /** Bind provenance even on a parsed-manifest cache hit, where the SDK 
will not open the manifest again. */
+    public void prepareManifest(ManifestFile file) {
+        if (file.path().startsWith("/")) {
+            metadataLocation(file);
+        }
+    }
+
+    /** A cached-only prefetch probe runs under its queue lock and must never 
bind provenance through I/O. */
+    public boolean isManifestPrepared(ManifestFile file) {
+        if (!file.path().startsWith("/")) {
+            return true;
+        }
+        MetadataLocation bound = locations().get(file.path());
+        return bound != null && Objects.equals(bound.snapshotId, 
file.snapshotId());
+    }
+
+    private synchronized ConcurrentMap<String, MetadataLocation> locations() {
+        if (metadataLocations == null) {
+            // Query-owned provenance, not a cross-query cache. Retain only 
ambiguous slash-leading references.
+            metadataLocations = new ConcurrentHashMap<>(taskLocations);
+        }
+        return metadataLocations;
+    }
+
+    private String remember(String path, String location, Long snapshotId) {
+        MetadataLocation previous = locations().putIfAbsent(path, new 
MetadataLocation(location, snapshotId));
+        if (previous != null && !previous.location.equals(location)) {
+            throw new IllegalArgumentException("Ambiguous legacy and V4 
metadata reference: " + path);
+        }
+        return location;
+    }
+
+    private synchronized LoadingCache<Long, MetadataHeader> snapshots() {
+        if (snapshotHeaders == null) {
+            snapshotHeaders = Caffeine.newBuilder().maximumSize(256).build(id 
-> {
+                Snapshot snapshot = metadata == null ? null : 
metadata.snapshot(id);
+                String path = snapshot == null ? null : 
snapshot.manifestListLocation();
+                return path == null ? null : snapshotHeader(path, id);
+            });
+        }
+        return snapshotHeaders;
+    }
+
+    private MetadataHeader snapshotHeader(String path, long snapshotId) {
+        String relative = hasBase() || isAbsolute(path) ? 
resolve(tableLocation, path) : null;
+        MetadataHeader header = relative == null ? null : 
existingHeader(relative, FileFormat.AVRO);
+        if (header != null && Objects.equals(header.snapshotId, snapshotId)) {
+            if (path.startsWith("/")) {
+                remember(path, relative, snapshotId);
+            }
+            return header;
+        }
+        if (path.startsWith("/")) {
+            header = existingHeader(path, FileFormat.AVRO);
+            if (header != null && Objects.equals(header.snapshotId, 
snapshotId)) {
+                remember(path, path, snapshotId);
+                return header;
+            }
+        }
+        throw new NotFoundException("Cannot find manifest list for snapshot 
%s: %s", snapshotId, path);
+    }
+
+    private String metadataLocation(ManifestFile file) {
+        String path = file.path();
+        MetadataLocation bound = locations().get(path);
+        if (bound != null && Objects.equals(bound.snapshotId, 
file.snapshotId())) {
+            return bound.location;
+        }
+        MetadataHeader source = file.snapshotId() == null ? null : 
snapshots().get(file.snapshotId());
+        // Only a pre-V4 producer proves that a slash-leading reference is 
filesystem-rooted.
+        // New V4 references remain relative, including when an unrelated root 
path also exists.
+        if (source != null && source.version < 4) {
+            return remember(path, path, file.snapshotId());
+        }
+        String relative = hasBase() ? resolve(tableLocation, path) : null;
+        if (relative != null && existingInput(relative) != null) {

Review Comment:
   Fixed in b2e860659f4e11df5ab98bcdd066e38c17b09d01.
   
   Manifest selection now validates concrete candidate lengths against the 
immutable descriptor before binding a location. A retained producer selects its 
proven namespace. When producer provenance has expired, both relative and 
rooted candidates are considered: a unique matching candidate is selected, two 
plausible candidates fail explicitly with an ambiguity error, and unmatched 
lengths fail rather than reading unrelated content.
   
   The SDK-backed regression retains the original manifest, expires its 
producer without cleanup and installs a valid relative decoy of a different 
length; cold cached and uncached plans retain the correct file. A second case 
with two matching candidates verifies explicit refusal. Additional 
storage-boundary tests retain support for FileIOs that reject scheme-less roots 
while propagating permission/IO failures. Both original expiration cases 
reproduce the reported behavior before the fix. All new cases and explicit FE 
Checkstyle pass.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergProcedureOps.java:
##########
@@ -201,14 +201,17 @@ private ConnectorProcedureResult 
runInAuthScopeUntracked(IcebergTableHandle hand
         // Resolve the per-request ops before the auth scope so a session=user 
fail-closed surfaces the
         // DorisConnectorException verbatim (not wrapped by 
executeAuthenticated's catch).
         IcebergCatalogOps ops = catalogOpsResolver.apply(session);
+        Function<Table, ConnectorProcedureResult> execute = table -> {
+            IcebergWriterHelper.validateWriteFormat(table);

Review Comment:
   Fixed in b2e860659f4e11df5ab98bcdd066e38c17b09d01.
   
   The procedure now captures its admitted format before validation and carries 
it through TableOperations.current/refresh, commit base and updated metadata, 
the final commit refresh and temporary operations. Catalog CAS still handles a 
race after that final refresh; its retry returns through the guarded refresh 
and aborts a format upgrade instead of publishing a V4 rewrite. Existing 
authenticated IO, encryption/location operations, cleanup policy, reporters and 
labels are forwarded.
   
   Four deterministic SDK catalog-handle cases upgrade V3 to V4 at refresh or 
final CAS through plain/authenticated procedure entry points. They fail on the 
original implementation; the fix preserves the original snapshot and the 
retained manifests remain readable. Two same-format concurrent-commit controls 
verify that ordinary rewrite retries still succeed. The complete related 
selection passes 1012 tests (two baseline-disabled cases), including existing 
procedure and Kerberos-IO suites; FE Checkstyle passes. No live KDC/HDFS run is 
claimed.



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