github-actions[bot] commented on code in PR #66348:
URL: https://github.com/apache/doris/pull/66348#discussion_r3695995835


##########
be/src/io/fs/azure_obj_storage_client.cpp:
##########
@@ -247,6 +253,38 @@ ObjectStorageResponse 
AzureObjStorageClient::complete_multipart_upload(
             opts, _tls_debug_context);
 }
 
+ObjectStorageResponse AzureObjStorageClient::abort_multipart_upload(
+        const ObjectStoragePathOptions& opts) {
+    auto client = _client->GetBlockBlobClient(opts.key);
+    auto response = do_azure_client_call(
+            [&]() {
+                GetBlockListOptions get_options;
+                get_options.ListType = Models::BlockListType::All;
+                auto block_list = client.GetBlockList(get_options);
+                if (block_list.Value.CommittedBlocks.empty()) {

Review Comment:
   [P1] Preserve a pre-existing Put Blob object during abort
   
   `CommittedBlocks.empty()` does not prove that the target key has no 
committed object. Azure defines this list as blocks committed through Put Block 
List, while this client itself writes small objects with `UploadFrom` / Put 
Blob. Because `S3FileSystem::create_file_impl` allows an existing key, a 
multipart replacement can stage blocks over such an object and, on failure, 
this branch deletes the valid old blob; `IfMatch`, when present, merely 
authorizes deleting the ETag that already existed. Please preserve committed 
content when abandoning this writer (leaving its unique staged blocks to expire 
if Azure cannot selectively unstage them) and add a test that seeds the key 
through `put_object`, stages a multipart block, aborts, and verifies the 
original bytes remain. See [Azure's Get Block List 
contract](https://learn.microsoft.com/en-us/rest/api/storageservices/get-block-list).



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergRemoveOrphanFilesAction.java:
##########
@@ -0,0 +1,267 @@
+// 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.action;
+
+import org.apache.doris.connector.api.ConnectorColumn;
+import org.apache.doris.connector.api.ConnectorSession;
+import org.apache.doris.connector.api.ConnectorType;
+import org.apache.doris.connector.api.DorisConnectorException;
+import org.apache.doris.connector.api.pushdown.ConnectorPredicate;
+import org.apache.doris.foundation.util.ArgumentParsers;
+
+import com.google.common.collect.Lists;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.ReachableFileUtil;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileInfo;
+import org.apache.iceberg.io.SupportsPrefixOperations;
+import org.apache.iceberg.util.PropertyUtil;
+
+import java.io.IOException;
+import java.net.URI;
+import java.time.Duration;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/** Safely lists or deletes old files that are unreachable from every retained 
snapshot. */
+public class IcebergRemoveOrphanFilesAction extends BaseIcebergAction {
+    private static final long MIN_RETENTION_MS = 
Duration.ofHours(24).toMillis();
+    public static final String OLDER_THAN = "older_than";
+    public static final String LOCATION = "location";
+    public static final String DRY_RUN = "dry_run";
+
+    public IcebergRemoveOrphanFilesAction(Map<String, String> properties, 
List<String> partitionNames,
+            ConnectorPredicate whereCondition) {
+        super("remove_orphan_files", properties, partitionNames, 
whereCondition);
+    }
+
+    @Override
+    protected void registerIcebergArguments() {
+        namedArguments.registerRequiredArgument(OLDER_THAN, "Creation time 
cutoff in milliseconds",
+                ArgumentParsers.nonNegativeLong(OLDER_THAN));
+        namedArguments.registerOptionalArgument(LOCATION, "Prefix within the 
table location",
+                null, ArgumentParsers.nonEmptyString(LOCATION));
+        namedArguments.registerOptionalArgument(DRY_RUN, "Only count orphan 
files", true,
+                ArgumentParsers.booleanValue(DRY_RUN));
+    }
+
+    @Override
+    protected void validateIcebergAction() {
+        validateNoPartitions();
+        validateNoWhereCondition();
+        String location = namedArguments.getString(LOCATION);
+        if (location != null) {
+            try {
+                normalizeLocation(location);
+            } catch (IllegalArgumentException e) {
+                throw new DorisConnectorException("Invalid location URI: " + 
location, e);
+            }
+        }
+    }
+
+    @Override
+    protected List<String> executeAction(Table table, ConnectorSession 
session) {
+        if (!(table.io() instanceof SupportsPrefixOperations)) {
+            throw new DorisConnectorException("remove_orphan_files requires 
FileIO prefix listing support");
+        }
+        if (!PropertyUtil.propertyAsBoolean(table.properties(), 
TableProperties.GC_ENABLED,
+                TableProperties.GC_ENABLED_DEFAULT)) {
+            // A GC-disabled table may share files with another table, so no 
destructive scan is safe.
+            throw new DorisConnectorException("Cannot remove orphan files: 
Iceberg GC is disabled");
+        }
+        String tableLocation = normalizeLocation(table.location());
+        String scanLocation = namedArguments.getString(LOCATION);
+        scanLocation = scanLocation == null ? tableLocation : 
normalizeLocation(scanLocation);
+        // Normalize dot segments before the containment check so local FileIO 
paths cannot escape the table root.
+        if (!scanLocation.equals(tableLocation) && 
!scanLocation.startsWith(tableLocation + "/")) {
+            throw new DorisConnectorException("location must be within the 
Iceberg table location");
+        }
+
+        try {
+            ReachableIndex reachable = new 
ReachableIndex(collectReachableFiles(table));
+            long orphanCount = 0;
+            long deletedCount = 0;
+            long olderThan = namedArguments.getLong(OLDER_THAN);
+            // The SQL procedure needs a retention fence because concurrent 
uploads are not reachable until commit.
+            if (olderThan > System.currentTimeMillis() - MIN_RETENTION_MS) {
+                throw new DorisConnectorException(
+                        "older_than must retain at least 24 hours of files");
+            }
+            boolean dryRun = namedArguments.getBoolean(DRY_RUN);
+            // Object stores use raw prefix matching, so the separator 
prevents "table_backup" siblings
+            // from being treated as children of "table".
+            String listingPrefix = scanLocation.endsWith("/") ? scanLocation : 
scanLocation + "/";
+            for (FileInfo file : ((SupportsPrefixOperations) 
table.io()).listPrefix(listingPrefix)) {
+                if (file.createdAtMillis() < olderThan && 
!isReachable(file.location(), reachable)) {
+                    orphanCount++;
+                    if (!dryRun) {
+                        table.io().deleteFile(file.location());
+                        deletedCount++;
+                    }
+                }
+            }
+            return Lists.newArrayList(String.valueOf(orphanCount), 
String.valueOf(deletedCount));
+        } catch (Exception e) {
+            throw new DorisConnectorException("Failed to remove orphan files: 
" + e.getMessage(), e);
+        }
+    }
+
+    private Set<String> collectReachableFiles(Table table) throws IOException {
+        Set<String> reachable = new 
HashSet<>(ReachableFileUtil.metadataFileLocations(table, true));
+        // Hadoop tables consult this live pointer even though it is not part 
of the metadata log.
+        reachable.add(ReachableFileUtil.versionHintLocation(table));
+        Set<String> scannedDeleteManifests = new HashSet<>();
+        reachable.addAll(ReachableFileUtil.manifestListLocations(table));
+        reachable.addAll(ReachableFileUtil.statisticsFilesLocations(table));
+        for (Snapshot snapshot : table.snapshots()) {
+            for (ManifestFile manifest : snapshot.allManifests(table.io())) {
+                reachable.add(manifest.path());
+            }
+            for (ManifestFile manifest : snapshot.deleteManifests(table.io())) 
{
+                if (!scannedDeleteManifests.add(manifest.path())) {
+                    continue;
+                }
+                // A retained delete file may not apply to any current data 
task, so read delete manifests directly.
+                try (ManifestReader<DeleteFile> deletes =
+                        ManifestFiles.readDeleteManifest(manifest, table.io(), 
table.specs())) {
+                    deletes.forEach(delete -> 
reachable.add(delete.location()));
+                }
+            }
+            try (CloseableIterable<FileScanTask> tasks = table.newScan()

Review Comment:
   [P2] Read each retained manifest only once
   
   This calls `planFiles()` for every retained snapshot. In an append-heavy 
history, later snapshots inherit earlier data manifests, so the same remote 
manifests and entries are reopened across snapshots and total work grows 
quadratically before the `HashSet` removes duplicate locations. This 
synchronous FE action can therefore become impractical on a table with a long 
retained history. Iceberg 1.10.1's own action [deduplicates manifest paths 
before reading their 
entries](https://github.com/apache/iceberg/blob/apache-iceberg-1.10.1/spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/BaseSparkAction.java#L138-L157).
 Please collect unique data manifests and read each once, and add a 
recording-FileIO test whose manifest-open count is bounded by unique manifests 
rather than snapshots.



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