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


##########
be/src/io/fs/azure_obj_storage_client.cpp:
##########
@@ -216,35 +237,78 @@ ObjectStorageResponse 
AzureObjStorageClient::put_object(const ObjectStoragePathO
 ObjectStorageUploadResponse AzureObjStorageClient::upload_part(const 
ObjectStoragePathOptions& opts,
                                                                
std::string_view stream,
                                                                int part_num) {
-    auto client = _client->GetBlockBlobClient(opts.key);
+    DCHECK(opts.upload_id.has_value());
+    auto client = 
_client->GetBlockBlobClient(azure_multipart_temp_key(opts.key, 
*opts.upload_id));
+    std::string block_id = azure_block_id(opts, part_num);
     auto resp = do_azure_client_call(
             [&]() {
                 Azure::Core::IO::MemoryBodyStream memory_body(
                         reinterpret_cast<const uint8_t*>(stream.data()), 
stream.size());
                 // The blockId must be base64 encoded
                 SCOPED_BVAR_LATENCY(s3_bvar::s3_multi_part_upload_latency);
-                client.StageBlock(base64_encode_part_num(part_num), 
memory_body);
+                client.StageBlock(block_id, memory_body);
+                if (opts.deferred_completion) {

Review Comment:
   Follow-up: the new-BE/old-FE path only fails closed while this 60-second 
lease is active. A file can finish more than a minute before the 
transaction-wide FE commit, with no renewal in between. After expiry, the old 
FE's unfenced `commitBlockList` is accepted; on an existing legacy target (or 
one with residual legacy blocks), its deterministic part IDs select the old 
blocks rather than the new BE's namespaced blocks, so Hive can commit metadata 
while stale bytes are republished. Please gate this protocol on an 
exact-ID-aware coordinator or keep a renewable fence alive until that 
coordinator completes it, and test the expired-lease rolling path.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/action/IcebergRemoveOrphanFilesAction.java:
##########
@@ -0,0 +1,344 @@
+// 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.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.ManifestContent;
+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.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.ArrayList;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+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");
+        }
+        List<String> scanLocations = resolveScanLocations(table);
+
+        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);
+            Set<String> visitedFiles = new HashSet<>();
+            for (String scanLocation : scanLocations) {
+                // Object stores use raw prefix matching, so the separator 
excludes sibling prefixes.
+                String listingPrefix = scanLocation.endsWith("/") ? 
scanLocation : scanLocation + "/";
+                for (FileInfo file : ((SupportsPrefixOperations) 
table.io()).listPrefix(listingPrefix)) {
+                    if (visitedFiles.add(file.location()) && 
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 List<String> resolveScanLocations(Table table) {
+        List<String> ownedRoots = resolveOwnedRoots(table.location(), 
table.properties());
+
+        String requested = namedArguments.getString(LOCATION);
+        if (requested != null) {
+            String normalized = normalizeLocation(requested);
+            boolean owned = ownedRoots.stream().anyMatch(root -> 
isWithin(normalized, root));
+            if (!owned) {
+                throw new DorisConnectorException(
+                        "location must be within an Iceberg table-owned 
metadata or data location");
+            }
+            return Lists.newArrayList(normalized);
+        }
+
+        return minimalOwnedRoots(ownedRoots);
+    }
+
+    static List<String> resolveOwnedRoots(String tableLocation, Map<String, 
String> properties) {
+        String tableRoot = normalizeLocation(tableLocation);
+        String dataRoot = normalizeLocation(resolveDataLocation(properties, 
tableRoot));

Review Comment:
   Follow-up: matching the exact `parent/table` context still does not prove 
exclusivity. Iceberg derives that context from only the last two table-location 
components, so tables such as `.../catalog-a/db/t` and `.../catalog-b/db/t` can 
share one `write.data.path` and generate the same `<hash>/db/t/...` pattern. 
Running this action for either table then treats the other's old live files as 
owned-but-unreachable and can delete them. Please fail closed for a shared 
external root unless context ownership is established outside this suffix (or 
require the explicit unsafe-location path), and add a same-suffix two-table 
test.



##########
be/src/runtime/runtime_state.cpp:
##########
@@ -52,12 +52,37 @@
 #include "runtime/thread_context.h"
 #include "storage/id_manager.h"
 #include "storage/storage_engine.h"
+#include "util/thrift_util.h"
 #include "util/timezone_utils.h"
 #include "util/uid_util.h"
 
 namespace doris {
 using namespace ErrorCode;
 
+Status RuntimeState::add_iceberg_commit_datas(TIcebergCommitData 
iceberg_commit_data) {
+    ThriftSerializer serializer(false, 256);
+    uint32_t serialized_size = 0;
+    uint8_t* buffer = nullptr;
+    RETURN_IF_ERROR(serializer.serialize(&iceberg_commit_data, 
&serialized_size, &buffer));
+
+    constexpr size_t report_envelope_headroom = 1024 * 1024;
+    const size_t thrift_limit = 
static_cast<size_t>(std::max(config::thrift_max_message_size, 0));

Review Comment:
   Follow-up: the receiver-limit propagation is fixed, but the constant 1 MiB 
allowance is not a bound on the rest of `TReportExecStatusParams`. The callback 
adds variable-length fields after this guard, including `error_log` (UDF 
warnings are arbitrary strings), first-error/load reports, export files, and 
other commit vectors. Commit metadata can therefore fill the admitted budget 
and still make the final RPC exceed the receiver limit after successful writer 
close has released file-cleanup ownership, stranding the files. Please budget 
the complete binary report (or retain cleanup ownership until acknowledgement) 
and add a near-limit test with a >1 MiB non-Iceberg envelope.



##########
be/src/exec/sink/writer/async_result_writer.cpp:
##########
@@ -54,9 +56,12 @@ Status AsyncResultWriter::sink(Block* block, bool eos) {
     if (_is_finished()) {
         _dependency->set_ready();
     }
-    if (rows) {
-        _memory_used_counter->update(add_block->allocated_bytes());
-        _data_queue.emplace_back(std::move(add_block));
+    if (rows || eos) {
+        if (rows) {
+            _memory_used_counter->update(add_block->allocated_bytes());
+        }
+        _data_queue.emplace_back(QueuedBlock {

Review Comment:
   [P2] Release queued reservation tokens when asynchronous `open()` fails. The 
producer can enqueue here while the writer thread is still opening; 
`force_close()` then makes `while (_writer_status.ok())` skip the only 
`_data_queue.clear()` path, and the token stays charged until writer 
destruction even though the finish dependency is ready. This can retain a large 
query/process/workload-group reservation throughout cancellation. Please clear 
or swap the queue on every terminal exit and add an enqueue-before-open-failure 
test that verifies the accounting returns to baseline.



##########
be/src/exec/operator/spill_iceberg_table_sink_operator.cpp:
##########
@@ -55,47 +57,62 @@ size_t 
SpillIcebergTableSinkLocalState::get_reserve_mem_size(RuntimeState* state
     if (!_writer) {
         return 0;
     }
-    auto current_writer = _writer->current_writer();
-    auto* sort_writer = 
dynamic_cast<VIcebergSortWriter*>(current_writer.get());
-    if (!sort_writer) {
-        return 0;
+    std::vector<IcebergSorterReserveMemory> per_partition_reservations;
+    auto active_writers = _writer->active_writers();
+    per_partition_reservations.reserve(active_writers->size());
+    for (const auto& writer : *active_writers) {
+        if (auto* sort_writer = 
dynamic_cast<VIcebergSortWriter*>(writer.get())) {
+            auto reservation = 
sort_writer->get_reserve_mem_size_components(state, eos);
+            per_partition_reservations.push_back(
+                    {.retained_growth = reservation.retained_growth,
+                     .transient_workspace = reservation.transient_workspace});
+        }
     }
-
-    return sort_writer->get_reserve_mem_size(state, eos);
+    // Column growth remains in every touched sorter, while sorting workspace 
is reused by serial dispatch.
+    // The final queued item may contain rows and also owns the reservation 
used by async finish().

Review Comment:
   [P1] Reserve the final spill-merge fan-in on EOS. When a sorter has already 
spilled its in-memory block, its reserve components are zero, so this path 
retains only the minimum allowance. `finish()` nevertheless enters 
`_combine_files_output()`, whose merger constructs every input cursor and 
immediately reads one spill block per run (up to the configured merge fan-in, 
64 MiB by default) before producing output. That work runs under this 
transferred reservation but is materially under-reserved and can cross a hard 
query/process limit. Please include EOS merge inputs/output workspace in the 
estimate and cover an empty sorter with several spill runs under a tight limit.



##########
fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorTransaction.java:
##########
@@ -304,10 +304,49 @@ private void applyBeginGuards(IcebergWriteContext ctx, 
String tableName) {
                     throw new IllegalArgumentException(branchName
                             + " is a tag, not a branch. Tags cannot be targets 
for producing snapshots");
                 }
+                this.baseSnapshotId = op == WriteOperation.OVERWRITE
+                        ? resolveOverwriteBaseSnapshot(ctx, 
branchRef.snapshotId(), tableName) : null;
             } else {
                 this.branchName = null;
+                this.baseSnapshotId = op == WriteOperation.OVERWRITE
+                        ? resolveOverwriteBaseSnapshot(ctx, 
getSnapshotIdIfPresent(table), tableName) : null;
+            }
+        }
+    }
+
+    private Long resolveOverwriteBaseSnapshot(IcebergWriteContext ctx, Long 
targetHead, String tableName) {
+        if (!ctx.isReadSnapshotPinned()) {
+            return targetHead;
+        }
+        long readSnapshotId = ctx.getReadSnapshotId();
+        if (readSnapshotId < 0) {
+            // An explicit empty read must conflict with any snapshot created 
before beginWrite.
+            if (targetHead != null) {
+                throw new DorisConnectorException("Iceberg table " + tableName

Review Comment:
   [P1] Preserve the explicit-empty generation fence across the transaction 
refresh. `applyBeginGuards()` observes an empty head and converts the pinned 
`-1` to `null` here, but `openTransaction()` immediately follows and 
`newTransaction()` refreshes the mutable table. If another writer creates the 
first snapshot in that interval, it becomes this transaction's base; the 
overwrite paths then skip `validateFromSnapshot` because `baseSnapshotId` is 
null and can replace that concurrent data. Please retain the `-1` OCC sentinel 
(as the RowDelta path does) or perform the empty-head check against the 
refreshed transaction base, with an injected check-to-refresh race test.



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