From 6dcef45fb6e69c85cab3a082f300df943a02a408 Mon Sep 17 00:00:00 2001 From: Jash Date: Fri, 13 Nov 2026 10:29:03 +0530 Subject: [PATCH] fix: stop a hung database from blocking Fatal and Panic from exiting fixes #5643 --- src/zm_db.cpp | 21 ++++++++++++++++++++- src/zm_db.h | 6 ++++++ src/zm_logger.cpp | 7 ++++++- 3 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/zm_db.cpp b/src/zm_db.cpp index b82ee1b95f..5113159cbb 100644 --- a/src/zm_db.cpp +++ b/src/zm_db.cpp @@ -365,7 +365,8 @@ zmDbQueue::zmDbQueue(size_t max_log_rows) : mMaxLogRows(max_log_rows), mLogRows(0), mDroppedLogs(0), - mTerminate(false) { + mTerminate(false), + mDone(false) { mThread = std::thread(&zmDbQueue::process, this); } @@ -404,6 +405,22 @@ void write_dropped_summary(size_t dropped) { } // namespace +bool zmDbQueue::stop(std::chrono::milliseconds wait) { + bool done; + { + std::unique_lock lock(mMutex); + mTerminate = true; + mCondition.notify_all(); + done = mDoneCondition.wait_for(lock, wait, [this] { return mDone; }); + } + + if (mThread.joinable()) { + if (done) mThread.join(); + else mThread.detach(); + } + return done; +} + void zmDbQueue::process() { std::unique_lock lock(mMutex); @@ -455,6 +472,8 @@ void zmDbQueue::process() { lock.lock(); } } + mDone = true; + mDoneCondition.notify_all(); } // end void zmDbQueue::process() void zmDbQueue::push(std::string &&sql, bool log_row, bool keep) { diff --git a/src/zm_db.h b/src/zm_db.h index 5d2094f2d6..10ac02c403 100644 --- a/src/zm_db.h +++ b/src/zm_db.h @@ -20,6 +20,7 @@ #ifndef ZM_DB_H #define ZM_DB_H +#include #include #include #include @@ -57,6 +58,8 @@ class zmDbQueue { std::mutex mMutex; std::condition_variable mCondition; bool mTerminate; + std::condition_variable mDoneCondition; + bool mDone; public: // Log rows past this many waiting are dropped; other writes never are. static constexpr size_t kMaxQueuedLogRows = 5000; @@ -69,6 +72,9 @@ class zmDbQueue { size_t logRowsDropped(); void process(); void stop(); + // Returns false, leaving the thread detached, if it is still inside a query + // after `wait`. + bool stop(std::chrono::milliseconds wait); }; class zmDbRow { diff --git a/src/zm_logger.cpp b/src/zm_logger.cpp index d66bb6038d..b35d6fd47e 100644 --- a/src/zm_logger.cpp +++ b/src/zm_logger.cpp @@ -604,7 +604,12 @@ void Logger::logPrint(bool hex, const char *filepath, int line, int level, const log_mutex.unlock(); if (level == FATAL || level == PANIC) { zm_terminate = true; - dbQueue.stop(); + if (!dbQueue.stop(std::chrono::seconds(5))) { + // The queue thread is stuck in a query to an unresponsive database and + // holds the connection, so it cannot be closed or joined. + if (level == PANIC) abort(); + _exit(-1); + } zmDbClose(); logTerm(); if (level == PANIC) abort();