This is an automated email from the ASF dual-hosted git repository.
morningman pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/doris.git
The following commit(s) were added to refs/heads/master by this push:
new fc947b47d1f [fix](fe) Serialize queued edit log entries in the
submitting thread (#69525)
fc947b47d1f is described below
commit fc947b47d1f3099449603b04f57b08a86332c194
Author: Mingyu Chen (Rayner) <[email protected]>
AuthorDate: Thu Dec 3 11:46:41 2026 +0800
[fix](fe) Serialize queued edit log entries in the submitting thread
(#69525)
### Background
The master FE writes metadata changes to the edit log before
acknowledging them. Batch edit logging queues entries for a flusher,
while transaction commit and finish can release the transaction monitor
before waiting for journal durability. Publish workers complete
committed transactions after backend publish tasks respond, and persist
their delta-row statistics with the VISIBLE state.
### What problem does this PR solve?
Issue Number: None
Related PR: #52971 (introduced batch edit logging), #59990 (moved
transaction persistence outside locks)
PR Type: Bugfix
Problem Summary:
Queued edit log entries refer to mutable objects that the flusher
serializes later, allowing concurrent transaction updates to crash the
master FE with `ConcurrentModificationException` or change the state
recorded. Entries are now serialized at submission under the object's
protecting lock, and fatal journal failures stop query draining. Publish
delta rows are collected by the executing finish attempt, keeping the
daemon off transaction monitors in parallel mode and including BE
responses received while the attempt was queued. Most of the diff is
deterministic concurrency and failure-path tests.
The follow-up tests reproduce these two schedules on `d3da7fca`:
| Schedule | Before follow-up | After follow-up |
|---|---|---|
| A COMMITTED transaction retains its monitor before its first finish
attempt | daemon future throws `TimeoutException` after 5 seconds |
daemon returns while the monitor remains held |
| Two successful BE responses arrive while a finish attempt is queued |
serialized delta rows: `{}` | serialized delta rows:
`{20000={30000=30}}` |
### Details
- **Change map:** Production +120/-31 lines; tests +583/-1 lines (83% of
added lines). The three production parts are snapshots/map protection
(101 changed lines), fatal-write shutdown (27) and publish scheduling
(23). Submission-time snapshots and transaction map protection involve
`JournalBatch`, `EditLog` and transaction finish checks. Fatal-write
signaling joins `BDBJEJournal` to the shutdown drain. Publish scheduling
moves delta collection to the executing attempt. No generated files or
documentation are changed.
- **Frequency:** Intermittent. The original report records a flusher
`ConcurrentModificationException` during a P0 run. The two follow-up
schedules above reproduce deterministically in unit tests; no production
latency was measured.
- **Root cause:** The flusher serializes a live queued reference after
its caller has released the object's lock. Adding monitor protection to
publish updates exposed daemon waits behind commit journal I/O; skipping
in-flight attempts also froze their earlier delta-row sample.
- **Why existing tests missed it:** Earlier edit-log tests did not park
the flusher while a payload changed. The in-flight skip test
pre-installs a publishing ID, missing commits before their first finish
attempt and BE replies during executor queueing. Regression
`load/insert/test_publish_slow_not_wait` delays a backend, but does not
control these FE monitor/queue schedules.
- **Fix:** Queue serialized bytes, protect transaction map writers with
the snapshot monitor, and preserve the journal encoding. Refresh
successful task deltas in `tryFinishTxnSync` immediately before the
finish manager, retaining synchronized map mutation and releasing the
monitor before table-lock acquisition. Record every fatal write failure
before exit and recheck the signal during query draining.
- **Other paths and branches:** Both queue entry points,
ordinary/subtransaction finish checks, direct/batch fatal writes and
both publish modes are covered. The follow-up regression belongs to this
unmerged PR; checked local refs for `branch-3.1`, `branch-4.0`,
`branch-4.1` and `branch-4.2` retain the unsynchronized setter. Release
exposure of the original snapshot defect was not re-audited here.
- **Behavior change:** Queued entries record submission-time state.
Fatal journal failures end query draining rather than waiting up to 300
seconds. Configurations and defaults are unchanged.
### Testing
- Locally ran `run-fe-ut.sh --run` with explicit classes:
`PublishVersionDaemonTest` (4), `TransactionStateTest` (6),
`DatabaseTransactionMgrTest` (35), `GlobalTransactionMgrTest` (15),
`EditLogTest` (8), `DorisFETest` (2) and `BDBJEJournalTest` (4): 74
tests passed, none skipped.
- Before the follow-up, both new daemon progress cases timed out, the
queued statistics case persisted an empty map instead of 30 rows, and
the synchronous control passed. All four pass with the fix, including
error/unfinished task filtering and journal serialization/readback.
- No live cluster, journal-stall/failover exercise or SQL regression
suite was run. Unit tests control the monitor and executor queue
directly.
### Notes for Reviewers
- Each queued payload is still serialized once, with serialized bytes
retained until its write completes.
---
.../src/main/java/org/apache/doris/DorisFE.java | 16 +-
.../org/apache/doris/journal/JournalBatch.java | 17 +-
.../apache/doris/journal/bdbje/BDBJEJournal.java | 11 +-
.../java/org/apache/doris/persist/EditLog.java | 59 ++++--
.../doris/transaction/DatabaseTransactionMgr.java | 19 ++
.../doris/transaction/PublishVersionDaemon.java | 23 ++-
.../apache/doris/transaction/TransactionState.java | 6 +-
.../test/java/org/apache/doris/DorisFETest.java | 79 ++++++++
.../doris/journal/bdbje/BDBJEJournalTest.java | 40 +++++
.../java/org/apache/doris/persist/EditLogTest.java | 133 +++++++++++++-
.../transaction/PublishVersionDaemonTest.java | 200 +++++++++++++++++++++
.../doris/transaction/TransactionStateTest.java | 132 ++++++++++++++
12 files changed, 703 insertions(+), 32 deletions(-)
diff --git a/fe/fe-core/src/main/java/org/apache/doris/DorisFE.java
b/fe/fe-core/src/main/java/org/apache/doris/DorisFE.java
index 4aaddedf41d..6acd1d9a736 100755
--- a/fe/fe-core/src/main/java/org/apache/doris/DorisFE.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/DorisFE.java
@@ -38,6 +38,7 @@ import org.apache.doris.httpv2.HttpServer;
import org.apache.doris.journal.bdbje.BDBDebugger;
import org.apache.doris.journal.bdbje.BDBTool;
import org.apache.doris.journal.bdbje.BDBToolOptions;
+import org.apache.doris.persist.EditLog;
import org.apache.doris.persist.meta.MetaReader;
import org.apache.doris.qe.Coordinator;
import org.apache.doris.qe.QeProcessorImpl;
@@ -51,6 +52,7 @@ import org.apache.doris.tls.server.FeServerStarterFactory;
import org.apache.doris.tls.server.ServerStarter;
import org.apache.doris.tls.server.TlsProtocolSet;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import io.netty.util.internal.logging.InternalLoggerFactory;
@@ -747,12 +749,17 @@ public class DorisFE {
return serverReady.get();
}
- private static void gracefulShutdown() {
- // wait for all queries to finish
+ @VisibleForTesting
+ static void gracefulShutdown() {
+ // wait for all queries to finish, unless the edit log can not be
written, which may also happen while
+ // waiting. Nothing done from then on can be persisted, and every
thread that writes the edit log is
+ // blocked while holding its locks. Waiting for running queries would
keep this frontend serving metadata
+ // that may never become durable.
try {
long now = System.currentTimeMillis();
List<Coordinator> allCoordinators =
QeProcessorImpl.INSTANCE.getAllCoordinators();
- while (!allCoordinators.isEmpty() && System.currentTimeMillis() -
now < 300 * 1000L) {
+ while (!allCoordinators.isEmpty() && !EditLog.isWriteFailed()
+ && System.currentTimeMillis() - now < 300 * 1000L) {
Thread.sleep(1000);
allCoordinators =
QeProcessorImpl.INSTANCE.getAllCoordinators();
LOG.info("waiting {} queries to finish before shutdown",
allCoordinators.size());
@@ -761,6 +768,9 @@ public class DorisFE {
LOG.error("", t);
}
+ if (EditLog.isWriteFailed()) {
+ LOG.warn("stop waiting for running queries because the edit log
can not be written");
+ }
LOG.info("graceful shutdown finished");
}
}
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/journal/JournalBatch.java
b/fe/fe-core/src/main/java/org/apache/doris/journal/JournalBatch.java
index 1236a08d0db..8e42be28e06 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/journal/JournalBatch.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/journal/JournalBatch.java
@@ -51,6 +51,15 @@ public class JournalBatch {
// If the batch is too large, it may cause a latency spike. Generally, we
recommend controlling
// the number of batch entities to less than 32 and the batch data size to
less than 640KB.
public void addJournal(short op, Writable data) throws IOException {
+ addEntity(serialize(op, data));
+ }
+
+ // Serialize a writable data into the internal representation of a journal
batch.
+ //
+ // The returned entity does not refer to the data object. A caller that
hands an edit to another
+ // thread should serialize it first, while it still holds the lock that
guards the data object,
+ // because the other thread reads the entity later and the data object may
have changed by then.
+ public static Entity serialize(short op, Writable data) throws IOException
{
if (op == OperationType.OP_TIMESTAMP) {
// OP_TIMESTAMP is not supported, see `BDBJEJournal.write` for
details.
throw new RuntimeException("JournalBatch.addJournal is not
supported OP_TIMESTAMP");
@@ -62,9 +71,13 @@ public class JournalBatch {
DataOutputBuffer buffer = new
DataOutputBuffer(OUTPUT_BUFFER_INIT_SIZE);
entity.write(buffer);
- size += buffer.size();
+ return new Entity(op, buffer);
+ }
- entities.add(new Entity(op, buffer));
+ // Add an entity returned by `serialize` into journal batch.
+ public void addEntity(Entity entity) {
+ size += entity.data.size();
+ entities.add(entity);
}
public ArrayList<Entity> getJournalEntities() {
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/journal/bdbje/BDBJEJournal.java
b/fe/fe-core/src/main/java/org/apache/doris/journal/bdbje/BDBJEJournal.java
index f4234cc462a..e1ea7201635 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/journal/bdbje/BDBJEJournal.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/journal/bdbje/BDBJEJournal.java
@@ -29,6 +29,7 @@ import org.apache.doris.journal.JournalBatch;
import org.apache.doris.journal.JournalCursor;
import org.apache.doris.journal.JournalEntity;
import org.apache.doris.metric.MetricRepo;
+import org.apache.doris.persist.EditLog;
import org.apache.doris.persist.OperationType;
import org.apache.doris.system.SystemInfoService.HostInfo;
@@ -122,7 +123,7 @@ public class BDBJEJournal implements Journal { //
CHECKSTYLE IGNORE THIS LINE: B
newName, currentDbName, newNameVerify);
LOG.error(msg);
LogUtils.stderr(msg);
- System.exit(-1);
+ EditLog.exitOnWriteFailure(new IOException(msg));
}
}
@@ -194,7 +195,7 @@ public class BDBJEJournal implements Journal { //
CHECKSTYLE IGNORE THIS LINE: B
+ currentJournalDB.getDatabaseName();
LOG.error(msg);
LogUtils.stderr(msg);
- System.exit(-1);
+ EditLog.exitOnWriteFailure(e);
} catch (DatabaseException e) {
LOG.error("catch an exception when writing to database. sleep
and retry. the first journal id {}",
firstId, e);
@@ -222,7 +223,7 @@ public class BDBJEJournal implements Journal { //
CHECKSTYLE IGNORE THIS LINE: B
+ currentJournalDB.getDatabaseName();
LOG.error(msg);
LogUtils.stderr(msg);
- System.exit(-1);
+ EditLog.exitOnWriteFailure(new IOException(msg));
return 0; // unreachable!
}
@@ -298,7 +299,7 @@ public class BDBJEJournal implements Journal { //
CHECKSTYLE IGNORE THIS LINE: B
+ currentJournalDB.getDatabaseName();
LOG.error(msg);
LogUtils.stderr(msg);
- System.exit(-1);
+ EditLog.exitOnWriteFailure(e);
} catch (DatabaseException e) {
LOG.error("catch an exception when writing to database. sleep
and retry. journal id {}", id, e);
try {
@@ -314,7 +315,7 @@ public class BDBJEJournal implements Journal { //
CHECKSTYLE IGNORE THIS LINE: B
+ currentJournalDB.getDatabaseName();
LOG.error(msg);
LogUtils.stderr(msg);
- System.exit(-1);
+ EditLog.exitOnWriteFailure(new IOException(msg));
}
return id;
}
diff --git a/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
b/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
index 68addc21ffc..c437539eac8 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/persist/EditLog.java
@@ -133,20 +133,26 @@ import java.util.concurrent.atomic.AtomicLong;
public class EditLog {
public static final Logger LOG = LogManager.getLogger(EditLog.class);
+ // Set when this frontend exits because the edit log can not be written.
The in-memory metadata may
+ // already be ahead of the journal by then, so the shutdown hook must not
keep serving requests.
+ private static volatile boolean writeFailed = false;
+
// Helper class to hold log edit requests.
// Public so that callers can enqueue inside a lock and await outside it.
public static class EditLogItem {
static AtomicLong nextUid = new AtomicLong(0);
final short op;
- final Writable writable;
+ // Serialized by the thread that submits the edit, while it still
holds the lock that guards the
+ // data object. The flusher writes these bytes and never reads an
object that may still change.
+ final JournalBatch.Entity entity;
final Object lock = new Object();
volatile boolean finished = false;
long logId = -1;
long uid = -1;
- EditLogItem(short op, Writable writable) {
+ EditLogItem(short op, JournalBatch.Entity entity) {
this.op = op;
- this.writable = writable;
+ this.entity = entity;
uid = nextUid.getAndIncrement();
}
@@ -160,8 +166,7 @@ public class EditLog {
try {
lock.wait();
} catch (InterruptedException e) {
- LOG.error("Fatal Error : write stream Exception");
- System.exit(-1);
+ exitOnWriteFailure(e);
}
}
}
@@ -169,6 +174,20 @@ public class EditLog {
}
}
+ public static boolean isWriteFailed() {
+ return writeFailed;
+ }
+
+ // The in-memory metadata has already changed when an edit can not be
written, and it can not be
+ // rolled back, so this frontend must stop. Every exit caused by a failed
journal write goes through
+ // here, including the ones the journal decides on by itself (see
BDBJEJournal), so that the shutdown
+ // hook does not wait for running queries.
+ public static void exitOnWriteFailure(Throwable t) {
+ writeFailed = true;
+ LOG.error("Fatal Error : write stream Exception", t);
+ System.exit(-1);
+ }
+
private final BlockingQueue<EditLogItem> logEditQueue = new
LinkedBlockingQueue<>();
private final Thread flushThread;
@@ -229,7 +248,7 @@ public class EditLog {
if (LOG.isDebugEnabled()) {
LOG.debug("try to flush editLog request: uid={}, op={}",
req.uid, req.op);
}
- journalBatch.addJournal(req.op, req.writable);
+ journalBatch.addEntity(req.entity);
if (journalBatch.shouldFlush()) {
long logId = journal.write(journalBatch);
logIdNumPairs.add(new long[]{logId,
journalBatch.getJournalEntities().size()});
@@ -266,8 +285,7 @@ public class EditLog {
if (journal instanceof BDBJEJournal) {
LOG.error("BDBJE stats : {}", ((BDBJEJournal)
journal).getBDBStats());
}
- LOG.error("Fatal Error : write stream Exception", t);
- System.exit(-1);
+ exitOnWriteFailure(t);
}
txId += batch.size();
@@ -1634,7 +1652,7 @@ public class EditLog {
* This method blocks until the log is written and returns the logId.
*/
public long logEditWithQueue(short op, Writable writable) {
- EditLogItem req = new EditLogItem(op, writable);
+ EditLogItem req = new EditLogItem(op, serializeEdit(op, writable));
if (LOG.isDebugEnabled()) {
LOG.debug("logEditWithQueue: op = {}, uid = {}", op, req.uid);
}
@@ -1656,8 +1674,7 @@ public class EditLog {
try {
req.lock.wait();
} catch (InterruptedException e) {
- LOG.error("Fatal Error : write stream Exception");
- System.exit(-1);
+ exitOnWriteFailure(e);
}
}
}
@@ -1684,8 +1701,9 @@ public class EditLog {
throw new Error("Fatal Error : no editLog stream");
}
- EditLogItem req = new EditLogItem(op, writable);
+ EditLogItem req;
if (Config.enable_batch_editlog && op != OperationType.OP_TIMESTAMP) {
+ req = new EditLogItem(op, serializeEdit(op, writable));
while (true) {
try {
logEditQueue.put(req);
@@ -1701,6 +1719,7 @@ public class EditLog {
}
} else {
// Non-batch mode: write directly (synchronous)
+ req = new EditLogItem(op, null);
long logId = logEditDirectly(op, writable);
req.logId = logId;
req.finished = true;
@@ -1708,6 +1727,19 @@ public class EditLog {
return req;
}
+ // Serialize an edit in the caller's thread before it is queued. The
caller still holds the lock
+ // that guards the data object here; once the edit is in the queue the
caller releases that lock
+ // and other threads may change the object while the edit waits for the
flusher.
+ private static JournalBatch.Entity serializeEdit(short op, Writable
writable) {
+ JournalBatch.Entity entity = null;
+ try {
+ entity = JournalBatch.serialize(op, writable);
+ } catch (Throwable t) {
+ exitOnWriteFailure(t);
+ }
+ return entity;
+ }
+
private synchronized long logEditDirectly(short op, Writable writable) {
long logId = -1;
try {
@@ -1718,8 +1750,7 @@ public class EditLog {
if (journal instanceof BDBJEJournal) {
LOG.error("BDBJE stats : {}", ((BDBJEJournal)
journal).getBDBStats());
}
- LOG.error("Fatal Error : write stream Exception", t);
- System.exit(-1);
+ exitOnWriteFailure(t);
}
// get a new transactionId
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/transaction/DatabaseTransactionMgr.java
b/fe/fe-core/src/main/java/org/apache/doris/transaction/DatabaseTransactionMgr.java
index b7f3ea18ebf..463b83e3b25 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/transaction/DatabaseTransactionMgr.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/transaction/DatabaseTransactionMgr.java
@@ -1450,8 +1450,18 @@ public class DatabaseTransactionMgr {
}
}
+ // The check removes the commit infos of dropped tables and partitions
from the transaction state. A
+ // commit or finish of the same transaction serializes that state for the
edit log under its monitor,
+ // so the removal must not run while the serialization does.
private boolean finishCheckPartitionVersion(TransactionState
transactionState, Database db,
List<Pair<OlapTable, Partition>> relatedTblPartitions) {
+ synchronized (transactionState) {
+ return unprotectedFinishCheckPartitionVersion(transactionState,
db, relatedTblPartitions);
+ }
+ }
+
+ private boolean unprotectedFinishCheckPartitionVersion(TransactionState
transactionState, Database db,
+ List<Pair<OlapTable, Partition>> relatedTblPartitions) {
Iterator<TableCommitInfo> tableCommitInfoIterator
=
transactionState.getIdToTableCommitInfos().values().iterator();
while (tableCommitInfoIterator.hasNext()) {
@@ -1501,7 +1511,16 @@ public class DatabaseTransactionMgr {
return true;
}
+ // Same as finishCheckPartitionVersion: the check removes dropped tables
and partitions from the
+ // transaction state, so it holds the monitor that guards the
serialization of that state.
private boolean finishCheckPartitionVersionWithSubTxns(TransactionState
transactionState, Database db) {
+ synchronized (transactionState) {
+ return
unprotectedFinishCheckPartitionVersionWithSubTxns(transactionState, db);
+ }
+ }
+
+ private boolean
unprotectedFinishCheckPartitionVersionWithSubTxns(TransactionState
transactionState,
+ Database db) {
List<Pair<OlapTable, Partition>> relatedTblPartitions = new
ArrayList<>();
Map<Long, Long> partitionToVisibleVersion = new HashMap<>();
Iterator<Long> iterator = transactionState.getSubTxnIds().iterator();
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/transaction/PublishVersionDaemon.java
b/fe/fe-core/src/main/java/org/apache/doris/transaction/PublishVersionDaemon.java
index 412e4b3de5d..9c7b1df02ee 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/transaction/PublishVersionDaemon.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/transaction/PublishVersionDaemon.java
@@ -186,15 +186,17 @@ public class PublishVersionDaemon extends MasterDaemon {
private void tryFinishOneTxn(TransactionState transactionState,
SystemInfoService infoService,
GlobalTransactionMgrIface globalTransactionMgr) {
- Map<Long, Map<Long, Long>> tableIdToTabletDeltaRows =
Maps.newHashMap();
+ // In parallel mode the executor refreshes delta rows when its finish
attempt runs. Leave that attempt
+ // to the worker so the daemon does not wait for the monitor used by
commit and finish serialization.
+ if (publishingTxnIds.contains(transactionState.getTransactionId())) {
+ return;
+ }
AtomicBoolean hasBackendAliveAndUnfinishedTask = new
AtomicBoolean(false);
Set<Long> notFinishTaskBe = Sets.newHashSet();
transactionState.getPublishVersionTasks().forEach((key, tasks) -> {
long beId = key;
for (PublishVersionTask task : tasks) {
- if (task.isFinished()) {
- calculateTaskUpdateRows(tableIdToTabletDeltaRows, task);
- } else {
+ if (!task.isFinished()) {
if (infoService.checkBackendAlive(task.getBackendId())) {
hasBackendAliveAndUnfinishedTask.set(true);
}
@@ -203,7 +205,6 @@ public class PublishVersionDaemon extends MasterDaemon {
}
});
- transactionState.setTableIdToTabletDeltaRows(tableIdToTabletDeltaRows);
if (LOG.isDebugEnabled()) {
LOG.debug("notFinishTaskBe {}, trans {}", notFinishTaskBe,
transactionState);
}
@@ -276,6 +277,18 @@ public class PublishVersionDaemon extends MasterDaemon {
}
try {
+ // Collect responses here, including those received while this
attempt was queued. Updating the
+ // state takes its monitor, which may still be held by a commit
waiting for journal I/O; in parallel
+ // mode only this worker should wait, while the daemon continues
publishing other transactions.
+ Map<Long, Map<Long, Long>> tableIdToTabletDeltaRows =
Maps.newHashMap();
+ transactionState.getPublishVersionTasks().values().forEach(tasks
-> {
+ for (PublishVersionTask task : tasks) {
+ if (task.isFinished()) {
+ calculateTaskUpdateRows(tableIdToTabletDeltaRows,
task);
+ }
+ }
+ });
+
transactionState.setTableIdToTabletDeltaRows(tableIdToTabletDeltaRows);
Map<Long, Long> txnPartitionVersions = Maps.newHashMap();
Map<Long, Set<Long>> txnBackendPartitions = Maps.newHashMap();
// one transaction exception should not affect other transaction
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
b/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
index a271c866c72..af8c64c92d7 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/transaction/TransactionState.java
@@ -836,7 +836,9 @@ public class TransactionState implements Writable,
GsonPostProcessable {
return tableIdToTabletDeltaRows;
}
- public void setTableIdToTabletDeltaRows(Map<Long, Map<Long, Long>>
tableIdToTabletDeltaRows) {
+ // PublishVersionDaemon calls this without any other lock. The monitor
keeps it from changing the map
+ // while a commit or finish is serializing this state for the edit log
under the same monitor.
+ public synchronized void setTableIdToTabletDeltaRows(Map<Long, Map<Long,
Long>> tableIdToTabletDeltaRows) {
this.tableIdToTabletDeltaRows.putAll(tableIdToTabletDeltaRows);
}
@@ -853,7 +855,7 @@ public class TransactionState implements Writable,
GsonPostProcessable {
}
// reduce memory
- public void pruneAfterVisible() {
+ public synchronized void pruneAfterVisible() {
publishVersionTasks.clear();
tableIdToTabletDeltaRows.clear();
involvedBackends.clear();
diff --git a/fe/fe-core/src/test/java/org/apache/doris/DorisFETest.java
b/fe/fe-core/src/test/java/org/apache/doris/DorisFETest.java
new file mode 100644
index 00000000000..817dec38455
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/DorisFETest.java
@@ -0,0 +1,79 @@
+// 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;
+
+import org.apache.doris.common.jmockit.Deencapsulation;
+import org.apache.doris.persist.EditLog;
+import org.apache.doris.qe.Coordinator;
+import org.apache.doris.qe.QeProcessorImpl;
+import org.apache.doris.thrift.TQueryOptions;
+import org.apache.doris.thrift.TUniqueId;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.time.Duration;
+
+public class DorisFETest {
+
+ // A frontend that can not write its edit log exits through the shutdown
hook. Waiting there for running
+ // queries (up to 300 seconds) would keep it serving metadata that can no
longer be persisted, while every
+ // thread that writes the edit log stays blocked with its locks held.
+ @Test
+ public void testGracefulShutdownDoesNotWaitAfterEditLogWriteFailure()
throws Exception {
+ Coordinator coordinator = Mockito.mock(Coordinator.class);
+ Mockito.when(coordinator.getQueryOptions()).thenReturn(new
TQueryOptions());
+ TUniqueId queryId = new TUniqueId(10L, 20L);
+ QeProcessorImpl.INSTANCE.registerQuery(queryId, new
QeProcessorImpl.QueryInfo(coordinator));
+ Deencapsulation.setField(EditLog.class, "writeFailed", true);
+ try {
+ Assertions.assertTimeoutPreemptively(Duration.ofSeconds(10),
DorisFE::gracefulShutdown);
+ } finally {
+ Deencapsulation.setField(EditLog.class, "writeFailed", false);
+ QeProcessorImpl.INSTANCE.unregisterQuery(queryId);
+ }
+ }
+
+ // The edit log may also fail after the hook has started to wait, for
example when SIGTERM or an exit that does
+ // not come from the edit log started it while an INSERT was still
committing. The wait must end then as well.
+ @Test
+ public void
testGracefulShutdownStopsWaitingWhenEditLogWriteFailsWhileWaiting() throws
Exception {
+ Coordinator coordinator = Mockito.mock(Coordinator.class);
+ Mockito.when(coordinator.getQueryOptions()).thenReturn(new
TQueryOptions());
+ TUniqueId queryId = new TUniqueId(10L, 21L);
+ QeProcessorImpl.INSTANCE.registerQuery(queryId, new
QeProcessorImpl.QueryInfo(coordinator));
+ Thread shutdown = new Thread(DorisFE::gracefulShutdown,
"graceful-shutdown");
+ try {
+ shutdown.start();
+ // The hook sleeps between two looks at the running queries.
+ long deadline = System.currentTimeMillis() + 10_000L;
+ while (shutdown.getState() != Thread.State.TIMED_WAITING &&
System.currentTimeMillis() < deadline) {
+ Thread.sleep(10);
+ }
+ Assertions.assertEquals(Thread.State.TIMED_WAITING,
shutdown.getState());
+ Deencapsulation.setField(EditLog.class, "writeFailed", true);
+ shutdown.join(10_000L);
+ Assertions.assertFalse(shutdown.isAlive());
+ } finally {
+ Deencapsulation.setField(EditLog.class, "writeFailed", false);
+ QeProcessorImpl.INSTANCE.unregisterQuery(queryId);
+ shutdown.join();
+ }
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBJEJournalTest.java
b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBJEJournalTest.java
index 11c98d7afd6..eb978e4df8c 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBJEJournalTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/journal/bdbje/BDBJEJournalTest.java
@@ -22,14 +22,18 @@ import org.apache.doris.common.FeConstants;
import org.apache.doris.common.Pair;
import org.apache.doris.common.io.Text;
import org.apache.doris.common.io.Writable;
+import org.apache.doris.common.jmockit.Deencapsulation;
import org.apache.doris.journal.JournalBatch;
import org.apache.doris.journal.JournalCursor;
import org.apache.doris.journal.JournalEntity;
+import org.apache.doris.persist.EditLog;
import org.apache.doris.persist.OperationType;
import org.apache.doris.system.SystemInfoService.HostInfo;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
+import com.sleepycat.je.Database;
+import com.sleepycat.je.OperationStatus;
import com.sleepycat.je.rep.ReplicatedEnvironment;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
@@ -37,6 +41,7 @@ import org.apache.logging.log4j.Logger;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.RepeatedTest;
+import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
@@ -362,4 +367,39 @@ public class BDBJEJournalTest { // CHECKSTYLE IGNORE THIS
LINE: BDBJE should use
journal.close();
}
}
+
+ // This journal exits the frontend by itself when it can not complete a
write. Such an exit must go through
+ // EditLog.exitOnWriteFailure, which records the failure so that the
shutdown hook does not wait for running
+ // queries. Each case below is a real failure of the journal; only the
exit itself is replaced.
+ @Test
+ public void testWriteFailuresExitThroughEditLog() throws Exception {
+ String nodeName = Env.genFeNodeName("127.0.0.1", 9010, false);
+ Env mockEnv = Mockito.mock(Env.class);
+
Mockito.when(mockEnv.getBdbDir()).thenReturn(createTmpDir().getAbsolutePath());
+ Mockito.when(mockEnv.getSelfNode()).thenReturn(new
HostInfo("127.0.0.1", 9010));
+ // A database that never accepts a put, and that holds more journals
than the journal ids handed out.
+ Database database = Mockito.mock(Database.class);
+ Mockito.when(database.put(Mockito.any(), Mockito.any(),
Mockito.any())).thenReturn(OperationStatus.KEYEXIST);
+ Mockito.when(database.count()).thenReturn(5L);
+ Mockito.when(database.getDatabaseName()).thenReturn("1");
+ RuntimeException exit = new RuntimeException("exit on write failure");
+
+ try (MockedStatic<Env> mockedEnvStatic = Mockito.mockStatic(Env.class,
Mockito.CALLS_REAL_METHODS);
+ MockedStatic<EditLog> mockedEditLog =
Mockito.mockStatic(EditLog.class)) {
+ mockedEnvStatic.when(Env::getServingEnv).thenReturn(mockEnv);
+ mockedEditLog.when(() ->
EditLog.exitOnWriteFailure(Mockito.any())).thenThrow(exit);
+ BDBJEJournal journal = new BDBJEJournal(nodeName);
+ Deencapsulation.setField(journal, "currentJournalDB", database);
+
+ // A direct write gives up after its retries.
+ Writable writable = out -> Text.writeString(out, "data");
+ Assertions.assertSame(exit,
Assertions.assertThrows(RuntimeException.class,
+ () -> journal.write(OperationType.OP_START_ROLLUP,
writable)));
+ mockedEditLog.verify(() ->
EditLog.exitOnWriteFailure(Mockito.any()), Mockito.times(1));
+
+ // A roll finds journals that this journal did not write.
+ Assertions.assertSame(exit,
Assertions.assertThrows(RuntimeException.class, journal::rollJournal));
+ mockedEditLog.verify(() ->
EditLog.exitOnWriteFailure(Mockito.any()), Mockito.times(2));
+ }
+ }
}
diff --git a/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java
b/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java
index c1f22307124..e95324d08ef 100644
--- a/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java
+++ b/fe/fe-core/src/test/java/org/apache/doris/persist/EditLogTest.java
@@ -19,9 +19,24 @@ package org.apache.doris.persist;
import org.apache.doris.catalog.Env;
import org.apache.doris.common.Config;
+import org.apache.doris.common.FeMetaVersion;
+import org.apache.doris.common.io.Text;
import org.apache.doris.common.jmockit.Deencapsulation;
+import org.apache.doris.journal.Journal;
+import org.apache.doris.journal.JournalBatch;
+import org.apache.doris.journal.JournalEntity;
import org.apache.doris.journal.bdbje.Timestamp;
-
+import org.apache.doris.meta.MetaContext;
+import org.apache.doris.persist.EditLog.EditLogItem;
+import org.apache.doris.thrift.TUniqueId;
+import org.apache.doris.transaction.TransactionState;
+import org.apache.doris.transaction.TransactionState.LoadJobSourceType;
+import org.apache.doris.transaction.TransactionState.TxnCoordinator;
+import org.apache.doris.transaction.TransactionState.TxnSourceType;
+import org.apache.doris.transaction.TransactionStatus;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@@ -30,12 +45,21 @@ import org.junit.jupiter.api.io.TempDir;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
public class EditLogTest {
private String meta = "editLogTestDir/";
@@ -44,6 +68,7 @@ public class EditLogTest {
private int originalCloudEditLogRollIntervalSecond;
private String originalDeployMode;
private String originalCloudUniqueId;
+ private boolean originalEnableBatchEditlog;
@TempDir
public Path temporaryFolder;
@@ -55,6 +80,7 @@ public class EditLogTest {
originalCloudEditLogRollIntervalSecond =
Config.cloud_edit_log_roll_interval_second;
originalDeployMode = Config.deploy_mode;
originalCloudUniqueId = Config.cloud_unique_id;
+ originalEnableBatchEditlog = Config.enable_batch_editlog;
Config.edit_log_type = "local";
Config.edit_log_roll_num = Integer.MAX_VALUE;
@@ -69,6 +95,7 @@ public class EditLogTest {
Config.cloud_edit_log_roll_interval_second =
originalCloudEditLogRollIntervalSecond;
Config.deploy_mode = originalDeployMode;
Config.cloud_unique_id = originalCloudUniqueId;
+ Config.enable_batch_editlog = originalEnableBatchEditlog;
}
public void mkdir() {
@@ -262,4 +289,108 @@ public class EditLogTest {
}
}
}
+
+ // A queued edit is written by the flusher thread later. The caller
releases its lock as soon as the
+ // edit is queued, and other threads (PublishVersionDaemon,
finishTransaction) keep changing the same
+ // TransactionState while the edit waits. The journal must get the state
of the moment it was queued.
+ @Test
+ public void testSubmitEditWritesStateAtSubmission() throws Exception {
+ assertQueuedEditWritesStateAtSubmission(true);
+ }
+
+ @Test
+ public void testLogEditWithQueueWritesStateAtSubmission() throws Exception
{
+ assertQueuedEditWritesStateAtSubmission(false);
+ }
+
+ private void assertQueuedEditWritesStateAtSubmission(boolean
submitWithoutWaiting) throws Exception {
+ Config.enable_batch_editlog = true;
+ File imageDir =
Files.createDirectories(temporaryFolder.resolve("queued_edit_" +
submitWithoutWaiting))
+ .toFile();
+ Env env = Mockito.mock(Env.class);
+ Mockito.when(env.getImageDir()).thenReturn(imageDir.getAbsolutePath());
+ try (MockedStatic<Env> envStatic = Mockito.mockStatic(Env.class)) {
+ envStatic.when(Env::getCurrentEnv).thenReturn(env);
+ EditLog editLog = new EditLog("test");
+
+ // The first write parks the flusher until the test releases it,
so the edit under test has
+ // to wait in the queue.
+ CountDownLatch flusherParked = new CountDownLatch(1);
+ CountDownLatch releaseFlusher = new CountDownLatch(1);
+ List<byte[]> writtenEntities = Collections.synchronizedList(new
ArrayList<>());
+ AtomicLong nextJournalId = new AtomicLong(1);
+ Journal journal = Mockito.mock(Journal.class);
+
Mockito.when(journal.write(Mockito.any(JournalBatch.class))).thenAnswer(invocation
-> {
+ JournalBatch batch = invocation.getArgument(0);
+ for (JournalBatch.Entity entity : batch.getJournalEntities()) {
+ writtenEntities.add(entity.getBinaryData().clone());
+ }
+ if (flusherParked.getCount() > 0) {
+ flusherParked.countDown();
+ releaseFlusher.await();
+ }
+ return
nextJournalId.getAndAdd(batch.getJournalEntities().size());
+ });
+ Deencapsulation.setField(editLog, "journal", journal);
+ try {
+ EditLogItem parked =
editLog.submitEdit(OperationType.OP_SAVE_NEXTID, new Text("1"));
+ Assertions.assertTrue(flusherParked.await(30,
TimeUnit.SECONDS));
+
+ TransactionState transactionState = new
TransactionState(1000L, Lists.newArrayList(2000L),
+ 3000L, "label_queued_edit", new TUniqueId(1L, 2L),
LoadJobSourceType.BACKEND_STREAMING,
+ new TxnCoordinator(TxnSourceType.BE, 0, "127.0.0.1",
System.currentTimeMillis()),
+ -1L, 60 * 1000L);
+
transactionState.setTransactionStatus(TransactionStatus.COMMITTED);
+ EditLogItem queued = null;
+ Thread logger = null;
+ if (submitWithoutWaiting) {
+ queued =
editLog.submitEdit(OperationType.OP_UPSERT_TRANSACTION_STATE, transactionState);
+ } else {
+ logger = new Thread(() -> editLog.logEditWithQueue(
+ OperationType.OP_UPSERT_TRANSACTION_STATE,
transactionState));
+ logger.start();
+ BlockingQueue<EditLogItem> queue =
Deencapsulation.getField(editLog, "logEditQueue");
+ long deadline = System.currentTimeMillis() +
TimeUnit.SECONDS.toMillis(30);
+ while (queue.isEmpty()) {
+ Assertions.assertTrue(System.currentTimeMillis() <
deadline);
+ Thread.sleep(10);
+ }
+ }
+
+ // What the publish of the same transaction does while its
commit edit waits in the queue.
+ Map<Long, Map<Long, Long>> deltaRows = Maps.newHashMap();
+ deltaRows.put(2000L, Maps.newHashMap());
+ deltaRows.get(2000L).put(4000L, 10L);
+ transactionState.setTableIdToTabletDeltaRows(deltaRows);
+
transactionState.setTransactionStatus(TransactionStatus.VISIBLE);
+
+ releaseFlusher.countDown();
+ parked.await();
+ if (submitWithoutWaiting) {
+ queued.await();
+ } else {
+ logger.join(TimeUnit.SECONDS.toMillis(30));
+ Assertions.assertFalse(logger.isAlive());
+ }
+
+ Assertions.assertEquals(2, writtenEntities.size());
+ MetaContext metaContext = new MetaContext();
+ metaContext.setMetaVersion(FeMetaVersion.VERSION_CURRENT);
+ metaContext.setThreadLocalInfo();
+ try {
+ JournalEntity entity = new JournalEntity();
+ entity.readFields(new DataInputStream(new
ByteArrayInputStream(writtenEntities.get(1))));
+
Assertions.assertEquals(OperationType.OP_UPSERT_TRANSACTION_STATE,
entity.getOpCode());
+ TransactionState persisted = (TransactionState)
entity.getData();
+ Assertions.assertEquals(TransactionStatus.COMMITTED,
persisted.getTransactionStatus());
+
Assertions.assertTrue(persisted.getTableIdToTabletDeltaRows().isEmpty());
+ } finally {
+ MetaContext.remove();
+ }
+ } finally {
+ releaseFlusher.countDown();
+ editLog.close();
+ }
+ }
+ }
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/transaction/PublishVersionDaemonTest.java
b/fe/fe-core/src/test/java/org/apache/doris/transaction/PublishVersionDaemonTest.java
new file mode 100644
index 00000000000..fb3cc0530ee
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/transaction/PublishVersionDaemonTest.java
@@ -0,0 +1,200 @@
+// 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.transaction;
+
+import org.apache.doris.common.Config;
+import org.apache.doris.common.FeMetaVersion;
+import org.apache.doris.journal.JournalBatch;
+import org.apache.doris.journal.JournalEntity;
+import org.apache.doris.meta.MetaContext;
+import org.apache.doris.persist.OperationType;
+import org.apache.doris.system.SystemInfoService;
+import org.apache.doris.task.PublishVersionTask;
+import org.apache.doris.thrift.TUniqueId;
+import org.apache.doris.transaction.TransactionState.LoadJobSourceType;
+import org.apache.doris.transaction.TransactionState.TxnCoordinator;
+import org.apache.doris.transaction.TransactionState.TxnSourceType;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mockito;
+
+import java.io.ByteArrayInputStream;
+import java.io.DataInputStream;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.FutureTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+
+public class PublishVersionDaemonTest {
+ private boolean originalParallelPublish;
+ private int originalPoolSize;
+ private Field executorsField;
+ private Object originalExecutors;
+ private List<ExecutorService> createdExecutors = new ArrayList<>();
+ private ExecutorService executor;
+ private PublishVersionDaemon daemon;
+
+ @BeforeEach
+ public void setUp() throws Exception {
+ originalParallelPublish = Config.enable_parallel_publish_version;
+ originalPoolSize = Config.publish_thread_pool_num;
+ executorsField =
PublishVersionDaemon.class.getDeclaredField("publishExecutors");
+ executorsField.setAccessible(true);
+ originalExecutors = executorsField.get(null);
+ Config.enable_parallel_publish_version = true;
+ Config.publish_thread_pool_num = 1;
+ executorsField.set(null, createdExecutors);
+ daemon = new PublishVersionDaemon();
+ executor = Mockito.mock(ExecutorService.class);
+ executorsField.set(null, Lists.newArrayList(executor));
+ }
+
+ @AfterEach
+ public void tearDown() throws Exception {
+ createdExecutors.forEach(ExecutorService::shutdownNow);
+ executorsField.set(null, originalExecutors);
+ Config.enable_parallel_publish_version = originalParallelPublish;
+ Config.publish_thread_pool_num = originalPoolSize;
+ MetaContext.remove();
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void testDaemonDoesNotWaitForCommittingTransaction(boolean
taskFinished) throws Exception {
+ TransactionState state = newTransactionState();
+ state.setSendedTask();
+ PublishVersionTask task = newTask(state, 1L, 10L);
+ task.setFinished(taskFinished);
+ SystemInfoService infoService = Mockito.mock(SystemInfoService.class);
+ Mockito.when(infoService.checkBackendAlive(1L)).thenReturn(true);
+ GlobalTransactionMgrIface transactionMgr =
Mockito.mock(GlobalTransactionMgrIface.class);
+ FutureTask<Void> round = new FutureTask<>(() -> {
+ tryFinish(state, infoService, transactionMgr);
+ return null;
+ });
+ Thread thread = new Thread(round);
+ try {
+ // A commit exposes COMMITTED before journal durability and can
retain this monitor while
+ // waiting for timestamp I/O or synchronous persistence. There is
no publishing ID yet.
+ synchronized (state) {
+ thread.start();
+ round.get(5, TimeUnit.SECONDS);
+
Assertions.assertTrue(state.getTableIdToTabletDeltaRows().isEmpty());
+ }
+ } finally {
+ thread.join(TimeUnit.SECONDS.toMillis(30));
+ }
+ Assertions.assertFalse(thread.isAlive());
+ Mockito.verify(executor, Mockito.times(taskFinished ? 1 :
0)).execute(Mockito.any(Runnable.class));
+ Mockito.verifyNoInteractions(transactionMgr);
+ }
+
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ public void testFinishCollectsLatestTaskDeltaRows(boolean parallel) throws
Exception {
+ Config.enable_parallel_publish_version = parallel;
+ TransactionState state = newTransactionState();
+ PublishVersionTask first = newTask(state, 1L, 10L);
+ PublishVersionTask second = newTask(state, 2L, 20L);
+ PublishVersionTask failed = newTask(state, 3L, 100L);
+ failed.addErrorTablets(Lists.newArrayList(30000L));
+ newTask(state, 4L, 1000L); // An unfinished response must not
contribute delta rows.
+ SystemInfoService infoService = Mockito.mock(SystemInfoService.class);
+
Mockito.when(infoService.checkBackendAlive(Mockito.anyLong())).thenReturn(true);
+ GlobalTransactionMgrIface transactionMgr =
Mockito.mock(GlobalTransactionMgrIface.class);
+ AtomicReference<TransactionState> persisted = new AtomicReference<>();
+ long dbId = state.getDbId();
+ long transactionId = state.getTransactionId();
+ Mockito.doAnswer(invocation -> {
+ state.setTransactionStatus(TransactionStatus.VISIBLE);
+ synchronized (state) {
+ byte[] bytes =
JournalBatch.serialize(OperationType.OP_UPSERT_TRANSACTION_STATE,
state).getBinaryData();
+ JournalEntity entity = new JournalEntity();
+ entity.readFields(new DataInputStream(new
ByteArrayInputStream(bytes)));
+ persisted.set((TransactionState) entity.getData());
+ }
+ return null;
+ }).when(transactionMgr).finishTransaction(Mockito.eq(dbId),
Mockito.eq(transactionId),
+ Mockito.anyMap(), Mockito.anyMap());
+ MetaContext context = new MetaContext();
+ context.setMetaVersion(FeMetaVersion.VERSION_CURRENT);
+ context.setThreadLocalInfo();
+
+ if (parallel) {
+ // The timed-out attempt is queued while no response has finished.
+ tryFinish(state, infoService, transactionMgr);
+ Mockito.verifyNoInteractions(transactionMgr);
+ }
+ first.setFinished(true);
+ second.setFinished(true);
+ failed.setFinished(true);
+ if (parallel) {
+ // A later daemon round skips the queued attempt. The worker must
refresh its own deltas.
+ tryFinish(state, infoService, transactionMgr);
+ ArgumentCaptor<Runnable> job =
ArgumentCaptor.forClass(Runnable.class);
+ Mockito.verify(executor).execute(job.capture());
+ job.getValue().run();
+ } else {
+ tryFinish(state, infoService, transactionMgr);
+ }
+ Assertions.assertNotNull(persisted.get());
+ Assertions.assertEquals(TransactionStatus.VISIBLE,
persisted.get().getTransactionStatus());
+ Assertions.assertEquals(Map.of(20000L, Map.of(30000L, 30L)),
+ persisted.get().getTableIdToTabletDeltaRows());
+ Assertions.assertTrue(state.getTableIdToTabletDeltaRows().isEmpty());
+ Assertions.assertTrue(state.getPublishVersionTasks().isEmpty());
+ }
+
+ private static TransactionState newTransactionState() {
+ TransactionState state = new TransactionState(1000L,
Lists.newArrayList(20000L),
+ 3000L, "label_publish", new TUniqueId(1L, 2L),
LoadJobSourceType.BACKEND_STREAMING,
+ new TxnCoordinator(TxnSourceType.BE, 0, "127.0.0.1",
System.currentTimeMillis()), -1L, 60000L);
+ state.setTransactionStatus(TransactionStatus.COMMITTED);
+ return state;
+ }
+
+ private static PublishVersionTask newTask(TransactionState state, long
backendId, long rows) {
+ PublishVersionTask task = new PublishVersionTask(backendId,
state.getTransactionId(), state.getDbId(),
+ null, System.currentTimeMillis());
+ Map<Long, Map<Long, Long>> deltas = Maps.newHashMap();
+ deltas.put(20000L, Map.of(30000L, rows));
+ task.setTableIdTabletsDeltaRows(deltas);
+ state.addPublishVersionTask(backendId, task);
+ return task;
+ }
+
+ private void tryFinish(TransactionState state, SystemInfoService
infoService,
+ GlobalTransactionMgrIface transactionMgr) throws Exception {
+ Method method =
PublishVersionDaemon.class.getDeclaredMethod("tryFinishOneTxn",
TransactionState.class,
+ SystemInfoService.class, GlobalTransactionMgrIface.class);
+ method.setAccessible(true);
+ method.invoke(daemon, state, infoService, transactionMgr);
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java
b/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java
index 4bd5cec17bd..a8d05bdf9a0 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/transaction/TransactionStateTest.java
@@ -17,6 +17,8 @@
package org.apache.doris.transaction;
+import org.apache.doris.catalog.Database;
+import org.apache.doris.catalog.Env;
import org.apache.doris.common.FeMetaVersion;
import org.apache.doris.common.jmockit.Deencapsulation;
import org.apache.doris.load.EtlStatus;
@@ -27,6 +29,7 @@ import org.apache.doris.load.loadv2.LoadJobFinalOperation;
import org.apache.doris.load.routineload.RLTaskTxnCommitAttachment;
import org.apache.doris.load.routineload.kafka.KafkaProgress;
import org.apache.doris.meta.MetaContext;
+import org.apache.doris.system.SystemInfoService;
import org.apache.doris.thrift.TEtlState;
import org.apache.doris.thrift.TKafkaRLTaskProgress;
import org.apache.doris.thrift.TUniqueId;
@@ -39,6 +42,7 @@ import com.google.common.collect.Maps;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
import java.io.DataInputStream;
import java.io.DataOutputStream;
@@ -46,7 +50,13 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
public class TransactionStateTest {
@@ -163,4 +173,126 @@ public class TransactionStateTest {
Assertions.assertEquals(100L, (long)
readKafkaProgress.getOffsetByPartition().getOrDefault(1, -1L));
});
}
+
+ // Commit and finish serialize the state for the edit log while they hold
its monitor. The writers that
+ // change it later without any lock of their own (PublishVersionDaemon,
the version check of finish)
+ // must wait for that monitor.
+ @Test
+ public void testPublishUpdatesWaitForMonitor() throws Exception {
+ TransactionState transactionState = newTransactionState();
+ Map<Long, Map<Long, Long>> deltaRows = Maps.newHashMap();
+ deltaRows.put(20000L, Maps.newHashMap());
+ deltaRows.get(20000L).put(30000L, 10L);
+
+ Thread setter = new Thread(() ->
transactionState.setTableIdToTabletDeltaRows(deltaRows));
+ synchronized (transactionState) {
+ setter.start();
+ waitUntilBlocked(setter);
+
Assertions.assertTrue(transactionState.getTableIdToTabletDeltaRows().isEmpty());
+ }
+ setter.join(TimeUnit.SECONDS.toMillis(30));
+ Assertions.assertEquals(deltaRows,
transactionState.getTableIdToTabletDeltaRows());
+
+ Thread pruner = new Thread(transactionState::pruneAfterVisible);
+ synchronized (transactionState) {
+ pruner.start();
+ waitUntilBlocked(pruner);
+
Assertions.assertFalse(transactionState.getTableIdToTabletDeltaRows().isEmpty());
+ }
+ pruner.join(TimeUnit.SECONDS.toMillis(30));
+
Assertions.assertTrue(transactionState.getTableIdToTabletDeltaRows().isEmpty());
+ }
+
+ @Test
+ public void testFinishCheckPartitionVersionWaitsForMonitor() throws
Exception {
+ DatabaseTransactionMgr dbTransactionMgr = new
DatabaseTransactionMgr(1000L, Mockito.mock(Env.class), null);
+ // The mocked database has no tables, so the check removes the commit
info of a dropped table.
+ Database db = Mockito.mock(Database.class);
+
+ TransactionState transactionState = newTransactionState();
+ transactionState.putIdToTableCommitInfo(20000L, new
TableCommitInfo(20000L));
+ Method check =
DatabaseTransactionMgr.class.getDeclaredMethod("finishCheckPartitionVersion",
+ TransactionState.class, Database.class, List.class);
+ check.setAccessible(true);
+ Thread checker = new Thread(() -> invoke(check, dbTransactionMgr,
transactionState, db, new ArrayList<>()));
+ synchronized (transactionState) {
+ checker.start();
+ waitUntilBlocked(checker);
+ Assertions.assertEquals(1,
transactionState.getIdToTableCommitInfos().size());
+ }
+ checker.join(TimeUnit.SECONDS.toMillis(30));
+
Assertions.assertTrue(transactionState.getIdToTableCommitInfos().isEmpty());
+
+ TransactionState subTxnState = newTransactionState();
+ subTxnState.setSubTxnIds(Lists.newArrayList(3001L));
+ subTxnState.getSubTxnIdToTableCommitInfo().put(3001L, new
TableCommitInfo(20000L));
+ Method subTxnCheck = DatabaseTransactionMgr.class.getDeclaredMethod(
+ "finishCheckPartitionVersionWithSubTxns",
TransactionState.class, Database.class);
+ subTxnCheck.setAccessible(true);
+ Thread subTxnChecker = new Thread(() -> invoke(subTxnCheck,
dbTransactionMgr, subTxnState, db));
+ synchronized (subTxnState) {
+ subTxnChecker.start();
+ waitUntilBlocked(subTxnChecker);
+ Assertions.assertEquals(1, subTxnState.getSubTxnIds().size());
+ }
+ subTxnChecker.join(TimeUnit.SECONDS.toMillis(30));
+ Assertions.assertTrue(subTxnState.getSubTxnIds().isEmpty());
+ }
+
+ // A publish executor finishes a transaction while it holds the monitor to
serialize the state for the edit log.
+ // The next round of PublishVersionDaemon must skip that transaction
instead of waiting for the monitor to set
+ // its delta rows again, which would hold up the publish of every other
transaction.
+ @Test
+ public void testPublishDaemonSkipsTransactionBeingFinished() throws
Exception {
+ PublishVersionDaemon daemon = new PublishVersionDaemon();
+ TransactionState transactionState = newTransactionState();
+ Map<Long, Map<Long, Long>> deltaRows = Maps.newHashMap();
+ deltaRows.put(20000L, Maps.newHashMap());
+ deltaRows.get(20000L).put(30000L, 10L);
+ transactionState.setTableIdToTabletDeltaRows(deltaRows);
+ Set<Long> publishingTxnIds = Deencapsulation.getField(daemon,
"publishingTxnIds");
+ publishingTxnIds.add(transactionState.getTransactionId());
+ Method tryFinish =
PublishVersionDaemon.class.getDeclaredMethod("tryFinishOneTxn",
TransactionState.class,
+ SystemInfoService.class, GlobalTransactionMgrIface.class);
+ tryFinish.setAccessible(true);
+
+ Thread round = new Thread(() -> invoke(tryFinish, daemon,
transactionState,
+ Mockito.mock(SystemInfoService.class),
Mockito.mock(GlobalTransactionMgrIface.class)));
+ synchronized (transactionState) {
+ round.start();
+ long deadline = System.currentTimeMillis() +
TimeUnit.SECONDS.toMillis(30);
+ while (round.getState() != Thread.State.TERMINATED) {
+ Assertions.assertNotEquals(Thread.State.BLOCKED,
round.getState(),
+ "the daemon waited for the monitor of a transaction
that is being finished");
+ Assertions.assertTrue(System.currentTimeMillis() < deadline,
"thread state: " + round.getState());
+ Thread.sleep(10);
+ }
+ }
+ Assertions.assertEquals(deltaRows,
transactionState.getTableIdToTabletDeltaRows());
+ }
+
+ private static TransactionState newTransactionState() {
+ return new TransactionState(1000L, Lists.newArrayList(20000L), 3000,
"label123", new TUniqueId(1L, 2L),
+ LoadJobSourceType.BACKEND_STREAMING,
+ new TxnCoordinator(TxnSourceType.BE, 0, "127.0.0.1",
System.currentTimeMillis()),
+ -1L, 60 * 1000L);
+ }
+
+ private static void invoke(Method method, Object target, Object... args) {
+ try {
+ method.invoke(target, args);
+ } catch (ReflectiveOperationException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static void waitUntilBlocked(Thread thread) throws
InterruptedException {
+ long deadline = System.currentTimeMillis() +
TimeUnit.SECONDS.toMillis(30);
+ while (thread.getState() != Thread.State.BLOCKED) {
+ Assertions.assertNotEquals(Thread.State.TERMINATED,
thread.getState(),
+ "the update did not wait for the monitor of the
transaction state");
+ Assertions.assertTrue(System.currentTimeMillis() < deadline,
"thread state: " + thread.getState());
+ Thread.sleep(10);
+ }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]