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


##########
fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeletePredicate.java:
##########
@@ -0,0 +1,367 @@
+// 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.datasource.iceberg;
+
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.nereids.trees.expressions.And;
+import org.apache.doris.nereids.trees.expressions.Between;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.GreaterThan;
+import org.apache.doris.nereids.trees.expressions.GreaterThanEqual;
+import org.apache.doris.nereids.trees.expressions.InPredicate;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.LessThan;
+import org.apache.doris.nereids.trees.expressions.LessThanEqual;
+import org.apache.doris.nereids.trees.expressions.Not;
+import org.apache.doris.nereids.trees.expressions.Or;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCatalogRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCheckPolicy;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSink;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types.NestedField;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+/**
+ * Builds the complete statement predicate for an Iceberg whole-file metadata 
delete.
+ *
+ * <p>Unlike the conflict-detection helper, this path may be destructive: 
every conjunct must be
+ * representable exactly. A missing conjunct would widen the delete and can 
drop a file that still
+ * contains live rows, so any uncertainty rejects the whole fast path.
+ */
+public final class IcebergMetadataDeletePredicate {
+    private IcebergMetadataDeletePredicate() {
+    }
+
+    /**
+     * Returns the exact Iceberg predicate for {@code plan}, or empty when the 
plan is not provably a
+     * single-table DELETE whose complete predicate is representable.
+     */
+    public static Optional<org.apache.iceberg.expressions.Expression> build(
+            Table icebergTable, Plan plan, long targetTableId) {
+        List<Expression> conjuncts = new ArrayList<>();
+        if (!collectCompletePredicate(plan, targetTableId, conjuncts)) {
+            return Optional.empty();
+        }
+        if (conjuncts.isEmpty()) {
+            return Optional.of(Expressions.alwaysTrue());
+        }
+
+        Schema schema = icebergTable.schema();
+        Set<Integer> unsafeNanosFields = 
IcebergTimestampUtils.unsafeNanosFields(icebergTable, schema);
+        org.apache.iceberg.expressions.Expression result = null;
+        for (Expression conjunct : conjuncts) {
+            if (IcebergTimestampUtils.referencesUnsafe(conjunct, schema, 
unsafeNanosFields)) {
+                return Optional.empty();
+            }
+            Optional<org.apache.iceberg.expressions.Expression> converted =
+                    convertExact(conjunct, schema);
+            if (!converted.isPresent()) {
+                return Optional.empty();
+            }
+            result = result == null ? converted.get() : 
Expressions.and(result, converted.get());
+        }
+        return Optional.of(result);

Review Comment:
   [P2] Decline the shortcut when DATE literals cannot bind in Iceberg
   
   With BE `allow_zero_date=true`, a prepared `DELETE FROM t WHERE d = ?` on a 
nonempty table can supply `MYSQL_TYPE_DATE` with a four-byte year/month/day 
payload of `0/0/0`. `Literal.handleDateLiteral` preserves that value, producing 
this reduced analyzed tree:
   
   ```text
   IcebergDeleteSink
     Project(operation, row_id)
       Filter(d = DateV2Literal(0, 0, 0))
         LogicalFileScan(t)
   ```
   
   `extractDorisLiteral` returns `"0000-00-00"`, but the predicate is returned 
here without binding validation. Iceberg's [DATE literal 
binder](https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/api/src/main/java/org/apache/iceberg/expressions/Literals.java)
 calls `LocalDate.parse`, so whole-file preflight throws 
`DateTimeParseException`, outside the `ValidationException` fallback. The 
existing scan converter catches this binding failure and retains a BE residual, 
whose enabled zero-date parser accepts it. Validate the converted predicate 
against the retained schema before returning it and decline known 
conversion/binding failures; add the prepared all-zero DATE case. The 
zero-length wire encoding is already normalized and is unaffected.



##########
fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDelete.java:
##########
@@ -0,0 +1,397 @@
+// 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.datasource.iceberg;
+
+import org.apache.doris.common.UserException;
+import 
org.apache.doris.datasource.iceberg.IcebergExternalMetaCache.WritableTableLease;
+
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
+import org.apache.iceberg.BaseTable;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.DeleteFiles;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.HasTableOperations;
+import org.apache.iceberg.ManifestFile;
+import org.apache.iceberg.ManifestFiles;
+import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.SnapshotSummary;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.TableMetadataParser;
+import org.apache.iceberg.TableOperations;
+import org.apache.iceberg.TableScan;
+import org.apache.iceberg.encryption.EncryptionManager;
+import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.expressions.Evaluator;
+import org.apache.iceberg.expressions.Expression;
+import org.apache.iceberg.expressions.ExpressionUtil;
+import org.apache.iceberg.expressions.Projections;
+import org.apache.iceberg.expressions.StrictMetricsEvaluator;
+import org.apache.iceberg.io.CloseableIterable;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.io.LocationProvider;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.OptionalLong;
+import java.util.concurrent.ExecutorService;
+import java.util.function.BooleanSupplier;
+
+/**
+ * Whole-file metadata delete for Iceberg tables.
+ *
+ * <p>This path uses the existing Iceberg metadata and cache-generation 
machinery. Candidate files
+ * must all match in full; partial matches and existing delete files retain 
row-level DELETE.
+ * The final refresh selects the current snapshot, as in the source feature. 
Later snapshot changes
+ * decline the shortcut, while cancellation prevents publication of the 
pending delete.
+ */
+public final class IcebergMetadataDelete {
+    private static final Logger LOG = 
LogManager.getLogger(IcebergMetadataDelete.class);
+
+    private IcebergMetadataDelete() {
+    }
+
+    /**
+     * Attempts the fast path against a statement-bound table generation.
+     *
+     * @return the number of rows removed when committed, otherwise empty to 
run row-level DELETE
+     */
+    public static OptionalLong execute(IcebergExternalTable dorisTable, 
IcebergSnapshotCacheValue targetSnapshot,
+            Expression deleteExpression, BooleanSupplier isCancelled) throws 
UserException {
+        Table targetTable = targetSnapshot.getIcebergTable().orElseThrow(
+                () -> new UserException("Iceberg delete target metadata is not 
available"));
+        // HMS catalogs retain their Iceberg ops separately from their Hive 
metadata ops. Use the
+        // context pinned by analysis, so a catalog reinitialization cannot 
mix generations either.
+        IcebergRuntimeContext runtimeContext = 
Preconditions.checkNotNull(targetSnapshot.getRuntimeContext(),
+                "Iceberg delete target runtime context is not available");
+        IcebergMetadataOps expectedOps = runtimeContext.getMetadataOps();
+        try (WritableTableLease lease = 
IcebergUtils.acquireWritableIcebergTable(dorisTable, expectedOps)) {
+            Table writableTable = lease.getTable();
+            if (IcebergSnapshotCacheValue.isRetainedGeneration(targetTable)) {
+                writableTable = 
IcebergSnapshotCacheValue.createWritableTable(targetTable, writableTable);
+            }
+            Table table = writableTable;
+            return lease.getAuthenticator().execute(() -> executeOnTable(
+                    table, targetTable, 
lease.getOps().getThreadPoolWithPreAuth(),
+                    deleteExpression, isCancelled));
+        } catch (ValidationException e) {
+            LOG.info("Metadata delete of {} is no longer whole-file ({}); 
falling back.",
+                    dorisTable.getName(), e.getMessage());
+            return OptionalLong.empty();
+        } catch (UserException e) {
+            throw e;
+        } catch (Exception e) {
+            throw new UserException("Failed to metadata-delete Iceberg table "
+                    + dorisTable.getName() + ": " + e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Core operation over a loaded writable table. This remains separate from 
catalog acquisition so
+     * it can be exercised against an InMemoryCatalog in unit tests.
+     */
+    @VisibleForTesting
+    static OptionalLong executeOnTable(Table table, Table statementTable, 
ExecutorService executor,
+            Expression deleteExpression, BooleanSupplier isCancelled) throws 
UserException {
+        if (isCancelled.getAsBoolean()) {
+            return OptionalLong.empty();
+        }
+        if (!(table instanceof BaseTable)
+                || ((BaseTable) table).operations().current().formatVersion() 
< 2) {
+            return OptionalLong.empty();
+        }
+        validateTableIdentity(statementTable, table);
+
+        Snapshot base = table.currentSnapshot();
+        if (base == null || hasLiveDeleteFiles(table, base)) {
+            return OptionalLong.empty();
+        }
+
+        if (!matchesWholeFilesOnly(table, deleteExpression, executor) || 
isCancelled.getAsBoolean()) {
+            return OptionalLong.empty();
+        }
+
+        // Re-read immediately before commit. A racing writer can add a 
candidate file or a delete
+        // file; the required snapshot check below then aborts instead of 
changing the deleted set.
+        table.refresh();
+        validateTableIdentity(statementTable, table);
+        Snapshot refreshed = table.currentSnapshot();
+        if (refreshed == null || hasLiveDeleteFiles(table, refreshed)) {
+            return OptionalLong.empty();
+        }
+        long requiredSnapshotId = refreshed.snapshotId();

Review Comment:
   [P2] Recheck eligibility after selecting the refreshed snapshot
   
   For `DELETE ... WHERE id < 1`, a concurrent append between preflight and 
refresh can add **one manifest** containing a whole-match file (`min=max=0`) 
followed by a partial-match file (`min=0,max=2`). This line adopts that new 
snapshot, so the later snapshot fence accepts it.
   
   Iceberg 1.11's [manifest 
filter](https://github.com/apache/iceberg/blob/apache-iceberg-1.11.0/core/src/main/java/org/apache/iceberg/ManifestFilterManager.java)
 stops its initial scan at the whole match, opens a rewrite writer, then throws 
`ValidationException` on the partial file. It closes the writer before 
registering the output in `filteredManifests`; SDK cleanup only visits 
registered rewrites, leaving an orphan `.avro` when this helper falls back. The 
current failed-staging test adds a partial-only manifest and misses this 
failure within one rewrite. Pin the preflight snapshot or repeat whole-file 
eligibility against the refreshed snapshot before staging, and cover this 
mixed-manifest layout.



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