You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by st...@apache.org on 2026/07/10 00:47:49 UTC
(impala) branch master updated: IMPALA-14637: COMMIT_TXN events should trigger reload for truncate ops
This is an automated email from the ASF dual-hosted git repository.
asf-gitbox-commits pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/impala.git
The following commit(s) were added to refs/heads/master by this push:
new e0c3291c1 IMPALA-14637: COMMIT_TXN events should trigger reload for truncate ops
e0c3291c1 is described below
commit e0c3291c1f1734121aaf88edf450268cc2f85ecf
Author: stiga-huang <hu...@gmail.com>
AuthorDate: Mon Dec 22 20:36:53 2025 +0800
IMPALA-14637: COMMIT_TXN events should trigger reload for truncate ops
Truncate operations generate ALTER events in HMS. These events trigger
metadata reloads when catalogd processes them. For a transactional
table, the ALTER event could be processed before the transaction is
committed. Then a stale snapshot is loaded. Catalogd should reload the
metadata in processing the corresponding COMMIT_TXN event. However, that
doesn't happen for truncate operations. When processing COMMIT_TXN
events, catalogd fetches the WriteEventInfo list for the transaction.
This doesn't include the truncate operations (HIVE-29677), which causes
COMMIT_TXN events skip the reloads.
This patch fixes the issue by tracking transactional truncate operations
when receiving ALTER_TABLE, ALTER_PARTITION and ALTER_PARTITIONS events.
A map from TableWriteId (db, tbl, writeId) to the truncated partition
list is maintained for this. When processing ABORT_TXN events, the
entries in this map will be cleared and no updates happen.
A new class, TableWriteEvent, is added to represent WriteEventInfo
returned from HMS and the truncation info. When processing a COMMIT_TXN
event, after fetching the WriteEventInfo list, we convert it into a list
of TableWriteEvent and then add all the truncation items of that
transaction. Reloads are triggered based on this list and ValidWriteIds
list of the table is updated accordingly.
Tests
- Added FE tests for ALTER_TABLE and ALTER_PARTITION events.
- Due to the dependent Hive version is missing HIVE-28668, HMS can't
generate a single ALTER_PARTITIONS event when truncating a
partitioned table. So tests for ALTER_PARTITIONS events are missing.
Assisted-by: Opus 4.7 (Claude Code)
Change-Id: I89aac12819f08dd9ed42d5d8b21a96c04b04d75c
Reviewed-on: http://gerrit.cloudera.org:8080/23805
Reviewed-by: Zoltan Borok-Nagy <bo...@cloudera.com>
Tested-by: Impala Public Jenkins <im...@cloudera.com>
---
.../org/apache/impala/compat/MetastoreShim.java | 9 ++
.../org/apache/impala/compat/MetastoreShim.java | 135 +++++++++++++--------
.../java/org/apache/impala/catalog/Catalog.java | 36 ++++++
.../impala/catalog/Hive3MetastoreShimBase.java | 12 +-
.../org/apache/impala/catalog/TableWriteEvent.java | 81 +++++++++++++
.../impala/catalog/events/MetastoreEvents.java | 47 +++++++
.../apache/impala/service/CatalogOpExecutor.java | 9 +-
.../events/MetastoreEventsProcessorTest.java | 103 ++++++++++++++++
8 files changed, 381 insertions(+), 51 deletions(-)
diff --git a/fe/src/compat-apache-hive-3/java/org/apache/impala/compat/MetastoreShim.java b/fe/src/compat-apache-hive-3/java/org/apache/impala/compat/MetastoreShim.java
index a16c6f063..815d9daec 100644
--- a/fe/src/compat-apache-hive-3/java/org/apache/impala/compat/MetastoreShim.java
+++ b/fe/src/compat-apache-hive-3/java/org/apache/impala/compat/MetastoreShim.java
@@ -56,6 +56,7 @@ import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.TableValidWriteIds;
import org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore;
import org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Client;
+import org.apache.hadoop.hive.metastore.messaging.AlterPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.AlterTableMessage;
import org.apache.hadoop.hive.metastore.messaging.EventMessage;
import org.apache.hadoop.hive.metastore.messaging.MessageDeserializer;
@@ -207,6 +208,14 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
return message.toString();
}
+ public static long getWriteId(AlterTableMessage message) {
+ return 0;
+ }
+
+ public static long getWriteId(AlterPartitionMessage message) {
+ return 0;
+ }
+
/**
* Get valid write ids from HMS for the acid table
* @param client the client to access HMS
diff --git a/fe/src/compat-hive-3/java/org/apache/impala/compat/MetastoreShim.java b/fe/src/compat-hive-3/java/org/apache/impala/compat/MetastoreShim.java
index 452a5da6c..70e500c9a 100644
--- a/fe/src/compat-hive-3/java/org/apache/impala/compat/MetastoreShim.java
+++ b/fe/src/compat-hive-3/java/org/apache/impala/compat/MetastoreShim.java
@@ -80,6 +80,7 @@ import org.apache.hadoop.hive.metastore.api.WriteEventInfo;
import org.apache.hadoop.hive.metastore.api.WriteNotificationLogBatchRequest;
import org.apache.hadoop.hive.metastore.api.WriteNotificationLogRequest;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
+import org.apache.hadoop.hive.metastore.messaging.AlterPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.AlterPartitionsMessage;
import org.apache.hadoop.hive.metastore.messaging.AlterTableMessage;
import org.apache.hadoop.hive.metastore.messaging.CommitTxnMessage;
@@ -108,6 +109,7 @@ import org.apache.impala.catalog.MetaStoreClientPool;
import org.apache.impala.catalog.MetaStoreClientPool.MetaStoreClient;
import org.apache.impala.catalog.TableNotFoundException;
import org.apache.impala.catalog.TableNotLoadedException;
+import org.apache.impala.catalog.TableWriteEvent;
import org.apache.impala.catalog.TableWriteId;
import org.apache.impala.catalog.events.MetastoreEvents.DerivedMetastoreEventContext;
import org.apache.impala.catalog.events.MetastoreEvents.DerivedMetastoreTableEvent;
@@ -258,6 +260,14 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
return getMessageSerializer().serialize(message);
}
+ public static long getWriteId(AlterTableMessage message) {
+ return message.getWriteId();
+ }
+
+ public static long getWriteId(AlterPartitionMessage message) {
+ return message.getWriteId();
+ }
+
/**
* Get valid write ids from HMS for the acid table
* @param client the client to access HMS
@@ -633,8 +643,9 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
org.apache.hadoop.hive.metastore.api.Table msTbl = Preconditions.checkNotNull(
alterPartitionsMessage.getTableObj());
boolean isTruncateOp = alterPartitionsMessage.getIsTruncateOp();
+ Long writeId = alterPartitionsMessage.getWriteId();
alterPartitionsInfo = new AlterPartitionsInfo(msTbl, partitionsAfter,
- isTruncateOp);
+ isTruncateOp, writeId);
} catch (Exception e) {
throw new MetastoreNotificationException(e);
}
@@ -943,6 +954,7 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
private final long txnId_;
private Set<TableWriteId> tableWriteIds_ = Collections.emptySet();
private final Set<String> tableNames_ = new HashSet<>();
+ private final Map<TableWriteId, List<Partition>> truncateOps_ = new HashMap<>();
public CommitTxnEvent(CatalogOpExecutor catalogOpExecutor, Metrics metrics,
NotificationEvent event) {
@@ -954,6 +966,11 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
.getCommitTxnMessage(event.getMessage());
txnId_ = commitTxnMessage.getTxnId();
tableWriteIds_ = catalog_.removeWriteIds(txnId_);
+ for (TableWriteId id : tableWriteIds_) {
+ List<Partition> parts = catalog_.removeTruncateOp(id);
+ if (parts == null) continue; // not a truncate writeId
+ truncateOps_.put(id, parts);
+ }
LOG.info("EventId: {} EventType: COMMIT_TXN transaction id: {}", getEventId(),
txnId_);
}
@@ -974,22 +991,10 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
@Override
protected void process() throws MetastoreNotificationException {
if (handleIfInCatchUpMode()) return;
- // Via getAllWriteEventInfo, we can get data insertion info for transactional tables
- // even though there are no insert events generated for transactional tables. Note
- // that we cannot get DDL info from this API.
- List<WriteEventInfo> writeEventInfoList;
- try (MetaStoreClientPool.MetaStoreClient client = catalog_.getMetaStoreClient()) {
- writeEventInfoList = client.getHiveClient().getAllWriteEventInfo(
- new GetAllWriteEventInfoRequest(txnId_));
- } catch (TException e) {
- throw new MetastoreNotificationNeedsInvalidateException(debugString("Failed to "
- + "get write event infos for txn {}. Event processing cannot continue. Issue "
- + "an invalidate metadata command to reset event processor.", txnId_), e);
- }
-
+ List<TableWriteEvent> writeEvents = getWriteEventsForTxn(this);
try {
- if (writeEventInfoList != null && !writeEventInfoList.isEmpty()) {
- addCommittedWriteIdsAndRefreshPartitions(writeEventInfoList);
+ if (!writeEvents.isEmpty()) {
+ addCommittedWriteIdsAndRefreshPartitions(writeEvents);
}
// committed write ids for DDL need to be added here
addCommittedWriteIdsToTables(tableWriteIds_);
@@ -1033,14 +1038,13 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
}
private void addCommittedWriteIdsAndRefreshPartitions(
- List<WriteEventInfo> writeEventInfoList) throws Exception {
- List<Long> writeIds = writeEventInfoList.stream().map(WriteEventInfo::getWriteId)
+ List<TableWriteEvent> writeEventList) throws Exception {
+ List<Long> writeIds = writeEventList.stream().map(TableWriteEvent::getWriteId)
.collect(Collectors.toList());
// To load partitions together for the same table, indexes are grouped by table name
Map<TableName, AcidTableWriteInfo> tableNameToWriteInfos = new HashMap<>();
for (int i = 0; i < writeIds.size(); i++) {
- Table tbl = (Table) MessageBuilder.getTObj(
- writeEventInfoList.get(i).getTableObj(), Table.class);
+ Table tbl = writeEventList.get(i).getTable();
if (catalog_.isHmsEventSyncDisabled(tbl)) {
LOG.debug("Not adding write ids to table {}.{} for event {} " +
"since table/db level flag {} is set to true", tbl.getDbName(),
@@ -1049,12 +1053,7 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
continue;
}
TableName tableName = new TableName(tbl.getDbName(), tbl.getTableName());
- Partition partition = null;
- if (writeEventInfoList.get(i).getPartitionObj() != null) {
- partition = (Partition) MessageBuilder.getTObj(
- writeEventInfoList.get(i).getPartitionObj(), Partition.class);
- Preconditions.checkNotNull(partition);
- }
+ Partition partition = writeEventList.get(i).getPartition();
AcidTableWriteInfo writeInfo = tableNameToWriteInfos.computeIfAbsent(tableName,
k -> new AcidTableWriteInfo(tbl));
writeInfo.appendWriteIdAndPartition(writeIds.get(i), partition);
@@ -1193,6 +1192,61 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
}
}
+ /**
+ * Retrieves write event information for a CommitTxnEvent and converts them into
+ * TableWriteEvent objects. Inserts come from {@code getAllWriteEventInfo}; truncates
+ * are joined in by intersecting the txn's writeIds with the catalog's truncateOps_
+ * map (populated when the ALTER_TABLE / ALTER_PARTITION / ALTER_PARTITIONS event was
+ * processed). Truncate entries are removed from truncateOps_ as a side effect.
+ */
+ private static List<TableWriteEvent> getWriteEventsForTxn(CommitTxnEvent event)
+ throws MetastoreNotificationNeedsInvalidateException {
+ Set<TableWriteEvent> writeEvents = new HashSet<>();
+ CatalogServiceCatalog cat = event.getCatalogOpExecutor().getCatalog();
+ try (MetaStoreClientPool.MetaStoreClient client = cat.getMetaStoreClient()) {
+ List<WriteEventInfo> writeEventInfoList = client.getHiveClient()
+ .getAllWriteEventInfo(new GetAllWriteEventInfoRequest(event.txnId_));
+ if (writeEventInfoList != null) {
+ for (WriteEventInfo info : writeEventInfoList) {
+ Table tbl = (Table) MessageBuilder.getTObj(info.getTableObj(), Table.class);
+ Partition partition = null;
+ if (info.getPartitionObj() != null) {
+ partition = (Partition) MessageBuilder.getTObj(info.getPartitionObj(),
+ Partition.class);
+ }
+ writeEvents.add(new TableWriteEvent(info.getWriteId(), tbl, partition));
+ }
+ }
+ } catch (Exception e) {
+ throw new MetastoreNotificationNeedsInvalidateException(String.format(
+ "EventId: %d EventType: COMMIT_TXN. Failed to get write event infos for " +
+ "txn %d. Event processing cannot continue. Issue an invalidate metadata " +
+ "command to reset event processor.",
+ event.getEventId(), event.txnId_), e);
+ }
+ // Adds truncate ops tracked in ALTER events. Note that truncate ops never appear in
+ // getAllWriteEventInfo results (HIVE-29677).
+ for (Map.Entry<TableWriteId, List<Partition>> entry : event.truncateOps_.entrySet()) {
+ TableWriteId id = entry.getKey();
+ List<Partition> parts = entry.getValue();
+ // Skip non-truncate writeIds
+ if (parts == null) continue;
+ org.apache.impala.catalog.Table cached = cat.getTableNoThrow(
+ id.getDbName(), id.getTblName());
+ // Skip non-existing or unloaded tables.
+ if (cached == null || cached.getMetaStoreTable() == null) continue;
+ Table tbl = cached.getMetaStoreTable();
+ if (parts.isEmpty()) {
+ writeEvents.add(new TableWriteEvent(id.getWriteId(), tbl, null));
+ } else {
+ for (Partition p : parts) {
+ writeEvents.add(new TableWriteEvent(id.getWriteId(), tbl, p));
+ }
+ }
+ }
+ return new ArrayList<>(writeEvents);
+ }
+
/**
* Gets the list of pseudo commit transaction events. It returns a PseudoCommitTxnEvent
* for each table involved in the transaction.
@@ -1203,18 +1257,9 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
public static List<PseudoCommitTxnEvent> getPseudoCommitTxnEvents(CommitTxnEvent event)
throws MetastoreNotificationException {
List<PseudoCommitTxnEvent> pseudoEvents = new ArrayList<>();
- List<WriteEventInfo> writeEventInfoList;
- try (MetaStoreClientPool.MetaStoreClient client = event.getCatalogOpExecutor()
- .getCatalog().getMetaStoreClient()) {
- writeEventInfoList = client.getHiveClient()
- .getAllWriteEventInfo(new GetAllWriteEventInfoRequest(event.txnId_));
- } catch (TException e) {
- throw new MetastoreNotificationNeedsInvalidateException(String.format(
- "Failed to get write event infos for txn %d. Event processing cannot " +
- "continue. Issue an invalidate metadata command to reset event processor.",
- event.txnId_), e);
- }
- // Build table name to write ids mapping from the catalog
+ List<TableWriteEvent> writeEvents = getWriteEventsForTxn(event);
+ // Build table name to write ids mapping from the catalog.
+ // Note that tableWriteIds_ are added to CommitTxnEvent from catalog.
Map<TableName, List<Long>> tableNameToWriteIds = new HashMap<>();
for (TableWriteId writeId : event.tableWriteIds_) {
TableName tableName = new TableName(writeId.getDbName(), writeId.getTblName());
@@ -1226,12 +1271,11 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
Map<TableName, AcidTableWriteInfo> tableNameToWriteInfos = new HashMap<>();
int derivedEventCount = 0;
DerivedMetastoreEventContext context = new DerivedMetastoreEventContext(event);
- if (writeEventInfoList != null && !writeEventInfoList.isEmpty()) {
- List<Long> writeIds = writeEventInfoList.stream().map(WriteEventInfo::getWriteId)
+ if (!writeEvents.isEmpty()) {
+ List<Long> writeIds = writeEvents.stream().map(TableWriteEvent::getWriteId)
.collect(Collectors.toList());
for (int i = 0; i < writeIds.size(); i++) {
- Table tbl = (Table) MessageBuilder.getTObj(
- writeEventInfoList.get(i).getTableObj(), Table.class);
+ Table tbl = writeEvents.get(i).getTable();
if (event.getCatalogOpExecutor().getCatalog().isHmsEventSyncDisabled(tbl)) {
LOG.debug("Not adding write ids to table {}.{} for event {} " +
"since table/db level flag {} or global level flag is set to true",
@@ -1240,12 +1284,7 @@ public class MetastoreShim extends Hive3MetastoreShimBase {
continue;
}
TableName tableName = new TableName(tbl.getDbName(), tbl.getTableName());
- Partition partition = null;
- if (writeEventInfoList.get(i).getPartitionObj() != null) {
- partition = (Partition) MessageBuilder.getTObj(
- writeEventInfoList.get(i).getPartitionObj(), Partition.class);
- Preconditions.checkNotNull(partition);
- }
+ Partition partition = writeEvents.get(i).getPartition();
AcidTableWriteInfo writeInfo = tableNameToWriteInfos.computeIfAbsent(tableName,
k -> new AcidTableWriteInfo(tbl));
writeInfo.appendWriteIdAndPartition(writeIds.get(i), partition);
diff --git a/fe/src/main/java/org/apache/impala/catalog/Catalog.java b/fe/src/main/java/org/apache/impala/catalog/Catalog.java
index e5f1761ef..096b570ac 100644
--- a/fe/src/main/java/org/apache/impala/catalog/Catalog.java
+++ b/fe/src/main/java/org/apache/impala/catalog/Catalog.java
@@ -111,6 +111,15 @@ public abstract class Catalog implements AutoCloseable {
protected final ConcurrentHashMap<Long, Set<TableWriteId>> txnToWriteIds_ =
new ConcurrentHashMap<>();
+ // Tracks transactional truncate operations. When a truncate operation is performed, an
+ // ALTER event is generated before the transaction commits. We track these operations
+ // here and reload the affected tables / partitions when the COMMIT_TXN event is
+ // processed. Entries are cleaned up on receiving commit or abort transaction events.
+ // Uses empty partition lists for non-partitioned tables or whole-table truncates.
+ protected final ConcurrentHashMap<TableWriteId,
+ List<org.apache.hadoop.hive.metastore.api.Partition>> truncateOps_ =
+ new ConcurrentHashMap<>();
+
// Cache of known HDFS cache pools. Allows for checking the existence
// of pools without hitting HDFS.
protected final CatalogObjectCache<HdfsCachePool> hdfsCachePools_ =
@@ -993,10 +1002,37 @@ public abstract class Catalog implements AutoCloseable {
return resultSet != null ? resultSet : Collections.emptySet();
}
+ /**
+ * Tracks a truncate operation. {@code partitions} is the list of partitions truncated
+ * under this writeId — empty for a non-partitioned table or a whole-table truncate.
+ * If the same writeId is tracked more than once (e.g. one ALTER_PARTITION event per
+ * partition before HIVE-28668), the partition lists are merged.
+ */
+ public void trackTruncateOp(TableWriteId tableWriteId,
+ List<org.apache.hadoop.hive.metastore.api.Partition> partitions) {
+ Preconditions.checkNotNull(tableWriteId);
+ if (tableWriteId.getWriteId() <= 0) return;
+ Preconditions.checkNotNull(partitions);
+ truncateOps_.computeIfAbsent(tableWriteId, k -> new ArrayList<>())
+ .addAll(partitions);
+ }
+
+ /**
+ * Returns and removes the truncate-op partitions for {@code tableWriteId}, or null
+ * if the writeId was not tracked as a truncate.
+ */
+ @Nullable
+ public List<org.apache.hadoop.hive.metastore.api.Partition> removeTruncateOp(
+ TableWriteId tableWriteId) {
+ Preconditions.checkNotNull(tableWriteId);
+ return truncateOps_.remove(tableWriteId);
+ }
+
/**
* Clears all write id records.
*/
public void clearWriteIds() {
txnToWriteIds_.clear();
+ truncateOps_.clear();
}
}
diff --git a/fe/src/main/java/org/apache/impala/catalog/Hive3MetastoreShimBase.java b/fe/src/main/java/org/apache/impala/catalog/Hive3MetastoreShimBase.java
index 10ce28c79..291ae96c5 100644
--- a/fe/src/main/java/org/apache/impala/catalog/Hive3MetastoreShimBase.java
+++ b/fe/src/main/java/org/apache/impala/catalog/Hive3MetastoreShimBase.java
@@ -858,13 +858,15 @@ public class Hive3MetastoreShimBase {
private final org.apache.hadoop.hive.metastore.api.Table msTable;
private final List<org.apache.hadoop.hive.metastore.api.Partition> partitions;
private final boolean isTruncate;
+ private final Long writeId;
public AlterPartitionsInfo(org.apache.hadoop.hive.metastore.api.Table msTable,
List<org.apache.hadoop.hive.metastore.api.Partition> partitions,
- boolean isTruncate) {
+ boolean isTruncate, Long writeId) {
this.msTable = msTable;
this.partitions = partitions;
this.isTruncate = isTruncate;
+ this.writeId = writeId;
}
/**
@@ -888,6 +890,14 @@ public class Hive3MetastoreShimBase {
public boolean isTruncate() {
return isTruncate;
}
+
+ /**
+ * Returns the write id of the alter partitions operation, or -1 if for
+ * non-transactional tables.
+ */
+ public long getWriteId() {
+ return writeId == null ? -1 : writeId;
+ }
}
/**
diff --git a/fe/src/main/java/org/apache/impala/catalog/TableWriteEvent.java b/fe/src/main/java/org/apache/impala/catalog/TableWriteEvent.java
new file mode 100644
index 000000000..65622edf0
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/catalog/TableWriteEvent.java
@@ -0,0 +1,81 @@
+// 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.impala.catalog;
+
+import com.google.common.base.Preconditions;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.Partition;
+
+/**
+ * Transient holder for a write event on a table during COMMIT_TXN processing.
+ * Built per partition from either an insert WriteEventInfo or a tracked truncate,
+ * e.g., a truncate spanning multiple partitions creates one TableWriteEvent per
+ * partition. Not stored in long-lived catalog state.
+ */
+public class TableWriteEvent {
+
+ private final TableWriteId tableWriteId_;
+ private final Table table_;
+ // null for a non-partitioned table or a whole-table truncate.
+ private final Partition partition_;
+
+ public TableWriteEvent(long writeId, Table table) {
+ this(writeId, table, null);
+ }
+
+ public TableWriteEvent(long writeId, Table table, Partition partition) {
+ Preconditions.checkArgument(table != null);
+ this.tableWriteId_ = new TableWriteId(table.getDbName(), table.getTableName(),
+ writeId);
+ this.table_ = table;
+ this.partition_ = partition;
+ }
+
+ public TableWriteId getTableWriteId() {
+ return tableWriteId_;
+ }
+
+ public Table getTable() {
+ return table_;
+ }
+
+ public Partition getPartition() {
+ return partition_;
+ }
+
+ public long getWriteId() {
+ return tableWriteId_.getWriteId();
+ }
+
+ @Override
+ public int hashCode() {
+ return tableWriteId_.hashCode() * 31 +
+ (partition_ == null ? 0 : partition_.getValues().hashCode());
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ if (this == object) return true;
+ if (object == null || getClass() != object.getClass()) return false;
+ TableWriteEvent that = (TableWriteEvent) object;
+ if (!tableWriteId_.equals(that.tableWriteId_)) return false;
+ if (partition_ == null && that.partition_ == null) return true;
+ if (partition_ == null || that.partition_ == null) return false;
+ return partition_.getValues().equals(that.partition_.getValues());
+ }
+}
diff --git a/fe/src/main/java/org/apache/impala/catalog/events/MetastoreEvents.java b/fe/src/main/java/org/apache/impala/catalog/events/MetastoreEvents.java
index 387a053eb..2d7f774e6 100644
--- a/fe/src/main/java/org/apache/impala/catalog/events/MetastoreEvents.java
+++ b/fe/src/main/java/org/apache/impala/catalog/events/MetastoreEvents.java
@@ -2099,11 +2099,13 @@ public class MetastoreEvents {
JSONAlterTableMessage alterTableMessage =
(JSONAlterTableMessage) MetastoreEventsProcessor.getMessageDeserializer()
.getAlterTableMessage(event.getMessage());
+ long writeId;
try {
msTbl_ = Preconditions.checkNotNull(alterTableMessage.getTableObjBefore());
tableAfter_ = Preconditions.checkNotNull(alterTableMessage.getTableObjAfter());
tableBefore_ = Preconditions.checkNotNull(alterTableMessage.getTableObjBefore());
isTruncateOp_ = alterTableMessage.getIsTruncateOp();
+ writeId = MetastoreShim.getWriteId(alterTableMessage);
} catch (Exception e) {
throw new MetastoreNotificationException(
debugString("Unable to parse the alter table message"), e);
@@ -2117,6 +2119,19 @@ public class MetastoreEvents {
dbFlagVal =
Boolean.valueOf(catalog_.getDbProperty(dbName_,
MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC.getKey()));
+
+ if (isTruncateOp_) {
+ if (AcidUtils.isTransactionalTable(tableAfter_.getParameters())) {
+ // Track the truncate by writeId. The owning txn is identified later when
+ // processing the COMMIT_TXN event.
+ catalog_.trackTruncateOp(
+ new TableWriteId(dbName_, tblName_, writeId), Collections.emptyList());
+ infoLog("Tracked truncate op with writeId {} on table {}.{}",
+ writeId, dbName_, tblName_);
+ } else {
+ infoLog("TruncateOp on non-transactional table");
+ }
+ }
}
public boolean isRename() { return isRename_; }
@@ -3024,6 +3039,19 @@ public class MetastoreEvents {
parameters, MetastoreEventPropertyKey.CATALOG_SERVICE_ID.getKey(), "");
partName_ = HdfsTable.constructPartitionName(getTPartitionSpecFromHmsPartition(
msTbl_, partitionAfter_));
+ if (isTruncateOp_) {
+ // Track truncate operations on transactional table partitions
+ if (AcidUtils.isTransactionalTable(msTbl_.getParameters())) {
+ long writeId = MetastoreShim.getWriteId(alterPartitionMessage);
+ catalog_.trackTruncateOp(
+ new TableWriteId(dbName_, tblName_, writeId),
+ Collections.singletonList(partitionAfter_));
+ infoLog("Tracked truncate op with writeId {} on partition {} of {}.{}",
+ writeId, partName_, dbName_, tblName_);
+ } else {
+ infoLog("TruncateOp on non-transactional table");
+ }
+ }
} catch (Exception e) {
throw new MetastoreNotificationException(
debugString("Unable to parse the alter partition message"), e);
@@ -3151,6 +3179,20 @@ public class MetastoreEvents {
msTbl_ = alterPartitionsInfo.getMsTable();
partitionsAfter_ = alterPartitionsInfo.getPartitions();
isTruncateOp_ = alterPartitionsInfo.isTruncate();
+ if (isTruncateOp_) {
+ // Track truncate operations on transactional table partitions. After
+ // HIVE-28668 the entire batch shares one writeId, so a single map entry
+ // carrying every partition is enough.
+ if (AcidUtils.isTransactionalTable(msTbl_.getParameters())) {
+ long writeId = alterPartitionsInfo.getWriteId();
+ catalog_.trackTruncateOp(
+ new TableWriteId(dbName_, tblName_, writeId), partitionsAfter_);
+ infoLog("Tracked truncate op with writeId {} on {} partitions of {}.{}",
+ writeId, partitionsAfter_.size(), dbName_, tblName_);
+ } else {
+ infoLog("TruncateOp on non-transactional table");
+ }
+ }
} catch (Exception e) {
throw new MetastoreNotificationException(
debugString("Unable to parse the alter partition message"), e);
@@ -3493,6 +3535,8 @@ public class MetastoreEvents {
TableWriteId tableWriteId =
new TableWriteId(dbName_, tblName_, txnToWriteId.getWriteId());
catalog_.addWriteId(txnToWriteId.getTxnId(), tableWriteId);
+ infoLog("Tracked writeId {} in transaction {}", txnToWriteId.getWriteId(),
+ txnToWriteId.getTxnId());
}
}
@@ -3757,6 +3801,9 @@ public class MetastoreEvents {
event.getMessage());
txnId_ = abortTxnMessage.getTxnId();
tableWriteIds_ = catalog_.removeWriteIds(txnId_);
+ for (TableWriteId id : tableWriteIds_) {
+ catalog_.removeTruncateOp(id);
+ }
infoLog("Received AbortTxnEvent for transaction " + txnId_);
}
diff --git a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
index 391a702ab..e719208c5 100644
--- a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
+++ b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
@@ -5655,8 +5655,13 @@ public class CatalogOpExecutor {
}
// set write id as committed before reload the partitions so that we can get
// up-to-date filemetadata.
- hdfsTable.addWriteIds(writeIdsToRefresh,
- MutableValidWriteIdList.WriteIdStatus.COMMITTED);
+ if (hdfsTable.addWriteIds(writeIdsToRefresh,
+ MutableValidWriteIdList.WriteIdStatus.COMMITTED)) {
+ // Log the deduplicated writeIds. Note that a writeId can be used to update
+ // multiple partitions.
+ LOG.info("Added COMMITTED writeIds to table {}: {} for event {}",
+ table.getFullName(), new HashSet<>(writeIdsToRefresh), eventId);
+ }
int numOfPartsReloaded;
try (MetaStoreClient metaStoreClient = catalog_.getMetaStoreClient()) {
numOfPartsReloaded = hdfsTable.reloadPartitionsFromEvent(eventId,
diff --git a/fe/src/test/java/org/apache/impala/catalog/events/MetastoreEventsProcessorTest.java b/fe/src/test/java/org/apache/impala/catalog/events/MetastoreEventsProcessorTest.java
index 7644cab10..e4b81a749 100644
--- a/fe/src/test/java/org/apache/impala/catalog/events/MetastoreEventsProcessorTest.java
+++ b/fe/src/test/java/org/apache/impala/catalog/events/MetastoreEventsProcessorTest.java
@@ -165,6 +165,7 @@ import org.apache.impala.thrift.TTypeNode;
import org.apache.impala.thrift.TTypeNodeType;
import org.apache.impala.thrift.TUpdateCatalogRequest;
import org.apache.impala.thrift.TUpdatedPartition;
+import org.apache.impala.util.AcidUtils.TblTransaction;
import org.apache.impala.util.DebugUtils;
import org.apache.impala.util.EventSequence;
import org.apache.impala.util.NoOpEventSequence;
@@ -4413,6 +4414,108 @@ public class MetastoreEventsProcessorTest {
metrics.getGauge(MetastoreEventsProcessor.GREATEST_SYNCED_EVENT_TIME).getValue());
}
+ @Test
+ public void testTruncateTxnTbl() throws Exception {
+ Assume.assumeFalse("Skipping this since it depends on the behavior of CDP Hive 3",
+ TestUtils.isApacheHiveVersion());
+ // Prepare a transactional non-partitioned table and a partitioned table with some
+ // data.
+ String nopartTblName = "test_trunc_txn_nopart";
+ String partTblName = "test_trunc_txn_part";
+ String insertNonPartTbl =
+ "insert into table " + TEST_DB_NAME + '.' + nopartTblName + " values('a', 'b')";
+ String insertPartTbl = String.format(
+ "insert into table %s.%s partition(p1) values" +
+ "('0', '0', 'a'), ('1', '1', 'b'), ('2', '2', 'c'), " +
+ "('3', '3', 'd'), ('4', '4', 'e'), ('5', '5', 'f')",
+ TEST_DB_NAME, partTblName);
+ createDatabase(TEST_DB_NAME, null);
+ createTransactionalTable(TEST_DB_NAME, nopartTblName, false);
+ createTransactionalTable(TEST_DB_NAME, partTblName, true);
+ try (HiveJdbcClientPool jdbcClientPool = HiveJdbcClientPool.create(1);
+ HiveJdbcClientPool.HiveJdbcClient hiveClient = jdbcClientPool.getClient()) {
+ hiveClient.executeSql(insertNonPartTbl);
+ hiveClient.executeSql("set hive.exec.dynamic.partition.mode=nonstrict");
+ hiveClient.executeSql(insertPartTbl);
+ }
+ eventsProcessor_.processEvents();
+
+ // Test truncate operations where the ALTER event is processed before the
+ // transaction is committed/aborted. abortTxn=true runs first so its aborted truncates
+ // leave the partitions intact for the committed truncates (abortTxn=false) to reuse.
+ for (boolean abortTxn : new boolean[]{true, false}) {
+ truncateTxnTblAndProcessEvents(nopartTblName, Arrays.asList(""), abortTxn, true);
+ truncateTxnTblAndProcessEvents(partTblName, Arrays.asList("p1=a"), abortTxn, true);
+ truncateTxnTblAndProcessEvents(
+ partTblName, Arrays.asList("p1=b", "p1=c"), abortTxn, true);
+ }
+
+ try (HiveJdbcClientPool jdbcClientPool = HiveJdbcClientPool.create(1);
+ HiveJdbcClientPool.HiveJdbcClient hiveClient = jdbcClientPool.getClient()) {
+ hiveClient.executeSql(insertNonPartTbl);
+ }
+ eventsProcessor_.processEvents();
+
+ // Test truncate operations where the transaction is committed before the ALTER
+ // event is processed. As above, abortTxn=true runs first so the committed truncates
+ // (abortTxn=false) can reuse the partitions.
+ for (boolean abortTxn : new boolean[]{true, false}) {
+ truncateTxnTblAndProcessEvents(nopartTblName, Arrays.asList(""), abortTxn, false);
+ truncateTxnTblAndProcessEvents(partTblName, Arrays.asList("p1=d"), abortTxn, false);
+ truncateTxnTblAndProcessEvents(
+ partTblName, Arrays.asList("p1=e", "p1=f"), abortTxn, false);
+ }
+ }
+
+ /**
+ * Helper method to truncate a transactional table in Hive and verify it's empty in
+ * Impala. Tests the scenario where the ALTER event from truncation is processed before
+ * or after the transaction is committed.
+ * @param tblName Name of the table to truncate
+ * @param partNames Partition names to verify (empty string for non-partitioned table)
+ * @param abortTxn whether to abort the transaction after the ALTER event is processed
+ * @param processAlterBeforeCommit whether to process the ALTER event before committing
+ * the transaction
+ */
+ private void truncateTxnTblAndProcessEvents(String tblName, List<String> partNames,
+ boolean abortTxn, boolean processAlterBeforeCommit) throws Exception {
+ // Load table in cache to process the events.
+ loadTable(tblName);
+ HdfsTable table = (HdfsTable) catalog_.getTable(TEST_DB_NAME, tblName);
+
+ try (MetaStoreClient client = catalog_.getMetaStoreClient()) {
+ TblTransaction tblTxn = MetastoreShim.createTblTransaction(
+ client.getHiveClient(), table.getMetaStoreTable(), -1);
+ List<String> hmsPartNames = partNames;
+ // For non-partitioned tables, HMS uses null as the partition names.
+ if (partNames.size() == 1 && "".equals(partNames.get(0))) {
+ hmsPartNames = null;
+ }
+ MetastoreShim.truncateTable(client.getHiveClient(), TEST_DB_NAME, tblName,
+ hmsPartNames, tblTxn.validWriteIds, tblTxn.writeId);
+
+ if (processAlterBeforeCommit) eventsProcessor_.processEvents();
+ if (abortTxn) {
+ MetastoreShim.abortTransaction(client.getHiveClient(), tblTxn.txnId);
+ } else {
+ MetastoreShim.commitTransaction(client.getHiveClient(), tblTxn.txnId);
+ }
+ }
+ eventsProcessor_.processEvents();
+
+ for (HdfsPartition partition : table.getPartitionsForNames(partNames)) {
+ if (abortTxn) {
+ assertTrue(String.format(
+ "Partition %s:%s should not be empty", tblName, partition.getPartitionName()),
+ partition.getNumFileDescriptors() > 0);
+ } else {
+ assertEquals(String.format(
+ "Partition %s:%s should be empty", tblName, partition.getPartitionName()),
+ 0, partition.getNumFileDescriptors());
+ }
+ }
+ }
+
private void createDatabase(String catName, String dbName,
Map<String, String> params) throws TException {
try(MetaStoreClient msClient = catalog_.getMetaStoreClient()) {