This is an automated email from the ASF dual-hosted git repository.
yiguolei pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/branch-4.2 by this push:
new 7c9bf309d4c branch-4.2: [feature](iceberg) Support whole-file metadata
delete for DELETE (#69176) (#70295)
7c9bf309d4c is described below
commit 7c9bf309d4c508cb973e6cd8c1e17359605ccefb
Author: daidai <[email protected]>
AuthorDate: Wed Dec 2 11:11:42 2026 +0800
branch-4.2: [feature](iceberg) Support whole-file metadata delete for
DELETE (#69176) (#70295)
pick #69176
Adapt the feature to branch-4.2's legacy Iceberg planner and metadata
stack without connector/SPI changes. Reuse statement-bound catalog
generations, writable leases and authenticated executors. Partial files,
unsupported predicates, v1 tables and existing delete files retain
row-level execution. FLOAT/DOUBLE value predicates also retain row-level
evaluation because the SDK and SQL differ on signed zero; NULL tests
remain eligible.
Use the existing analyzed literal conversion and atom-local NULL guards
for exact temporal and NULL semantics. Fence publication with the
required snapshot and the actual current metadata JSON, including Hadoop
same-version table recreation. A direct SDK delete update owns staging
cleanup on cancellation and known validation failures; unknown commit
outcomes propagate without fallback. Affected rows come from the
immutable metadata passed to the successful commit. When the final
metadata fence detects a changed statement-bound write identity, the SDK
cleans its tagged validation failure and the caller raises a
statement-retry error instead of falling back. SDK-native runtime
failures retain their existing conservative cleanup contract; a native
UUID-refresh rejection can leave unpublished metadata for separate
maintenance. Snapshot and partial-file validation retain row-level
fallback. Cancellation handoff to a late Coordinator is local to Iceberg
DELETE; ordinary StmtExecutor coordinator publication and forwarding of
cancel reasons retain the existing behavior.
The two existing regression matrices explicitly retain their row-level
coverage; golden files are unchanged. New FE unit coverage includes
v2/v3 whole-file and partition deletes, historical specs, exact
predicates, partial-file/delete-file fallback, temporal precision and
timezone handling, NULL partition ranges, signed zero, physical staging
cleanup, real HadoopCatalog table recreation, cancellation, concurrent
commits and unknown commit outcomes.
Validation: FE packaging via build.sh passed; seven changed Java files
passed Checkstyle; 55 focused FE tests (44 metadata/predicate cases, 9
command cases and 2 selected executor cases) passed via run-fe-ut.sh
using the freshly built local FE classes (skip.clean/maven.main.skip,
build cache disabled). External Iceberg SQL and Kerberos integration
regressions were not run locally.
---
.../datasource/iceberg/IcebergMetadataDelete.java | 398 +++++++
.../iceberg/IcebergMetadataDeletePredicate.java | 368 +++++++
.../doris/datasource/iceberg/IcebergUtils.java | 2 +-
.../trees/plans/commands/IcebergDeleteCommand.java | 100 +-
.../iceberg/IcebergMetadataDeleteTest.java | 1164 ++++++++++++++++++++
.../plans/commands/IcebergDeleteCommandTest.java | 49 +
.../java/org/apache/doris/qe/StmtExecutorTest.java | 32 +
...t_iceberg_delete_unpartitioned_evolution.groovy | 4 +-
.../test_iceberg_write_dml_modes_evolution.groovy | 4 +-
9 files changed, 2109 insertions(+), 12 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDelete.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDelete.java
new file mode 100644
index 00000000000..57c0f150cd0
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDelete.java
@@ -0,0 +1,398 @@
+// 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 preflight and the delete must use the same snapshot. A concurrent
snapshot change declines
+ * 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();
+ }
+
+ long requiredSnapshotId = base.snapshotId();
+ if (!matchesWholeFilesOnly(table, requiredSnapshotId,
deleteExpression, executor)
+ || isCancelled.getAsBoolean()) {
+ return OptionalLong.empty();
+ }
+
+ // Never stage against an uninspected manifest. A concurrent append
may contain both a
+ // whole-file match and a partial match that the SDK would discover
mid-rewrite.
+ table.refresh();
+ validateTableIdentity(statementTable, table);
+ Snapshot refreshed = table.currentSnapshot();
+ if (refreshed == null || refreshed.snapshotId() != requiredSnapshotId)
{
+ return OptionalLong.empty();
+ }
+
+ try {
+ // The SDK update owns cleanup directly. A discarded
BaseTransaction would only
+ // enqueue deletion of staged manifests, leaking them on
cancellation or validation.
+ TableOperations liveOperations =
IcebergSnapshotCacheValue.unwrapRetainedTableOperations(
+ ((BaseTable) table).operations());
+ RequiredSnapshotTableOperations operations = new
RequiredSnapshotTableOperations(
+ liveOperations, requiredSnapshotId, ((BaseTable)
table).operations().current(), isCancelled);
+ Table deleteTable = new BaseTable(operations, table.name(),
((BaseTable) table).reporter());
+ DeleteFiles deleteFiles = deleteTable.newDelete();
+ if (executor != null) {
+ deleteFiles = deleteFiles.scanManifestsWith(executor);
+ }
+ deleteFiles =
deleteFiles.caseSensitive(false).deleteFromRowFilter(deleteExpression);
+ if (isCancelled.getAsBoolean()) {
+ return OptionalLong.empty();
+ }
+ deleteFiles.commit();
+
+ // Read the immutable metadata passed to this successful CAS. The
live table can
+ // already contain another writer's snapshot when SDK post-commit
cleanup refreshes it.
+ Snapshot committed = operations.getCommittedSnapshot();
+ if (committed == null || committed.snapshotId() ==
requiredSnapshotId) {
+ return OptionalLong.of(0L);
+ }
+ return OptionalLong.of(deletedRowCount(committed));
+ } catch (WriteIdentityChangedException e) {
+ // The SDK has reclaimed this known-uncommitted update. Replanning
against a changed
+ // table identity would violate the statement's binding, so do not
use row-level DELETE.
+ throw new UserException("Iceberg write metadata changed for " +
table.name()
+ + " after the write was bound; retry the statement", e);
+ } catch (ValidationException e) {
+ // Nothing was committed. A snapshot change or a partial candidate
declines the shortcut.
+ LOG.info("Metadata delete of {} is no longer whole-file ({});
falling back.",
+ table.name(), e.getMessage());
+ return OptionalLong.empty();
+ }
+ }
+
+ /**
+ * Every candidate file returned by the same inclusive scan the statement
would use must satisfy
+ * its strict partition projection or the strict file-metrics evaluator.
+ */
+ private static boolean matchesWholeFilesOnly(
+ Table table, long snapshotId, Expression deleteExpression,
ExecutorService executor) {
+ boolean caseSensitive = false;
+ if (ExpressionUtil.selectsPartitions(deleteExpression, table,
caseSensitive)) {
+ return true;
+ }
+ TableScan scan = table.newScan().useSnapshot(snapshotId)
+ .filter(deleteExpression)
+ .caseSensitive(caseSensitive)
+ .includeColumnStats()
+ .ignoreResiduals();
+ if (executor != null) {
+ // Candidate planning can fan out as well as commit manifest
filtering. Both must use
+ // the pre-authenticated executor retained with this writable
table generation.
+ scan = scan.planWith(executor);
+ }
+ try (CloseableIterable<FileScanTask> tasks = scan.planFiles()) {
+ Map<Integer, Evaluator> partitionEvaluators = new HashMap<>();
+ StrictMetricsEvaluator metricsEvaluator =
+ new StrictMetricsEvaluator(table.schema(),
deleteExpression, caseSensitive);
+ for (FileScanTask task : tasks) {
+ DataFile file = task.file();
+ PartitionSpec spec = task.spec();
+ Evaluator evaluator =
partitionEvaluators.computeIfAbsent(spec.specId(), ignored ->
+ new Evaluator(spec.partitionType(),
+ Projections.strict(spec,
caseSensitive).project(deleteExpression)));
+ if (!evaluator.eval(file.partition()) &&
!metricsEvaluator.eval(file)) {
+ return false;
+ }
+ }
+ return true;
+ } catch (IOException e) {
+ LOG.warn("Failed to evaluate whole-file delete candidates for {}:
{}",
+ table.name(), e.getMessage());
+ return false;
+ }
+ }
+
+ private static boolean hasLiveDeleteFiles(Table table, Snapshot snapshot) {
+ try {
+ for (ManifestFile manifest : snapshot.deleteManifests(table.io()))
{
+ try (ManifestReader<DeleteFile> reader =
+ ManifestFiles.readDeleteManifest(manifest, table.io(),
table.specs())) {
+ if (reader.iterator().hasNext()) {
+ return true;
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ return false;
+ }
+
+ private static long deletedRowCount(Snapshot committed) {
+ if (committed == null || committed.summary() == null) {
+ return 0L;
+ }
+ Map<String, String> summary = committed.summary();
+ long deletedRecords = Long.parseLong(
+ summary.getOrDefault(SnapshotSummary.DELETED_RECORDS_PROP,
"0"));
+ long removedPositionDeletes = Long.parseLong(
+ summary.getOrDefault(SnapshotSummary.REMOVED_POS_DELETES_PROP,
"0"));
+ return Math.max(0L, deletedRecords - removedPositionDeletes);
+ }
+
+ private static void validateTableIdentity(Table expected, Table current)
throws UserException {
+ Preconditions.checkState(expected instanceof HasTableOperations,
+ "Iceberg delete target %s does not expose table operations",
expected.name());
+ Preconditions.checkState(current instanceof HasTableOperations,
+ "Iceberg commit table %s does not expose table operations",
current.name());
+ TableMetadata expectedMetadata = ((HasTableOperations)
expected).operations().current();
+ TableMetadata currentMetadata = ((HasTableOperations)
current).operations().current();
+ if (!sameWriteIdentity(expectedMetadata, currentMetadata)) {
+ throw new UserException("Iceberg write metadata changed after the
write was bound; "
+ + "retry the statement");
+ }
+ }
+
+ private static boolean sameWriteIdentity(TableMetadata expected,
TableMetadata current) {
+ return Objects.equals(expected.uuid(), current.uuid())
+ && expected.formatVersion() == current.formatVersion()
+ && expected.currentSchemaId() == current.currentSchemaId()
+ && expected.defaultSpecId() == current.defaultSpecId()
+ && expected.defaultSortOrderId() ==
current.defaultSortOrderId()
+ && Objects.equals(expected.location(), current.location())
+ && Objects.equals(expected.properties(), current.properties());
+ }
+
+ // ValidationException implements the SDK's CleanableFailure contract, so
staged manifests
+ // are reclaimed even when the catalog requires strict cleanup of known
failures only.
+ private static final class WriteIdentityChangedException extends
ValidationException {
+ private WriteIdentityChangedException() {
+ super("Iceberg write metadata changed since the metadata delete
preflight");
+ }
+ }
+
+ /**
+ * Fences the final CAS, including Iceberg retry replays, to the snapshot
inspected by the
+ * candidate preflight. This turns a concurrent append/delete into a safe
row-level fallback.
+ */
+ private static final class RequiredSnapshotTableOperations implements
TableOperations {
+ private final TableOperations delegate;
+ private final long requiredSnapshotId;
+ private final TableMetadata expectedMetadata;
+ private final BooleanSupplier isCancelled;
+ private Snapshot committedSnapshot;
+
+ private RequiredSnapshotTableOperations(TableOperations delegate, long
requiredSnapshotId,
+ TableMetadata expectedMetadata, BooleanSupplier isCancelled) {
+ this.delegate = delegate;
+ this.requiredSnapshotId = requiredSnapshotId;
+ this.expectedMetadata = expectedMetadata;
+ this.isCancelled = isCancelled;
+ }
+
+ @Override
+ public TableMetadata current() {
+ return delegate.current();
+ }
+
+ @Override
+ public TableMetadata refresh() {
+ if (committedSnapshot != null) {
+ // SnapshotProducer refreshes for best-effort cleanup after
its durable commit.
+ // Later changes or cancellation must not turn that success
into a fallback.
+ return delegate.refresh();
+ }
+ checkNotCancelled();
+ TableMetadata metadata = delegate.refresh();
+ checkMetadata(metadata);
+ return metadata;
+ }
+
+ @Override
+ public void commit(TableMetadata base, TableMetadata metadata) {
+ checkNotCancelled();
+ TableMetadata refreshed = Preconditions.checkNotNull(
+ delegate.refresh(), "Iceberg table metadata changed before
metadata delete");
+ String metadataFileLocation = Preconditions.checkNotNull(
+ refreshed.metadataFileLocation(), "Iceberg table has no
current metadata file");
+ // Hadoop refresh can reuse a cached object after DROP/recreate at
the same vN path.
+ // Match the existing writer fence by checking the actual current
JSON before the CAS.
+ checkMetadata(TableMetadataParser.read(delegate.io(),
metadataFileLocation));
+ checkNotCancelled();
+ delegate.commit(base, metadata);
+ committedSnapshot = metadata.currentSnapshot();
+ }
+
+ private Snapshot getCommittedSnapshot() {
+ return committedSnapshot;
+ }
+
+ private void checkNotCancelled() {
+ if (isCancelled.getAsBoolean()) {
+ // ValidationException is a known pre-commit failure: the SDK
reclaims the
+ // manifests it wrote. Unknown commit outcomes never enter
this cleanup path.
+ throw new ValidationException("Metadata delete was cancelled
before the remote commit");
+ }
+ }
+
+ private void checkMetadata(TableMetadata metadata) {
+ if (!sameWriteIdentity(expectedMetadata, metadata)) {
+ throw new WriteIdentityChangedException();
+ }
+ Snapshot snapshot = metadata.currentSnapshot();
+ if (snapshot == null || snapshot.snapshotId() !=
requiredSnapshotId) {
+ throw new ValidationException(
+ "Table changed since the metadata delete preflight;
retry the statement");
+ }
+ }
+
+ @Override
+ public FileIO io() {
+ return delegate.io();
+ }
+
+ @Override
+ public EncryptionManager encryption() {
+ return delegate.encryption();
+ }
+
+ @Override
+ public String metadataFileLocation(String fileName) {
+ return delegate.metadataFileLocation(fileName);
+ }
+
+ @Override
+ public LocationProvider locationProvider() {
+ return delegate.locationProvider();
+ }
+
+ @Override
+ public TableOperations temp(TableMetadata metadata) {
+ return delegate.temp(metadata);
+ }
+
+ @Override
+ public long newSnapshotId() {
+ return delegate.newSnapshotId();
+ }
+
+ @Override
+ public boolean requireStrictCleanup() {
+ return delegate.requireStrictCleanup();
+ }
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeletePredicate.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeletePredicate.java
new file mode 100644
index 00000000000..cfea02da8c2
--- /dev/null
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeletePredicate.java
@@ -0,0 +1,368 @@
+// 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());
+ }
+ // A Doris literal can be legal on the row path but fail to bind in
Iceberg (e.g. a zero DATE).
+ return Optional.ofNullable(IcebergUtils.checkConversion(result,
schema, true));
+ }
+
+ /**
+ * Walks the single-input analyzed plan and returns false as soon as a
node can change which
+ * target rows are produced without exposing that restriction as a
LogicalFilter.
+ */
+ private static boolean collectCompletePredicate(
+ Plan plan, long targetTableId, List<Expression> output) {
+ if (plan instanceof LogicalFilter) {
+ for (Expression conjunct : ((LogicalFilter<?>)
plan).getConjuncts()) {
+ if (!isExactPhysicalTargetPredicate(conjunct, targetTableId)) {
+ return false;
+ }
+ output.add(conjunct);
+ }
+ } else if (!(plan instanceof LogicalSink) && !(plan instanceof
LogicalProject)
+ && !(plan instanceof LogicalCheckPolicy) && !(plan instanceof
LogicalSubQueryAlias)
+ && !(plan instanceof LogicalCatalogRelation)) {
+ return false;
+ }
+
+ List<Plan> children = plan.children();
+ if (plan instanceof LogicalCatalogRelation) {
+ return children.isEmpty() && ((LogicalCatalogRelation)
plan).getTable().getId() == targetTableId;
+ }
+ if (children.size() != 1) {
+ return false;
+ }
+ return collectCompletePredicate(children.get(0), targetTableId,
output);
+ }
+
+ /**
+ * A conjunct must target only the DELETE table, use physical column
names, and contain no
+ * synthetic Iceberg metadata columns.
+ */
+ private static boolean isExactPhysicalTargetPredicate(Expression
predicate, long targetTableId) {
+ if (predicate == null) {
+ return false;
+ }
+ Set<Slot> slots = predicate.getInputSlots();
+ if (slots.isEmpty()) {
+ return false;
+ }
+ for (Slot slot : slots) {
+ if (!(slot instanceof SlotReference)) {
+ return false;
+ }
+ SlotReference reference = (SlotReference) slot;
+ Optional<TableIf> originalTable = reference.getOriginalTable();
+ if (!originalTable.isPresent() || originalTable.get().getId() !=
targetTableId) {
+ return false;
+ }
+ Optional<Column> originalColumn = reference.getOriginalColumn();
+ if (!originalColumn.isPresent() ||
!reference.getName().equals(originalColumn.get().getName())) {
+ return false;
+ }
+ if (Column.ICEBERG_ROWID_COL.equalsIgnoreCase(reference.getName())
+ ||
IcebergMetadataColumn.isMetadataColumn(reference.getName())
+ || !reference.getSubPath().isEmpty()) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private static Optional<org.apache.iceberg.expressions.Expression>
convertExact(
+ Expression expression, Schema schema) {
+ if (expression instanceof And) {
+ org.apache.iceberg.expressions.Expression combined = null;
+ for (Expression child : expression.children()) {
+ Optional<org.apache.iceberg.expressions.Expression> converted =
+ convertExact(child, schema);
+ if (!converted.isPresent()) {
+ return Optional.empty();
+ }
+ combined = combined == null ? converted.get()
+ : Expressions.and(combined, converted.get());
+ }
+ return combined == null ? Optional.empty() : Optional.of(combined);
+ }
+ if (expression instanceof Or) {
+ org.apache.iceberg.expressions.Expression combined = null;
+ for (Expression child : expression.children()) {
+ Optional<org.apache.iceberg.expressions.Expression> converted =
+ convertExact(child, schema);
+ if (!converted.isPresent()) {
+ return Optional.empty();
+ }
+ combined = combined == null ? converted.get()
+ : Expressions.or(combined, converted.get());
+ }
+ return combined == null ? Optional.empty() : Optional.of(combined);
+ }
+ if (expression instanceof Not) {
+ Expression child = ((Not) expression).child();
+ // Iceberg's notEqual/notIn match NULL while SQL NOT(UNKNOWN) does
not. IS NOT NULL is
+ // the only negation whose SQL semantics are preserved by this
conversion.
+ if (!(child instanceof IsNull)) {
+ return Optional.empty();
+ }
+ Optional<org.apache.iceberg.expressions.Expression> converted =
+ convertIsNull((IsNull) child, schema);
+ return converted.map(Expressions::not);
+ }
+ if (expression instanceof EqualTo
+ || expression instanceof GreaterThan
+ || expression instanceof GreaterThanEqual
+ || expression instanceof LessThan
+ || expression instanceof LessThanEqual) {
+ return convertComparison(expression, schema);
+ }
+ if (expression instanceof InPredicate) {
+ return convertIn((InPredicate) expression, schema);
+ }
+ if (expression instanceof IsNull) {
+ return convertIsNull((IsNull) expression, schema);
+ }
+ if (expression instanceof Between) {
+ return convertBetween((Between) expression, schema);
+ }
+ return Optional.empty();
+ }
+
+ private static Optional<org.apache.iceberg.expressions.Expression>
convertComparison(
+ Expression expression, Schema schema) {
+ Optional<NestedField> field = resolveSingleField(expression, schema);
+ if (!field.isPresent() || !isSupportedValueType(field.get().type())) {
+ return Optional.empty();
+ }
+
+ Expression left = expression.child(0);
+ Expression right = expression.child(1);
+ Literal literal;
+ boolean literalOnLeft;
+ if (left instanceof Slot && right instanceof Literal) {
+ literal = (Literal) right;
+ literalOnLeft = false;
+ } else if (left instanceof Literal && right instanceof Slot) {
+ literal = (Literal) left;
+ literalOnLeft = true;
+ } else {
+ return Optional.empty();
+ }
+ if (literal instanceof NullLiteral) {
+ // SQL `col = NULL` does not match rows; do not silently lower it
to IS NULL.
+ return Optional.empty();
+ }
+
+ // Use the same already-analyzed literal contract as scan predicates.
The maintenance
+ // helper has different timestamp precision/timezone semantics and is
not exact here.
+ Object value = IcebergUtils.extractDorisLiteral(field.get().type(),
literal.toLegacyLiteral());
+ if (value == null) {
+ return Optional.empty();
+ }
+
+ String columnName = field.get().name();
+ org.apache.iceberg.expressions.Expression comparison;
+ if (expression instanceof EqualTo) {
+ comparison = Expressions.equal(columnName, value);
+ } else if (expression instanceof GreaterThan) {
+ comparison = literalOnLeft
+ ? Expressions.lessThan(columnName, value)
+ : Expressions.greaterThan(columnName, value);
+ } else if (expression instanceof GreaterThanEqual) {
+ comparison = literalOnLeft
+ ? Expressions.lessThanOrEqual(columnName, value)
+ : Expressions.greaterThanOrEqual(columnName, value);
+ } else if (expression instanceof LessThan) {
+ comparison = literalOnLeft
+ ? Expressions.greaterThan(columnName, value)
+ : Expressions.lessThan(columnName, value);
+ } else if (expression instanceof LessThanEqual) {
+ comparison = literalOnLeft
+ ? Expressions.greaterThanOrEqual(columnName, value)
+ : Expressions.lessThanOrEqual(columnName, value);
+ } else {
+ return Optional.empty();
+ }
+ // Iceberg 1.11 partition residuals order NULL before non-NULL for
LT/LT_EQ. SQL
+ // comparisons exclude NULL; keep that condition inside each atom,
including OR arms.
+ return Optional.of(Expressions.and(Expressions.notNull(columnName),
comparison));
+ }
+
+ private static Optional<org.apache.iceberg.expressions.Expression>
convertIn(
+ InPredicate predicate, Schema schema) {
+ Optional<NestedField> field = resolveSingleField(predicate, schema);
+ if (!field.isPresent() || !isSupportedValueType(field.get().type())) {
+ return Optional.empty();
+ }
+ if (!(predicate.child(0) instanceof Slot) ||
predicate.optionsContainsNullLiteral()) {
+ return Optional.empty();
+ }
+
+ List<Object> values = new ArrayList<>();
+ for (int i = 1; i < predicate.children().size(); i++) {
+ Expression child = predicate.child(i);
+ if (!(child instanceof Literal)) {
+ return Optional.empty();
+ }
+ Object value =
IcebergUtils.extractDorisLiteral(field.get().type(), ((Literal)
child).toLegacyLiteral());
+ if (value == null) {
+ return Optional.empty();
+ }
+ values.add(value);
+ }
+ return values.isEmpty() ? Optional.empty()
+ : Optional.of(Expressions.in(field.get().name(), values));
+ }
+
+ private static Optional<org.apache.iceberg.expressions.Expression>
convertIsNull(
+ IsNull predicate, Schema schema) {
+ if (!(predicate.child() instanceof SlotReference)) {
+ return Optional.empty();
+ }
+ Optional<NestedField> field = resolveSingleField(predicate, schema);
+ if (!field.isPresent() || !isSupportedType(field.get().type())) {
+ return Optional.empty();
+ }
+ return Optional.of(Expressions.isNull(field.get().name()));
+ }
+
+ private static Optional<org.apache.iceberg.expressions.Expression>
convertBetween(
+ Between predicate, Schema schema) {
+ Optional<NestedField> field = resolveSingleField(predicate, schema);
+ if (!field.isPresent() || !isSupportedValueType(field.get().type())
+ || !(predicate.getCompareExpr() instanceof Slot)
+ || !(predicate.getLowerBound() instanceof Literal)
+ || !(predicate.getUpperBound() instanceof Literal)) {
+ return Optional.empty();
+ }
+ Object lower = IcebergUtils.extractDorisLiteral(
+ field.get().type(), ((Literal)
predicate.getLowerBound()).toLegacyLiteral());
+ Object upper = IcebergUtils.extractDorisLiteral(
+ field.get().type(), ((Literal)
predicate.getUpperBound()).toLegacyLiteral());
+ if (lower == null || upper == null) {
+ return Optional.empty();
+ }
+ return
Optional.of(Expressions.and(Expressions.notNull(field.get().name()),
Expressions.and(
+ Expressions.greaterThanOrEqual(field.get().name(), lower),
+ Expressions.lessThanOrEqual(field.get().name(), upper))));
+ }
+
+ private static Optional<NestedField> resolveSingleField(Expression
predicate, Schema schema) {
+ Set<Slot> slots = predicate.getInputSlots();
+ if (slots.size() != 1) {
+ return Optional.empty();
+ }
+ Slot slot = slots.iterator().next();
+ if (!(slot instanceof SlotReference)) {
+ return Optional.empty();
+ }
+ SlotReference reference = (SlotReference) slot;
+ if (!reference.getSubPath().isEmpty()
+ ||
Column.ICEBERG_ROWID_COL.equalsIgnoreCase(reference.getName())
+ ||
IcebergMetadataColumn.isMetadataColumn(reference.getName())) {
+ return Optional.empty();
+ }
+ return
Optional.ofNullable(schema.caseInsensitiveFindField(reference.getName()));
+ }
+
+ private static boolean isSupportedValueType(Type type) {
+ // Java/Iceberg distinguish signed zero in FLOAT/DOUBLE ordering while
Doris SQL
+ // treats both zeros as equal. Preserve row-level evaluation for these
value predicates.
+ return isSupportedType(type) && type.typeId() != Type.TypeID.FLOAT &&
type.typeId() != Type.TypeID.DOUBLE;
+ }
+
+ private static boolean isSupportedType(Type type) {
+ return type != null && !type.isStructType() && !type.isListType() &&
!type.isMapType()
+ && type.typeId() != Type.TypeID.UUID;
+ }
+}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
index 2923bba5d68..e37875287e8 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
@@ -512,7 +512,7 @@ public class IcebergUtils {
return schema.caseInsensitiveFindField(colName);
}
- private static Expression checkConversion(Expression expression, Schema
schema, boolean requireExact) {
+ static Expression checkConversion(Expression expression, Schema schema,
boolean requireExact) {
if (expression == null) {
return null;
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommand.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommand.java
index 347c3e654a9..ea5909f179f 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommand.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommand.java
@@ -19,16 +19,21 @@ package org.apache.doris.nereids.trees.plans.commands;
import org.apache.doris.analysis.StmtType;
import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.Env;
import org.apache.doris.catalog.TableIf;
+import org.apache.doris.common.UserException;
import org.apache.doris.common.util.Util;
import org.apache.doris.datasource.iceberg.IcebergConflictDetectionFilterUtils;
import org.apache.doris.datasource.iceberg.IcebergExternalDatabase;
import org.apache.doris.datasource.iceberg.IcebergExternalTable;
import org.apache.doris.datasource.iceberg.IcebergMergeOperation;
+import org.apache.doris.datasource.iceberg.IcebergMetadataDelete;
+import org.apache.doris.datasource.iceberg.IcebergMetadataDeletePredicate;
import org.apache.doris.datasource.iceberg.IcebergMvccSnapshot;
import org.apache.doris.datasource.iceberg.IcebergNereidsUtils;
import org.apache.doris.datasource.mvcc.MvccSnapshot;
import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerHook;
import org.apache.doris.nereids.analyzer.UnboundAlias;
import org.apache.doris.nereids.analyzer.UnboundSlot;
import org.apache.doris.nereids.exceptions.AnalysisException;
@@ -58,10 +63,14 @@ import org.apache.doris.qe.StmtExecutor;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import org.apache.iceberg.Table;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
import java.util.List;
import java.util.Optional;
+import java.util.OptionalLong;
import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
/**
* DELETE command for Iceberg tables.
@@ -78,6 +87,7 @@ import java.util.concurrent.Callable;
* 3. Commit the DeleteFile to Iceberg table using RowDelta API
*/
public class IcebergDeleteCommand extends Command implements ForwardWithSync,
Explainable {
+ private static final Logger LOG =
LogManager.getLogger(IcebergDeleteCommand.class);
protected final List<String> nameParts;
protected final String tableAlias;
@@ -131,12 +141,20 @@ public class IcebergDeleteCommand extends Command
implements ForwardWithSync, Ex
long previousTargetTableId = ctx.getIcebergRowIdTargetTableId();
ctx.setIcebergRowIdTargetTableId(icebergTable.getId());
try {
- LogicalPlan deleteQueryPlan = completeQueryPlan(ctx, logicalQuery,
icebergTable);
+ Optional<MvccSnapshot> targetSnapshot = loadTargetSnapshot(ctx,
icebergTable);
+ Table targetIcebergTable = loadTargetIcebergTable(targetSnapshot);
+ LogicalPlan deleteQueryPlan = completeQueryPlan(
+ ctx, logicalQuery, icebergTable, targetSnapshot,
targetIcebergTable);
executeWithExternalTableBatchModeDisabled(ctx, () -> {
// Create planner and plan the delete operation
NereidsPlanner planner = new
NereidsPlanner(ctx.getStatementContext());
LogicalPlanAdapter logicalPlanAdapter =
new LogicalPlanAdapter(deleteQueryPlan,
ctx.getStatementContext());
+ boolean tryMetadataDelete = partitions.isEmpty() &&
!isTempPart;
+ AtomicReference<Plan> analyzedPlan = new AtomicReference<>();
+ if (tryMetadataDelete) {
+ captureAnalyzedPlan(ctx, analyzedPlan);
+ }
// Plan the delete query to generate physical plan and
distributed plan
planner.plan(logicalPlanAdapter,
ctx.getSessionVariable().toThrift());
@@ -144,6 +162,25 @@ public class IcebergDeleteCommand extends Command
implements ForwardWithSync, Ex
// Set planner in executor for later use
executor.setPlanner(planner);
executor.checkBlockRules();
+
+ if (tryMetadataDelete) {
+ throwIfCancelled(executor, ctx);
+ Optional<org.apache.iceberg.expressions.Expression>
deleteExpression =
+ IcebergMetadataDeletePredicate.build(
+ targetIcebergTable, analyzedPlan.get(),
icebergTable.getId());
+ if (deleteExpression.isPresent()) {
+ OptionalLong deletedRows =
IcebergMetadataDelete.execute(
+ icebergTable, ((IcebergMvccSnapshot)
targetSnapshot.get()).getSnapshotCacheValue(),
+ deleteExpression.get(),
+ () -> executor.getPendingCancelReason() !=
null || ctx.isKilled());
+ if (deletedRows.isPresent()) {
+ reportMetadataDelete(ctx, icebergTable,
deletedRows.getAsLong());
+ return null;
+ }
+ }
+ throwIfCancelled(executor, ctx);
+ }
+
Optional<org.apache.iceberg.expressions.Expression>
conflictFilter =
IcebergConflictDetectionFilterUtils.buildConflictDetectionFilter(
planner.getAnalyzedPlan(), icebergTable);
@@ -202,13 +239,9 @@ public class IcebergDeleteCommand extends Command
implements ForwardWithSync, Ex
* Select $row_id (file_path, row_position, partition info).
*/
private LogicalPlan completeQueryPlan(ConnectContext ctx, LogicalPlan
logicalQuery,
- IcebergExternalTable icebergTable) {
- Optional<MvccSnapshot> targetSnapshot = ctx.getStatementContext()
- .loadSnapshots(icebergTable, Optional.empty(),
Optional.empty());
- Table targetIcebergTable = ((IcebergMvccSnapshot)
targetSnapshot.orElseThrow(
- () -> new AnalysisException("Iceberg delete target snapshot is
not available")))
- .getSnapshotCacheValue().getIcebergTable().orElseThrow(
- () -> new AnalysisException("Iceberg delete target
metadata is not available"));
+ IcebergExternalTable icebergTable,
+ Optional<MvccSnapshot> targetSnapshot,
+ Table targetIcebergTable) {
LogicalPlan queryPlan = buildPositionDeletePlan(ctx, logicalQuery,
icebergTable);
// Convert output to NamedExpression list
@@ -240,6 +273,19 @@ public class IcebergDeleteCommand extends Command
implements ForwardWithSync, Ex
return deleteSink;
}
+ private Optional<MvccSnapshot> loadTargetSnapshot(
+ ConnectContext ctx, IcebergExternalTable icebergTable) {
+ return ctx.getStatementContext()
+ .loadSnapshots(icebergTable, Optional.empty(),
Optional.empty());
+ }
+
+ private Table loadTargetIcebergTable(Optional<MvccSnapshot>
targetSnapshot) {
+ return ((IcebergMvccSnapshot) targetSnapshot.orElseThrow(
+ () -> new AnalysisException("Iceberg delete target snapshot is
not available")))
+ .getSnapshotCacheValue().getIcebergTable().orElseThrow(
+ () -> new AnalysisException("Iceberg delete target
metadata is not available"));
+ }
+
/**
* Build query plan for position delete.
* Add $row_id column to select list.
@@ -301,12 +347,48 @@ public class IcebergDeleteCommand extends Command
implements ForwardWithSync, Ex
long previousTargetTableId = ctx.getIcebergRowIdTargetTableId();
ctx.setIcebergRowIdTargetTableId(table.getId());
try {
- return completeQueryPlan(ctx, logicalQuery, icebergTable);
+ Optional<MvccSnapshot> targetSnapshot = loadTargetSnapshot(ctx,
icebergTable);
+ Table targetIcebergTable = loadTargetIcebergTable(targetSnapshot);
+ return completeQueryPlan(
+ ctx, logicalQuery, icebergTable, targetSnapshot,
targetIcebergTable);
} finally {
ctx.setIcebergRowIdTargetTableId(previousTargetTableId);
}
}
+ @VisibleForTesting
+ static void captureAnalyzedPlan(ConnectContext ctx, AtomicReference<Plan>
analyzedPlan) {
+ ctx.getStatementContext().addPlannerHook(new PlannerHook() {
+ @Override
+ public void afterAnalyze(NereidsPlanner planner) {
+
analyzedPlan.set(planner.getCascadesContext().getRewritePlan());
+ }
+ });
+ }
+
+ @VisibleForTesting
+ static void throwIfCancelled(StmtExecutor executor, ConnectContext ctx)
throws UserException {
+ if (executor.getPendingCancelReason() != null) {
+ throw new
UserException(executor.getPendingCancelReason().getErrorMsg());
+ }
+ if (ctx.isKilled()) {
+ throw new UserException("query was cancelled");
+ }
+ }
+
+ private static void reportMetadataDelete(
+ ConnectContext ctx, IcebergExternalTable table, long deletedRows) {
+ ctx.getState().setOk(deletedRows, 0, "{'status':'COMMITTED'}");
+ ctx.updateReturnRows((int) deletedRows);
+ try {
+
Env.getCurrentEnv().getRefreshManager().refreshTableAfterCommit(table);
+ } catch (Exception e) {
+ // The remote delete is already durable. A refresh failure must
not make the client retry it.
+ LOG.warn("Post-commit refresh failed for table {}. Data was
committed successfully.",
+ table.getName(), e);
+ }
+ }
+
@Override
public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
return visitor.visitCommand(this, context);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeleteTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeleteTest.java
new file mode 100644
index 00000000000..3392daa1a86
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergMetadataDeleteTest.java
@@ -0,0 +1,1164 @@
+// 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.MysqlColType;
+import org.apache.doris.catalog.TableIf;
+import org.apache.doris.common.UserException;
+import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
+import
org.apache.doris.datasource.iceberg.IcebergExternalMetaCache.WritableTableLease;
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Add;
+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.StatementScopeIdGenerator;
+import org.apache.doris.nereids.trees.expressions.literal.DateTimeV2Literal;
+import org.apache.doris.nereids.trees.expressions.literal.DoubleLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.FloatLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.expressions.literal.Literal;
+import org.apache.doris.nereids.trees.expressions.literal.TimestampTzLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.RelationId;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCatalogRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
+import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.DateTimeV2Type;
+import org.apache.doris.nereids.types.DateV2Type;
+import org.apache.doris.nereids.types.DoubleType;
+import org.apache.doris.nereids.types.FloatType;
+import org.apache.doris.nereids.types.IntegerType;
+import org.apache.doris.nereids.types.TimeStampTzType;
+import org.apache.doris.qe.ConnectContext;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.iceberg.BaseTable;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.DataFiles;
+import org.apache.iceberg.DeleteFile;
+import org.apache.iceberg.FileFormat;
+import org.apache.iceberg.FileMetadata;
+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.Metrics;
+import org.apache.iceberg.PartitionData;
+import org.apache.iceberg.PartitionSpec;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.Snapshot;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableMetadata;
+import org.apache.iceberg.TableOperations;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.CommitStateUnknownException;
+import org.apache.iceberg.exceptions.NotFoundException;
+import org.apache.iceberg.expressions.ExpressionUtil;
+import org.apache.iceberg.expressions.Expressions;
+import org.apache.iceberg.hadoop.HadoopCatalog;
+import org.apache.iceberg.inmemory.InMemoryCatalog;
+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.types.Conversions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.AdditionalAnswers;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalLong;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+/**
+ * Pins the branch-4.2 whole-file metadata-delete path and its strict plan
extraction.
+ */
+public class IcebergMetadataDeleteTest {
+ private static final TableIdentifier TABLE_ID = TableIdentifier.of("db1",
"t1");
+ private static final long DORIS_TARGET_ID = 100L;
+ private static final Schema SCHEMA = new Schema(
+ Types.NestedField.required(1, "id", Types.IntegerType.get()),
+ Types.NestedField.optional(2, "region", Types.StringType.get()));
+
+ @ParameterizedTest
+ @ValueSource(strings = {"2", "3"})
+ public void wholePartitionDeleteDropsMatchingFilesOnly(String
formatVersion) throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec =
PartitionSpec.builderFor(SCHEMA).identity("region").build();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", formatVersion));
+ table.newAppend()
+ .appendFile(partitionedDataFile(
+ spec, "s3://b/db1/t1/region=us/a.parquet", 10L,
"region=us"))
+ .appendFile(partitionedDataFile(
+ spec, "s3://b/db1/t1/region=us/b.parquet", 10L,
"region=us"))
+ .appendFile(partitionedDataFile(
+ spec, "s3://b/db1/t1/region=eu/c.parquet", 20L,
"region=eu"))
+ .commit();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.equal("region", "us"), () ->
false);
+
+ Assertions.assertEquals(OptionalLong.of(20L), deleted);
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/region=eu/c.parquet"),
+ dataFilePaths(reload(catalog)));
+ Assertions.assertEquals(0, liveDeleteFileCount(reload(catalog)));
+ }
+
+ @Test
+ public void wholePartitionDeleteCoversHistoricalSpecs() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec originalSpec =
PartitionSpec.builderFor(SCHEMA).identity("region").build();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, originalSpec,
props("format-version", "2"));
+ table.newAppend()
+ .appendFile(partitionedDataFile(
+ originalSpec, "s3://b/db1/t1/old-us.parquet", 10L,
"region=us"))
+ .appendFile(partitionedDataFile(
+ originalSpec, "s3://b/db1/t1/old-eu.parquet", 20L,
"region=eu"))
+ .commit();
+ table.updateSpec().addField("id").commit();
+ table.newAppend().appendFile(partitionedDataFile(
+ table.spec(), "s3://b/db1/t1/new-us.parquet", 5L,
"region=us/id=1")).commit();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.equal("region", "us"), () ->
false);
+
+ Assertions.assertEquals(OptionalLong.of(15L), deleted);
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/old-eu.parquet"),
+ dataFilePaths(reload(catalog)));
+ }
+
+ @Test
+ public void unfilteredDeleteRemovesEveryFile() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend()
+ .appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet", 10L))
+ .appendFile(dataFile(spec, "s3://b/db1/t1/b.parquet", 5L))
+ .commit();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.alwaysTrue(), () -> false);
+
+ Assertions.assertEquals(OptionalLong.of(15L), deleted);
+ Assertions.assertTrue(dataFilePaths(reload(catalog)).isEmpty());
+ }
+
+ @Test
+ public void partialMatchFallsBackWithoutCommitting() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.greaterThan("id", 5), () ->
false);
+
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertEquals(snapshotBefore,
reload(catalog).currentSnapshot().snapshotId());
+ }
+
+ @Test
+ public void existingDeleteFilesFallBackToTheRowLevelPath() throws
Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec =
PartitionSpec.builderFor(SCHEMA).identity("region").build();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "3"));
+ DataFile dataFile = partitionedDataFile(
+ spec, "s3://b/db1/t1/region=us/a.parquet", 10L, "region=us");
+ table.newAppend().appendFile(dataFile).commit();
+ table.newRowDelta().addDeletes(
+ deletionVector(spec, "s3://b/db1/t1/dv.puffin", dataFile,
3L)).commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.equal("region", "us"), () ->
false);
+
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertEquals(snapshotBefore,
reload(catalog).currentSnapshot().snapshotId());
+ Assertions.assertEquals(1,
+ attachedDeleteFileCount(reload(catalog),
dataFile.path().toString()));
+ }
+
+ @Test
+ public void wholeFileMetricsDeleteKeepsNonmatchingFiles() throws Exception
{
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend()
+ .appendFile(dataFileWithId(spec, "s3://b/db1/t1/a.parquet",
10L, 0))
+ .appendFile(dataFileWithId(spec, "s3://b/db1/t1/b.parquet",
5L, 2))
+ .commit();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new LogicalFilter<>(ImmutableSet.of(new LessThan(new
IntegerLiteral(1), id)),
+ new TargetScan(target, ImmutableList.of(id)));
+ org.apache.iceberg.expressions.Expression predicate =
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).get();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, predicate, () -> false);
+
+ Assertions.assertEquals(OptionalLong.of(5L), deleted);
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/a.parquet"),
+ dataFilePaths(reload(catalog)));
+ Assertions.assertEquals(0, liveDeleteFileCount(reload(catalog)));
+ }
+
+ @Test
+ public void schemaRebindRejectsTheStatementGeneration() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ Table statementTable = reload(catalog);
+ statementTable.schema();
+ table.updateSchema().renameColumn("id", "renamed_id").commit();
+
+ Assertions.assertThrows(UserException.class, () ->
IcebergMetadataDelete.executeOnTable(
+ table, statementTable, null, Expressions.alwaysTrue(), () ->
false));
+ Assertions.assertEquals(1, dataFilePaths(reload(catalog)).size());
+ }
+
+ @Test
+ public void cancelledDeleteDoesNotCommit() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend()
+ .appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet", 10L))
+ .appendFile(dataFile(spec, "s3://b/db1/t1/b.parquet", 5L))
+ .commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.alwaysTrue(), () -> true);
+
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertEquals(snapshotBefore,
reload(catalog).currentSnapshot().snapshotId());
+ Assertions.assertEquals(2, dataFilePaths(reload(catalog)).size());
+ }
+
+ @Test
+ public void cancellationAfterStagingCleansUncommittedMetadata() throws
Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+ TrackingFileIO io = new TrackingFileIO(table.io());
+ Table tracked = tableWithFileIO(table, io);
+ AtomicBoolean cancelled = new AtomicBoolean();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ tracked, table, null, Expressions.alwaysTrue(), () -> {
+ // Deliver cancellation after the SDK has physically
written staging metadata,
+ // independently of the number of cancellation checks in
the implementation.
+ if (io.hasCreatedFile()) {
+ cancelled.set(true);
+ }
+ return cancelled.get();
+ });
+
+ Assertions.assertTrue(cancelled.get());
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertFalse(io.createdFiles.isEmpty(), "the cancellation
must follow real staging");
+ Assertions.assertTrue(io.existingCreatedFiles().isEmpty(), "staged
metadata must be reclaimed");
+ Assertions.assertEquals(snapshotBefore,
reload(catalog).currentSnapshot().snapshotId());
+ Assertions.assertEquals(1, dataFilePaths(reload(catalog)).size());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"property", "schema", "spec"})
+ public void
identityChangeAfterStagingFailsWithoutFallbackAndCleansMetadata(String change)
throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+ TrackingFileIO io = new TrackingFileIO(table.io());
+ Table tracked = tableWithFileIO(table, io);
+ // Exercise catalogs that reclaim artifacts only for the SDK's
CleanableFailure contract.
+ Mockito.when(((HasTableOperations)
tracked).operations().requireStrictCleanup()).thenReturn(true);
+ AtomicBoolean changed = new AtomicBoolean();
+
+ UserException exception = Assertions.assertThrows(UserException.class,
+ () -> IcebergMetadataDelete.executeOnTable(tracked, table,
null, Expressions.alwaysTrue(), () -> {
+ if (io.hasCreatedFile() && changed.compareAndSet(false,
true)) {
+ Table concurrent = reload(catalog);
+ switch (change) {
+ case "property":
+ concurrent.updateProperties().set("comment",
"concurrent update").commit();
+ break;
+ case "schema":
+ concurrent.updateSchema().addColumn("new_col",
Types.IntegerType.get()).commit();
+ break;
+ case "spec":
+
concurrent.updateSpec().addField("region").commit();
+ break;
+ default:
+ throw new AssertionError("unknown metadata
change: " + change);
+ }
+ Assertions.assertEquals(snapshotBefore,
concurrent.currentSnapshot().snapshotId());
+ }
+ return false;
+ }));
+
+ Assertions.assertTrue(exception.getMessage().contains("retry the
statement"));
+ Assertions.assertTrue(changed.get());
+ Assertions.assertFalse(io.createdFiles.isEmpty(), "the identity change
must follow real staging");
+ Assertions.assertTrue(io.existingCreatedFiles().isEmpty(), "staged
metadata must be reclaimed");
+ Table current = reload(catalog);
+ Assertions.assertEquals(snapshotBefore,
current.currentSnapshot().snapshotId());
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/a.parquet"),
dataFilePaths(current));
+ switch (change) {
+ case "property":
+ Assertions.assertEquals("concurrent update",
current.properties().get("comment"));
+ break;
+ case "schema":
+
Assertions.assertNotNull(current.schema().findField("new_col"));
+ break;
+ case "spec":
+ Assertions.assertEquals("region",
current.spec().fields().get(0).name());
+ break;
+ default:
+ throw new AssertionError("unknown metadata change: " + change);
+ }
+ }
+
+ @Test
+ public void concurrentMixedManifestFallsBackBeforeStaging() throws
Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFileWithId(spec,
"s3://b/db1/t1/base.parquet", 10L, 0)).commit();
+ Table statementTable =
IcebergSnapshotCacheValue.retainTableGeneration(table);
+ TableOperations realOps = ((HasTableOperations) table).operations();
+ TrackingFileIO io = new TrackingFileIO(table.io());
+ TableOperations racingOps = operationsWithFileIO(realOps, io);
+ AtomicBoolean appended = new AtomicBoolean();
+ Mockito.doAnswer(invocation -> {
+ if (appended.compareAndSet(false, true)) {
+ Table current = reload(catalog);
+ current.newFastAppend()
+ .appendFile(dataFileWithId(spec,
"s3://b/db1/t1/whole.parquet", 5L, 0))
+ .appendFile(dataFileWithBounds(spec,
+ "s3://b/db1/t1/partial.parquet", 2L,
Types.IntegerType.get(), 0, 2))
+ .commit();
+ Snapshot snapshot = current.currentSnapshot();
+ ManifestFile added =
snapshot.dataManifests(current.io()).stream()
+ .filter(manifest -> manifest.snapshotId() ==
snapshot.snapshotId())
+ .findFirst().get();
+ Assertions.assertEquals(2, added.addedFilesCount().intValue());
+ }
+ return realOps.refresh();
+ }).when(racingOps).refresh();
+ Table racingTable = new BaseTable(racingOps, table.name());
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ racingTable, statementTable, null, Expressions.lessThan("id",
1), () -> false);
+
+ Assertions.assertTrue(appended.get());
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertTrue(io.createdFiles.isEmpty(), "an uninspected
snapshot must not start a manifest rewrite");
+ Table current = reload(catalog);
+ Assertions.assertEquals("append",
current.currentSnapshot().operation());
+ Assertions.assertEquals(3, dataFilePaths(current).size());
+ }
+
+ @Test
+ public void hadoopSameVersionRecreationCannotReplaceTheNewTable(@TempDir
Path warehouse) throws Exception {
+ Configuration configuration = new Configuration();
+ configuration.set("fs.defaultFS", "file:///");
+ try (HadoopCatalog catalog = new HadoopCatalog(configuration,
warehouse.toUri().toString())) {
+ catalog.createNamespace(Namespace.of("db1"));
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec,
warehouse.resolve("old.parquet").toString(), 10L)).commit();
+ Table statementTable =
IcebergSnapshotCacheValue.retainTableGeneration(table);
+ TrackingFileIO io = new TrackingFileIO(table.io());
+ Table writableTable =
IcebergSnapshotCacheValue.createWritableTable(
+ statementTable, tableWithFileIO(table, io));
+ String oldUuid = ((HasTableOperations)
table).operations().current().uuid();
+ AtomicReference<String> replacementUuid = new AtomicReference<>();
+ AtomicBoolean recreated = new AtomicBoolean();
+ String replacementPath =
warehouse.resolve("replacement.parquet").toString();
+
+ UserException exception =
Assertions.assertThrows(UserException.class,
+ () -> IcebergMetadataDelete.executeOnTable(
+ writableTable, statementTable, null,
Expressions.alwaysTrue(), () -> {
+ if (io.hasCreatedFile() &&
recreated.compareAndSet(false, true)) {
+ // Replacement completes after staging,
before final validation.
+ // Both end at v2, so SDK refresh alone is
stale.
+
Assertions.assertTrue(catalog.dropTable(TABLE_ID, true));
+ Table replacement = catalog.createTable(
+ TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ replacement.newAppend().appendFile(
+ dataFile(spec, replacementPath,
5L)).commit();
+ replacementUuid.set(((HasTableOperations)
replacement)
+ .operations().current().uuid());
+ Assertions.assertNotEquals(oldUuid,
replacementUuid.get());
+
Assertions.assertTrue(((HasTableOperations) replacement).operations().current()
+
.metadataFileLocation().endsWith("v2.metadata.json"));
+ }
+ return false;
+ }));
+
+ Assertions.assertTrue(recreated.get());
+ Assertions.assertTrue(exception.getMessage().contains("retry the
statement"));
+ Table replacement = catalog.loadTable(TABLE_ID);
+ Assertions.assertEquals(replacementUuid.get(),
+ ((HasTableOperations)
replacement).operations().current().uuid());
+
Assertions.assertEquals(Collections.singletonList(replacementPath),
dataFilePaths(replacement));
+ }
+ }
+
+ @Test
+ public void noMatchAfterADeleteReportsZeroInsteadOfThePreviousSummary()
throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend()
+ .appendFile(dataFileWithId(spec,
"s3://b/db1/t1/match.parquet", 10L, 0))
+ .appendFile(dataFileWithId(spec,
"s3://b/db1/t1/other.parquet", 5L, 2))
+ .commit();
+
+ Assertions.assertEquals(OptionalLong.of(10L),
IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.equal("id", 0), () -> false));
+ Assertions.assertEquals(OptionalLong.of(0L),
IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.equal("id", 0), () -> false));
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/other.parquet"),
+ dataFilePaths(reload(catalog)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"false,comparison", "false,in", "false,between",
"true,comparison", "true,in", "true,between"})
+ public void temporalPredicatesPreserveSqlFileSelection(boolean zoned,
String kind) throws Exception {
+ ConnectContext previous = ConnectContext.get();
+ ConnectContext context = new ConnectContext();
+ context.getSessionVariable().setTimeZone("+08:00");
+ context.setThreadLocalInfo();
+ try {
+ Type fieldType = zoned ? Types.TimestampType.withZone() :
Types.TimestampType.withoutZone();
+ DataType sqlType = zoned ? TimeStampTzType.of(6) :
DateTimeV2Type.of(6);
+ Schema schema = new Schema(Types.NestedField.optional(1, "ts",
fieldType));
+ InMemoryCatalog catalog = freshCatalog();
+ Table table = catalog.createTable(
+ TABLE_ID, schema, PartitionSpec.unpartitioned(),
props("format-version", "2"));
+ IcebergExternalTable target = targetTable();
+ SlotReference ts = slot(target, "ts", sqlType);
+ String threshold = zoned ? "2026-01-01 08:00:00.000001" :
"2026-01-01 00:00:00.500001";
+ Literal literal = temporalLiteral(zoned, threshold);
+ Expression sqlPredicate;
+ String fileInstant;
+ switch (kind) {
+ case "comparison":
+ sqlPredicate = zoned ? new GreaterThan(ts, literal) : new
LessThan(ts, literal);
+ fileInstant = zoned ? "2025-12-31T20:00:00.000001Z" :
"2026-01-01T00:00:00.750000Z";
+ break;
+ case "in":
+ sqlPredicate = new InPredicate(ts,
ImmutableList.of(literal));
+ fileInstant = zoned ? "2025-12-31T16:00:00.000001Z" :
"2026-01-01T00:00:01.000001Z";
+ break;
+ case "between":
+ Literal lower = temporalLiteral(zoned,
+ zoned ? threshold : "2026-01-01 00:00:00.000001");
+ Literal upper = temporalLiteral(zoned,
+ zoned ? "2026-01-01 08:00:01.000001" : threshold);
+ sqlPredicate = new Between(ts, lower, upper);
+ fileInstant = zoned ? "2025-12-31T16:00:00.500000Z" :
"2026-01-01T00:00:00.750000Z";
+ break;
+ default:
+ throw new AssertionError(kind);
+ }
+ String path = "s3://b/db1/t1/temporal.parquet";
+ // These values are outside the SQL predicate. Encode file metrics
independently
+ // from Doris literal conversion so a shared encoding bug cannot
make the oracle pass.
+ Instant instant = Instant.parse(fileInstant);
+ long value = instant.getEpochSecond() * 1_000_000L +
instant.getNano() / 1000L;
+ table.newAppend().appendFile(dataFileWithBounds(table.spec(),
path, 3L, fieldType, value, value)).commit();
+ org.apache.iceberg.expressions.Expression predicate =
exactPredicate(table, target, ts, sqlPredicate);
+
+ Assertions.assertEquals(OptionalLong.of(0L),
IcebergMetadataDelete.executeOnTable(
+ table, table, null, predicate, () -> false));
+ Assertions.assertEquals(Collections.singletonList(path),
dataFilePaths(reload(catalog)));
+ } finally {
+ if (previous == null) {
+ ConnectContext.remove();
+ } else {
+ previous.setThreadLocalInfo();
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"lt", "le", "left_lt", "left_le", "or_null"})
+ public void nullableRangesKeepSqlNullSemanticsInMixedManifests(String
kind) throws Exception {
+ Schema schema = new Schema(Types.NestedField.optional(1, "p",
Types.IntegerType.get()));
+ PartitionSpec spec =
PartitionSpec.builderFor(schema).identity("p").build();
+ InMemoryCatalog catalog = freshCatalog();
+ Table table = catalog.createTable(TABLE_ID, schema, spec,
props("format-version", "2"));
+ String nullPath = "s3://b/db1/t1/a-null.parquet";
+ String matchPath = "s3://b/db1/t1/b-match.parquet";
+ String otherPath = "s3://b/db1/t1/c-other.parquet";
+ table.newAppend()
+ .appendFile(dataFileInPartition(spec, nullPath, 2L, null))
+ .appendFile(dataFileInPartition(spec, matchPath, 3L, 1))
+ .appendFile(dataFileInPartition(spec, otherPath, 5L, 3))
+ .commit();
+ Assertions.assertEquals(1,
table.currentSnapshot().dataManifests(table.io()).size(),
+ "the NULL and non-NULL partitions must share a manifest");
+ IcebergExternalTable target = targetTable();
+ SlotReference partition = slot(target, "p", IntegerType.INSTANCE);
+ Expression sqlPredicate;
+ switch (kind) {
+ case "lt":
+ sqlPredicate = new LessThan(partition, new IntegerLiteral(2));
+ break;
+ case "le":
+ sqlPredicate = new LessThanEqual(partition, new
IntegerLiteral(1));
+ break;
+ case "left_lt":
+ sqlPredicate = new GreaterThan(new IntegerLiteral(2),
partition);
+ break;
+ case "left_le":
+ sqlPredicate = new GreaterThanEqual(new IntegerLiteral(1),
partition);
+ break;
+ case "or_null":
+ sqlPredicate = new Or(new LessThan(partition, new
IntegerLiteral(2)), new IsNull(partition));
+ break;
+ default:
+ throw new AssertionError(kind);
+ }
+ org.apache.iceberg.expressions.Expression predicate =
exactPredicate(table, target, partition, sqlPredicate);
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(table,
table, null, predicate, () -> false);
+
+ boolean includesNull = kind.equals("or_null");
+ Assertions.assertEquals(OptionalLong.of(includesNull ? 5L : 3L),
deleted);
+ List<String> expected = includesNull
+ ? Collections.singletonList(otherPath) :
ImmutableList.of(nullPath, otherPath);
+ Assertions.assertEquals(expected, dataFilePaths(reload(catalog)));
+ }
+
+ @ParameterizedTest
+ @CsvSource({"float,-0.0", "float,0.0", "double,-0.0", "double,0.0"})
+ public void floatingValuePredicatesKeepTheRowLevelPath(String kind, String
zero) throws Exception {
+ Type fieldType;
+ DataType sqlType;
+ Object value;
+ Literal literal;
+ if (kind.equals("float")) {
+ fieldType = Types.FloatType.get();
+ sqlType = FloatType.INSTANCE;
+ value = Float.valueOf(zero);
+ literal = new FloatLiteral(0.0f);
+ } else {
+ fieldType = Types.DoubleType.get();
+ sqlType = DoubleType.INSTANCE;
+ value = Double.valueOf(zero);
+ literal = new DoubleLiteral(0.0d);
+ }
+ Assertions.assertFalse(((Number) value).doubleValue() < 0.0d, "both
zero signs are equal in numeric SQL");
+ Schema schema = new Schema(Types.NestedField.optional(1, "f",
fieldType));
+ InMemoryCatalog catalog = freshCatalog();
+ Table table = catalog.createTable(
+ TABLE_ID, schema, PartitionSpec.unpartitioned(),
props("format-version", "2"));
+ String path = "s3://b/db1/t1/zero.parquet";
+ table.newAppend().appendFile(dataFileWithBounds(table.spec(), path,
2L, fieldType, value, value)).commit();
+ IcebergExternalTable target = targetTable();
+ SlotReference field = slot(target, "f", sqlType);
+ for (Expression predicate : ImmutableList.of(new LessThan(field,
literal), new EqualTo(field, literal),
+ new InPredicate(field, ImmutableList.of(literal)), new
Between(field, literal, literal))) {
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(predicate), new TargetScan(target,
ImmutableList.of(field)));
+ Assertions.assertFalse(IcebergMetadataDeletePredicate.build(table,
plan, DORIS_TARGET_ID).isPresent());
+ }
+ org.apache.iceberg.expressions.Expression isNull =
exactPredicate(table, target, field, new IsNull(field));
+ Assertions.assertEquals(OptionalLong.of(0L),
IcebergMetadataDelete.executeOnTable(
+ table, table, null, isNull, () -> false));
+ Assertions.assertEquals(Collections.singletonList(path),
dataFilePaths(reload(catalog)));
+ }
+
+ @Test
+ public void concurrentAppendAtFinalCommitFallsBack() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ TableOperations realOps = ((HasTableOperations) table).operations();
+ TableOperations racingOps = Mockito.mock(TableOperations.class,
AdditionalAnswers.delegatesTo(realOps));
+ AtomicBoolean appended = new AtomicBoolean();
+ Mockito.doAnswer(invocation -> {
+ if (appended.compareAndSet(false, true)) {
+ reload(catalog).newAppend().appendFile(
+ dataFile(spec, "s3://b/db1/t1/concurrent.parquet",
5L)).commit();
+ }
+ realOps.commit(invocation.getArgument(0),
invocation.getArgument(1));
+ return null;
+ }).when(racingOps).commit(Mockito.any(), Mockito.any());
+ Table racingTable = new BaseTable(racingOps, table.name());
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ racingTable, table, null, Expressions.alwaysTrue(), () ->
false);
+
+ Assertions.assertTrue(appended.get());
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertEquals(2, dataFilePaths(reload(catalog)).size());
+ Assertions.assertEquals("append",
reload(catalog).currentSnapshot().operation());
+ }
+
+ @Test
+ public void unknownCommitOutcomeIsNeverReportedAsFallback() throws
Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ TableOperations realOps = ((HasTableOperations) table).operations();
+ TableOperations uncertainOps = Mockito.mock(TableOperations.class,
AdditionalAnswers.delegatesTo(realOps));
+ Mockito.doAnswer(invocation -> {
+ realOps.commit(invocation.getArgument(0),
invocation.getArgument(1));
+ throw new CommitStateUnknownException(new IOException("Commit
response was lost"));
+ }).when(uncertainOps).commit(Mockito.any(), Mockito.any());
+ Table uncertainTable = new BaseTable(uncertainOps, table.name());
+
+ Assertions.assertThrows(CommitStateUnknownException.class,
+ () -> IcebergMetadataDelete.executeOnTable(
+ uncertainTable, table, null, Expressions.alwaysTrue(),
() -> false));
+ Assertions.assertTrue(dataFilePaths(reload(catalog)).isEmpty());
+ }
+
+ @Test
+ public void affectedRowsUseThisDeletesSnapshot() throws Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "2"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ TableOperations realOps = ((HasTableOperations) table).operations();
+ TableOperations racingOps = Mockito.mock(TableOperations.class,
AdditionalAnswers.delegatesTo(realOps));
+ Mockito.doAnswer(invocation -> {
+ realOps.commit(invocation.getArgument(0),
invocation.getArgument(1));
+ reload(catalog).newAppend().appendFile(
+ dataFile(spec, "s3://b/db1/t1/concurrent.parquet",
5L)).commit();
+ return null;
+ }).when(racingOps).commit(Mockito.any(), Mockito.any());
+ Table racingTable = new BaseTable(racingOps, table.name());
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ racingTable, table, null, Expressions.alwaysTrue(), () ->
false);
+
+ Assertions.assertEquals(OptionalLong.of(10L), deleted);
+
Assertions.assertEquals(Collections.singletonList("s3://b/db1/t1/concurrent.parquet"),
+ dataFilePaths(reload(catalog)));
+ Assertions.assertEquals("append",
reload(catalog).currentSnapshot().operation());
+ }
+
+ @Test
+ public void v1TableKeepsTheRowLevelFormatVersionContract() throws
Exception {
+ InMemoryCatalog catalog = freshCatalog();
+ PartitionSpec spec = PartitionSpec.unpartitioned();
+ Table table = catalog.createTable(TABLE_ID, SCHEMA, spec,
props("format-version", "1"));
+ table.newAppend().appendFile(dataFile(spec, "s3://b/db1/t1/a.parquet",
10L)).commit();
+ long snapshotBefore = table.currentSnapshot().snapshotId();
+
+ OptionalLong deleted = IcebergMetadataDelete.executeOnTable(
+ table, table, null, Expressions.alwaysTrue(), () -> false);
+
+ Assertions.assertFalse(deleted.isPresent());
+ Assertions.assertEquals(snapshotBefore,
reload(catalog).currentSnapshot().snapshotId());
+ }
+
+ @Test
+ public void metadataDeleteUsesPinnedIcebergOpsAndClosesTheLease() throws
Exception {
+ Table table = createTable();
+ IcebergExternalTable dorisTable = targetTable();
+ IcebergSnapshotCacheValue snapshot =
Mockito.mock(IcebergSnapshotCacheValue.class);
+ IcebergRuntimeContext runtimeContext =
Mockito.mock(IcebergRuntimeContext.class);
+ IcebergMetadataOps pinnedOps = Mockito.mock(IcebergMetadataOps.class);
+ WritableTableLease lease = Mockito.mock(WritableTableLease.class);
+
Mockito.when(snapshot.getIcebergTable()).thenReturn(Optional.of(table));
+ Mockito.when(snapshot.getRuntimeContext()).thenReturn(runtimeContext);
+ Mockito.when(runtimeContext.getMetadataOps()).thenReturn(pinnedOps);
+ Mockito.when(lease.getTable()).thenReturn(table);
+ Mockito.when(lease.getOps()).thenReturn(pinnedOps);
+ Mockito.when(lease.getAuthenticator()).thenReturn(new
ExecutionAuthenticator() { });
+
+ try (MockedStatic<IcebergUtils> utils =
Mockito.mockStatic(IcebergUtils.class)) {
+ utils.when(() ->
IcebergUtils.acquireWritableIcebergTable(dorisTable,
pinnedOps)).thenReturn(lease);
+
+ Assertions.assertFalse(IcebergMetadataDelete.execute(
+ dorisTable, snapshot, Expressions.alwaysTrue(), () ->
false).isPresent());
+
+ utils.verify(() ->
IcebergUtils.acquireWritableIcebergTable(dorisTable, pinnedOps));
+ }
+ Mockito.verify(lease).close();
+ // In HMS catalogs getMetadataOps() is the Hive implementation. The
retained snapshot is
+ // the authority for Iceberg ops on both catalog routes.
+ Mockito.verify(dorisTable, Mockito.never()).getCatalog();
+ }
+
+ @ParameterizedTest
+ @CsvSource({"0,0,0,false", "2024,2,29,true"})
+ public void preparedDateMustBindBeforeMetadataDelete(int year, int month,
int day, boolean canBind)
+ throws Exception {
+ Schema schema = new Schema(Types.NestedField.required(1, "d",
Types.DateType.get()));
+ Table table = freshCatalog().createTable(TABLE_ID, schema,
PartitionSpec.unpartitioned(),
+ props("format-version", "2"));
+ IcebergExternalTable target = targetTable();
+ SlotReference date = slot(target, "d", DateV2Type.INSTANCE);
+ ByteBuffer data =
ByteBuffer.allocate(5).order(ByteOrder.LITTLE_ENDIAN);
+ data.put((byte) 4).putShort((short) year).put((byte) month).put((byte)
day).flip();
+ Literal parameter =
Literal.getLiteralByMysqlType(MysqlColType.MYSQL_TYPE_DATE, false, data);
+ Plan plan = new LogicalFilter<>(ImmutableSet.of(new EqualTo(date,
parameter)),
+ new TargetScan(target, ImmutableList.of(date)));
+
+ Assertions.assertEquals(canBind,
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).isPresent());
+ }
+
+ @Test
+ public void exactPredicateIsBuiltFromTheTargetFilter() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(new EqualTo(id, new IntegerLiteral(1))),
+ new TargetScan(target, ImmutableList.of(id)));
+
+ Optional<org.apache.iceberg.expressions.Expression> result =
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID);
+
+ Assertions.assertTrue(result.isPresent());
+ Assertions.assertTrue(ExpressionUtil.equivalent(
+ Expressions.equal("id", 1), result.get(), SCHEMA.asStruct(),
false));
+ }
+
+ @Test
+ public void unfilteredTargetPlanMeansAlwaysTrue() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new TargetScan(target, ImmutableList.of(id));
+
+ Optional<org.apache.iceberg.expressions.Expression> result =
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID);
+
+ Assertions.assertTrue(result.isPresent());
+ Assertions.assertTrue(ExpressionUtil.equivalent(
+ Expressions.alwaysTrue(), result.get(), SCHEMA.asStruct(),
false));
+ }
+
+ @Test
+ public void literalLeftComparisonIsCommutatedExactly() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(new LessThan(new IntegerLiteral(1), id)),
+ new TargetScan(target, ImmutableList.of(id)));
+
+ Optional<org.apache.iceberg.expressions.Expression> result =
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID);
+
+ Assertions.assertTrue(result.isPresent());
+ Assertions.assertTrue(ExpressionUtil.equivalent(
+ Expressions.greaterThan("id", 1), result.get(),
SCHEMA.asStruct(), false));
+ }
+
+ @Test
+ public void unsafeNegationDisablesTheFastPath() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(new Not(new EqualTo(id, new
IntegerLiteral(1)))),
+ new TargetScan(target, ImmutableList.of(id)));
+
+ Assertions.assertFalse(
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).isPresent());
+ }
+
+ @Test
+ public void nullTestOfComputedExpressionDisablesTheWholeFastPath() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference id = slot(target, "id");
+ Plan plan = new LogicalFilter<>(ImmutableSet.of(
+ new EqualTo(id, new IntegerLiteral(1)),
+ new IsNull(new Add(id, new IntegerLiteral(1)))),
+ new TargetScan(target, ImmutableList.of(id)));
+
+ Assertions.assertFalse(
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).isPresent());
+ }
+
+ @Test
+ public void crossTableConjunctDisablesTheFastPath() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ TableIf other = Mockito.mock(TableIf.class);
+ Mockito.when(other.getId()).thenReturn(DORIS_TARGET_ID + 1);
+ SlotReference targetId = slot(target, "id");
+ SlotReference otherId = slot(other, "id");
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(
+ new EqualTo(targetId, new IntegerLiteral(1)),
+ new EqualTo(otherId, new IntegerLiteral(2))),
+ new TargetScan(target, ImmutableList.of(targetId, otherId)));
+
+ Assertions.assertFalse(
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).isPresent());
+ }
+
+ @Test
+ public void renamedSlotDisablesTheFastPath() {
+ Table table = createTable();
+ IcebergExternalTable target = targetTable();
+ SlotReference physical = slot(target, "region");
+ SlotReference renamed = physical.withName("id");
+ Plan plan = new LogicalFilter<>(
+ ImmutableSet.of(new EqualTo(renamed, new IntegerLiteral(1))),
+ new TargetScan(target, ImmutableList.of(renamed)));
+
+ Assertions.assertFalse(
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID).isPresent());
+ }
+
+ @Test
+ public void nonlinearPlanDisablesTheFastPath() {
+ Table table = createTable();
+ Plan join = Mockito.mock(LogicalJoin.class);
+
+ Assertions.assertFalse(
+ IcebergMetadataDeletePredicate.build(table, join,
DORIS_TARGET_ID).isPresent());
+ }
+
+ private static IcebergExternalTable targetTable() {
+ IcebergExternalTable table = Mockito.mock(IcebergExternalTable.class);
+ Mockito.when(table.getId()).thenReturn(DORIS_TARGET_ID);
+ return table;
+ }
+
+ private static SlotReference slot(TableIf table, String name) {
+ Column column = name.equals("id")
+ ? new Column(name, org.apache.doris.catalog.ScalarType.INT)
+ : new Column(name, org.apache.doris.catalog.ScalarType.STRING);
+ return SlotReference.fromColumn(
+ StatementScopeIdGenerator.newExprId(), table, column,
ImmutableList.of("t"));
+ }
+
+ private static Table createTable() {
+ InMemoryCatalog catalog = freshCatalog();
+ return catalog.createTable(
+ TABLE_ID, SCHEMA, PartitionSpec.unpartitioned(),
props("format-version", "2"));
+ }
+
+ private static InMemoryCatalog freshCatalog() {
+ InMemoryCatalog catalog = new InMemoryCatalog();
+ catalog.initialize("test", Collections.emptyMap());
+ catalog.createNamespace(Namespace.of("db1"));
+ return catalog;
+ }
+
+ private static Table reload(InMemoryCatalog catalog) {
+ return catalog.loadTable(TABLE_ID);
+ }
+
+ private static Map<String, String> props(String... keyValues) {
+ Map<String, String> properties = new HashMap<>();
+ for (int i = 0; i + 1 < keyValues.length; i += 2) {
+ properties.put(keyValues[i], keyValues[i + 1]);
+ }
+ return properties;
+ }
+
+ private static DataFile dataFile(PartitionSpec spec, String path, long
records) {
+ return DataFiles.builder(spec)
+ .withPath(path)
+ .withFileSizeInBytes(1024)
+ .withRecordCount(records)
+ .withFormat(FileFormat.PARQUET)
+ .build();
+ }
+
+ private static DataFile partitionedDataFile(
+ PartitionSpec spec, String path, long records, String
partitionPath) {
+ return DataFiles.builder(spec)
+ .withPath(path)
+ .withFileSizeInBytes(1024)
+ .withRecordCount(records)
+ .withFormat(FileFormat.PARQUET)
+ .withPartitionPath(partitionPath)
+ .build();
+ }
+
+ private static DataFile dataFileWithId(PartitionSpec spec, String path,
long records, int id) {
+ return dataFileWithBounds(spec, path, records,
Types.IntegerType.get(), id, id);
+ }
+
+ private static DataFile dataFileWithBounds(
+ PartitionSpec spec, String path, long records, Type type, Object
lower, Object upper) {
+ return DataFiles.builder(spec)
+ .withPath(path)
+ .withFileSizeInBytes(1024L)
+ .withFormat(FileFormat.PARQUET)
+ .withMetrics(new Metrics(records, Collections.emptyMap(),
Collections.singletonMap(1, records),
+ Collections.singletonMap(1, 0L),
Collections.emptyMap(),
+ Collections.singletonMap(1,
Conversions.toByteBuffer(type, lower)),
+ Collections.singletonMap(1,
Conversions.toByteBuffer(type, upper))))
+ .build();
+ }
+
+ private static DataFile dataFileInPartition(PartitionSpec spec, String
path, long records, Object value) {
+ PartitionData partition = new PartitionData(spec.partitionType());
+ partition.set(0, value);
+ return
DataFiles.builder(spec).withPath(path).withFileSizeInBytes(1024L).withRecordCount(records)
+
.withFormat(FileFormat.PARQUET).withPartition(partition).build();
+ }
+
+ private static Literal temporalLiteral(boolean zoned, String value) {
+ return zoned ?
TimestampTzLiteral.fromSessionTimeZone(TimeStampTzType.of(6), value)
+ : new DateTimeV2Literal(DateTimeV2Type.of(6), value);
+ }
+
+ private static SlotReference slot(TableIf table, String name, DataType
type) {
+ return SlotReference.fromColumn(StatementScopeIdGenerator.newExprId(),
table,
+ new Column(name, type.toCatalogDataType()),
ImmutableList.of("t"));
+ }
+
+ private static org.apache.iceberg.expressions.Expression exactPredicate(
+ Table table, IcebergExternalTable target, SlotReference field,
Expression expression) {
+ Plan plan = new LogicalFilter<>(ImmutableSet.of(expression), new
TargetScan(target, ImmutableList.of(field)));
+ Optional<org.apache.iceberg.expressions.Expression> predicate =
+ IcebergMetadataDeletePredicate.build(table, plan,
DORIS_TARGET_ID);
+ Assertions.assertTrue(predicate.isPresent());
+ return predicate.get();
+ }
+
+ private static Table tableWithFileIO(Table table, FileIO io) {
+ return new BaseTable(operationsWithFileIO(((HasTableOperations)
table).operations(), io), table.name());
+ }
+
+ private static TableOperations operationsWithFileIO(TableOperations
delegate, FileIO io) {
+ TableOperations operations = Mockito.mock(TableOperations.class,
AdditionalAnswers.delegatesTo(delegate));
+ Mockito.when(operations.io()).thenReturn(io);
+ // A transaction uses temporary operations for its IO. Preserve the
same decorated IO
+ // there, as the production retained writable operations do, rather
than losing the observer.
+ Mockito.doAnswer(invocation -> {
+ TableMetadata metadata = invocation.getArgument(0);
+ TableOperations temporary = Mockito.mock(TableOperations.class,
+ AdditionalAnswers.delegatesTo(delegate.temp(metadata)));
+ Mockito.when(temporary.io()).thenReturn(io);
+ return temporary;
+ }).when(operations).temp(Mockito.any(TableMetadata.class));
+ return operations;
+ }
+
+ private static final class TrackingFileIO implements FileIO {
+ private static final long serialVersionUID = 1L;
+ private final FileIO delegate;
+ private final List<String> createdFiles = new CopyOnWriteArrayList<>();
+
+ private TrackingFileIO(FileIO delegate) {
+ this.delegate = delegate;
+ }
+
+ @Override
+ public InputFile newInputFile(String path) {
+ return delegate.newInputFile(path);
+ }
+
+ @Override
+ public InputFile newInputFile(String path, long length) {
+ return delegate.newInputFile(path, length);
+ }
+
+ @Override
+ public OutputFile newOutputFile(String path) {
+ createdFiles.add(path);
+ return delegate.newOutputFile(path);
+ }
+
+ @Override
+ public void deleteFile(String path) {
+ delegate.deleteFile(path);
+ }
+
+ @Override
+ public void close() {
+ delegate.close();
+ }
+
+ private boolean hasCreatedFile() {
+ return !existingCreatedFiles().isEmpty();
+ }
+
+ private List<String> existingCreatedFiles() {
+ List<String> existing = new ArrayList<>();
+ for (String path : createdFiles) {
+ if (exists(path)) {
+ existing.add(path);
+ }
+ }
+ return existing;
+ }
+
+ private boolean exists(String path) {
+ try {
+ return delegate.newInputFile(path).exists();
+ } catch (NotFoundException e) {
+ // InMemoryFileIO reports an already deleted object when
constructing InputFile;
+ // HadoopFileIO instead returns an InputFile whose exists() is
false.
+ return false;
+ }
+ }
+ }
+
+ private static DeleteFile deletionVector(
+ PartitionSpec spec, String puffin, DataFile referencedDataFile,
long cardinality) {
+ return FileMetadata.deleteFileBuilder(spec)
+ .ofPositionDeletes()
+ .withPath(puffin)
+ .withFormat(FileFormat.PUFFIN)
+ .withFileSizeInBytes(128L)
+ .withRecordCount(cardinality)
+ .withPartition(referencedDataFile.partition())
+ .withReferencedDataFile(referencedDataFile.path().toString())
+ .withContentOffset(0L)
+ .withContentSizeInBytes(64L)
+ .build();
+ }
+
+ private static List<String> dataFilePaths(Table table) {
+ List<String> paths = new ArrayList<>();
+ try (CloseableIterable<FileScanTask> tasks =
table.newScan().planFiles()) {
+ for (FileScanTask task : tasks) {
+ paths.add(task.file().path().toString());
+ }
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ Collections.sort(paths);
+ return paths;
+ }
+
+ private static int liveDeleteFileCount(Table table) {
+ Snapshot snapshot = table.currentSnapshot();
+ if (snapshot == null) {
+ return 0;
+ }
+ int count = 0;
+ for (ManifestFile manifest : snapshot.deleteManifests(table.io())) {
+ try (ManifestReader<DeleteFile> reader =
+ ManifestFiles.readDeleteManifest(manifest, table.io(),
table.specs())) {
+ count += Iterables.size(reader);
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ }
+ return count;
+ }
+
+ private static int attachedDeleteFileCount(Table table, String
dataFilePath) {
+ try (CloseableIterable<FileScanTask> tasks =
table.newScan().planFiles()) {
+ for (FileScanTask task : tasks) {
+ if (task.file().path().toString().equals(dataFilePath)) {
+ return task.deletes().size();
+ }
+ }
+ } catch (IOException e) {
+ throw new AssertionError(e);
+ }
+ return -1;
+ }
+
+ private static final class TargetScan extends LogicalCatalogRelation {
+ private final List<Slot> output;
+
+ private TargetScan(TableIf table, List<? extends Slot> output) {
+ super(new RelationId(0), PlanType.LOGICAL_FILE_SCAN, table,
ImmutableList.of("db1"));
+ this.output = ImmutableList.copyOf(output);
+ }
+
+ @Override
+ public List<Slot> computeOutput() {
+ return output;
+ }
+
+ @Override
+ public LogicalCatalogRelation withRelationId(RelationId relationId) {
+ return this;
+ }
+
+ @Override
+ public LogicalCatalogRelation withTableAlias(String tableAlias) {
+ return this;
+ }
+
+ @Override
+ public Plan withGroupExprLogicalPropChildren(Optional<GroupExpression>
groupExpression,
+ Optional<LogicalProperties> logicalProperties, List<Plan>
children) {
+ return this;
+ }
+
+ @Override
+ public Plan withGroupExpression(Optional<GroupExpression>
groupExpression) {
+ return this;
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommandTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommandTest.java
index f6874c2705d..7306d925b43 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommandTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/trees/plans/commands/IcebergDeleteCommandTest.java
@@ -19,11 +19,24 @@ package org.apache.doris.nereids.trees.plans.commands;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.StructType;
+import org.apache.doris.common.Status;
+import org.apache.doris.common.UserException;
import org.apache.doris.datasource.iceberg.IcebergRowId;
+import org.apache.doris.nereids.CascadesContext;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerHook;
+import org.apache.doris.nereids.StatementContext;
+import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.StmtExecutor;
+import org.apache.doris.thrift.TStatusCode;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import java.util.concurrent.atomic.AtomicReference;
/**
* Unit tests for IcebergDeleteCommand.
@@ -88,4 +101,40 @@ public class IcebergDeleteCommandTest {
Assertions.assertEquals("expected", exception.getMessage());
Assertions.assertFalse(ctx.getSessionVariable().enableExternalTableBatchMode);
}
+
+ @Test
+ public void deleteCapturesThePreRewriteAnalyzedPlanLocally() {
+ ConnectContext ctx = Mockito.mock(ConnectContext.class);
+ StatementContext statementContext =
Mockito.mock(StatementContext.class);
+ Mockito.when(ctx.getStatementContext()).thenReturn(statementContext);
+ AtomicReference<Plan> captured = new AtomicReference<>();
+
+ IcebergDeleteCommand.captureAnalyzedPlan(ctx, captured);
+
+ ArgumentCaptor<PlannerHook> captor =
ArgumentCaptor.forClass(PlannerHook.class);
+ Mockito.verify(statementContext).addPlannerHook(captor.capture());
+ NereidsPlanner planner = Mockito.mock(NereidsPlanner.class);
+ CascadesContext cascadesContext = Mockito.mock(CascadesContext.class);
+ Plan analyzed = Mockito.mock(Plan.class);
+ Mockito.when(planner.getCascadesContext()).thenReturn(cascadesContext);
+ Mockito.when(cascadesContext.getRewritePlan()).thenReturn(analyzed);
+
+ captor.getValue().afterAnalyze(planner);
+
+ Assertions.assertSame(analyzed, captured.get());
+ Mockito.verify(planner,
Mockito.never()).setAnalyzedPlan(Mockito.any());
+ }
+
+ @Test
+ public void retainedCancellationIsReplayedBeforeMetadataDelete() {
+ StmtExecutor executor = Mockito.mock(StmtExecutor.class);
+ Mockito.when(executor.getPendingCancelReason())
+ .thenReturn(new Status(TStatusCode.CANCELLED, "query was
killed"));
+
+ UserException exception = Assertions.assertThrows(
+ UserException.class, () ->
IcebergDeleteCommand.throwIfCancelled(
+ executor, Mockito.mock(ConnectContext.class)));
+
+ Assertions.assertTrue(exception.getMessage().contains("query was
killed"));
+ }
}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
index ef33be260ae..e9defba540c 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/qe/StmtExecutorTest.java
@@ -96,6 +96,38 @@ public class StmtExecutorTest extends TestWithFeService {
private static final String AI_RESOURCE_LOG_SECRET = "sk-test-secret";
private static final String MASKED_STMT_FALLBACK = "/* masked statement
unavailable */";
+ @Test
+ public void testLateCoordinatorReceivesFirstCancelReason() {
+ StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "");
+ Status first = new Status(TStatusCode.CANCELLED, "first cancellation");
+ Status second = new Status(TStatusCode.CANCELLED, "second
cancellation");
+
+ stmtExecutor.cancel(first, false);
+ stmtExecutor.cancel(second, false);
+
+ Assertions.assertSame(first, stmtExecutor.getPendingCancelReason());
+ Coordinator coordinator = Mockito.mock(Coordinator.class);
+ stmtExecutor.setCoord(coordinator);
+ Mockito.verify(coordinator).cancel(first);
+ Mockito.verifyNoMoreInteractions(coordinator);
+ }
+
+ @Test
+ public void testPublishedCoordinatorRetainsFirstCancelReason() {
+ StmtExecutor stmtExecutor = new StmtExecutor(connectContext, "");
+ Coordinator coordinator = Mockito.mock(Coordinator.class);
+ stmtExecutor.setCoord(coordinator);
+ Status first = new Status(TStatusCode.CANCELLED, "first cancellation");
+ Status second = new Status(TStatusCode.CANCELLED, "second
cancellation");
+
+ stmtExecutor.cancel(first, false);
+ stmtExecutor.cancel(second, false);
+
+ Assertions.assertSame(first, stmtExecutor.getPendingCancelReason());
+ Mockito.verify(coordinator, Mockito.times(2)).cancel(first);
+ Mockito.verifyNoMoreInteractions(coordinator);
+ }
+
@Test
public void testInsertSourceCollectionDoesNotHoldTargetLock() throws
Exception {
assertInsertSourceCollectionFence(false);
diff --git
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_delete_unpartitioned_evolution.groovy
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_delete_unpartitioned_evolution.groovy
index 138b3a6c82c..6bc1cbc18ce 100644
---
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_delete_unpartitioned_evolution.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_delete_unpartitioned_evolution.groovy
@@ -107,7 +107,9 @@ suite("test_iceberg_delete_unpartitioned_evolution",
select record_key, metric from demo.${dbName}.mixed_partition_specs
where record_key not in (1, 3) order by record_key
"""
- sql """delete from mixed_partition_specs where record_key in (1, 3)"""
+ // This case checks row-level delete-file specs. A negated comparison
keeps it on the
+ // metadata-delete fallback path; all fixture metrics are positive.
+ sql """delete from mixed_partition_specs where record_key in (1, 3) and
metric <> -1"""
checkRows("mixed_partition_specs", expectedAfterMixedDelete)
assertEquals(mixedSpecs, sql("""
select distinct spec_id from mixed_partition_specs\$delete_files order
by spec_id
diff --git
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_dml_modes_evolution.groovy
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_dml_modes_evolution.groovy
index db999e19651..d1738c63e10 100644
---
a/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_dml_modes_evolution.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/write/test_iceberg_write_dml_modes_evolution.groovy
@@ -121,7 +121,9 @@ suite("test_iceberg_write_dml_modes_evolution",
sql """alter table mor_evolution create tag mor_before_dml as of version
${morBeforeDmlSnapshot}"""
// W03-S03: DELETE spans old/new specs and removes NULL partition rows.
- sql """delete from mor_evolution where region is null"""
+ // Keep this row-level DML matrix on the fallback path: SQL negation is
deliberately not
+ // lowered by whole-file metadata DELETE. All fixture scores are positive.
+ sql """delete from mor_evolution where region is null and score <> -1"""
// W03-S04: UPDATE changes partition source values in files from both
specs.
sql """
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]