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


##########
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:
   **[P1] Resolve file identity before matching deletion vectors**
   
   On an HDFS table, append `/data/a.parquet` in V2, upgrade to V4, then append 
a different file with the same stored path. The V2 entry names a file at the 
filesystem root. The V4 entry names a file under the table directory. Add a V4 
deletion vector that references only the new file.
   
   With Iceberg 1.12, both `TableScan.planFiles()` and the `DeleteFileIndex` 
used by Doris cached planning assigned that vector to **both** files. 
Qualifying just the V2 path as `hdfs://nn/data/a.parquet` made both planners 
assign it only to the V4 file. The path resolution here happens after 
`DeleteFileIndex.findDV()` has matched the raw strings, so BE can filter out a 
live row from the old file at the same position.
   
   Please resolve the data file and the vector’s target according to their 
producing manifests before building and probing the delete index. Keep the 
original spelling separately for legacy position-delete payloads, and cover the 
collision in both planning paths.



##########
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:
   **[P1] Enforce the V4 write restriction when `rewrite_manifests` refreshes 
and commits**
   
   Start `rewrite_manifests` on a V3 table with two manifests containing rooted 
data paths. After this check observes V3, use a second catalog handle to 
upgrade the table to V4, then let the first operation continue. 
`SnapshotProducer.apply()` refreshes the table metadata, so the rewrite can 
commit against V4 after passing admission on V3.
   
   I reproduced this ordering with two Iceberg 1.12 catalog handles and the 
Doris `RewriteManifestExecutor`. Both rooted files opened before the rewrite. 
The executor reported two manifests replaced by one and committed a new V4 
snapshot. The next read resolved `/data/a.parquet` as 
`hdfs://nn/warehouse/db/race//data/a.parquet` and raised `NotFoundException` 
for both data files. The original objects were still present.
   
   Please carry the admitted format version into the procedure’s 
`TableOperations` and validate the refreshed metadata and final commit base, 
including retries. A concurrent upgrade should abort the rewrite before it 
publishes a new snapshot.



##########
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:
   **[P1] Verify the table-relative manifest before accepting it after snapshot 
expiration**
   
   Create a V2 table with a rooted `write.metadata.path`, append a file, then 
upgrade to V4 and append again so the current snapshot retains the V2 manifest. 
Leave the original manifest intact and place another valid manifest at 
`tableLocation + "/" + retained.path()`. Expire only the snapshot that created 
the retained manifest, with `cleanExpiredFiles(false)`, and reopen the current 
snapshot cold.
   
   Before expiration, the Iceberg 1.12 reader returned `/data/correct.parquet` 
with `record_count = 10`. After expiration, the same descriptor returned an 
unrelated file with `record_count = 77`. The substitute even had a different 
byte length. Once `source` is unavailable, this branch accepts the 
table-relative candidate solely because it exists. Only the rooted branch below 
checks `file.length()`. A current-snapshot query can therefore scan another 
file’s rows.
   
   Please validate both candidates against the descriptor before choosing one. 
If both remain plausible and their identity cannot be established, fail the 
read explicitly.



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