From 837153cbd603eb7eac9a56a535c016262ca5b083 Mon Sep 17 00:00:00 2001 From: Giulio Eulisse <10544+ktf@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:51:38 +0100 Subject: [PATCH] DPL: make the stats command queue safe for concurrent updates and flushes updateStats appends to a fixed queue of commands and the one which finds it full flushes it. With a thread pool the loop and the pool threads update the same stats, and that went wrong several ways, all upstream: - A thread finding the queue full while another flushed waited on `while (cmds.size())`, which is the size of a std::array and never false, and it still counted as pending, which is what the flush waits for. Both waited for ever: SlowConsumer hung with the loop asleep inside updateStats, reached from DataRelayer::relay, and its producer blocked in Send. - processCommandQueue reopened the queue by storing nextCmd = 0 before insertedCmds = 0, both relaxed, so a command taken from the new queue could have its count wiped and never be processed. The flushing thread then reset both counters a second time after processCommandQueue had reopened the queue, losing whatever other threads had added in between. - processCommandQueue is also called directly, by the metrics flush on the loop, while pool threads may be adding commands. So processCommandQueue now takes a mutex, closes the queue before looking at it (whoever takes a command from then on finds it full and waits on that mutex), waits for those already writing, and reopens it in an order which cannot lose a count, also when a command throws. Taking a command and closing the queue are sequentially consistent with the pending count, so that either the flush sees a writer pending or the writer sees the queue closed. A thread finding the queue full stops counting as pending, waits for the mutex and flushes the queue only if nobody has reopened it meanwhile, so that threads which found it full together do not flush it one after the other, then goes round again. The fast path stays lock-free, and single-threaded behaviour, nextCmd back to 0 after a flush included, is unchanged. The new DataProcessingStatsConcurrentUpdates test has four threads add 1 twenty thousand times each while a fifth flushes the queue directly. Before, 5 runs out of 5 gave up after 10 s with threads still stuck; after, 200 runs out of 200 pass with the exact total. --- .../include/Framework/DataProcessingStats.h | 5 +- Framework/Core/src/DataProcessingStats.cxx | 62 +++++++++++-------- .../Core/test/test_DataProcessingStats.cxx | 42 +++++++++++++ 3 files changed, 83 insertions(+), 26 deletions(-) diff --git a/Framework/Core/include/Framework/DataProcessingStats.h b/Framework/Core/include/Framework/DataProcessingStats.h index d5e9ec14adc26..0d2a796c477d7 100644 --- a/Framework/Core/include/Framework/DataProcessingStats.h +++ b/Framework/Core/include/Framework/DataProcessingStats.h @@ -188,13 +188,16 @@ struct DataProcessingStats { char const* findMetricNameById(ProcessingStatsId id) const; /// This will process the queue of commands required to update the stats. /// It is meant to be called periodically by a single thread. - void processCommandQueue(); + /// With @a onlyIfFull, it does nothing if the queue is not full once it has the lock. + void processCommandQueue(bool onlyIfFull = false); void flushChangedMetrics(std::function const& callback); std::atomic statesSize = 0; std::array cmds = {}; + /// Held by processCommandQueue, so that the queue is flushed by one thread at a time. + std::mutex flushMutex; std::array metrics = {}; std::array updated = {}; std::array metricsNames = {}; diff --git a/Framework/Core/src/DataProcessingStats.cxx b/Framework/Core/src/DataProcessingStats.cxx index 8349af62acdc2..849e75b3a9cb3 100644 --- a/Framework/Core/src/DataProcessingStats.cxx +++ b/Framework/Core/src/DataProcessingStats.cxx @@ -57,29 +57,21 @@ void DataProcessingStats::updateStats(CommandSpec cmd) pendingCmds++; // Add a static mutex to protect the queue // Get the next available operation in an atomic way. - auto idx = nextCmd.fetch_add(1, std::memory_order_relaxed); - if (idx == cmds.size()) { - // We abort this command + // Sequentially consistent, like the increment of pendingCmds above and, in + // processCommandQueue, the close of the queue and the read of pendingCmds which + // follows: either the flush sees this command pending and waits for it, or this + // thread sees the queue closed. It also acquires the release which reopens the + // queue, so that a command taken from a fresh queue is counted after + // insertedCmds was reset. + auto idx = nextCmd.fetch_add(1); + while (idx >= cmds.size()) { + // Full, or being flushed. Flush it, unless whoever was flushing it already + // has reopened it by the time we get the lock, and go round again. Not + // pending meanwhile: the flush waits for every pending command. pendingCmds--; - while (pendingCmds.load(std::memory_order_relaxed) > 0) { - // We need to wait for all the pending commands to be processed. - // This is needed because we are going to flush the queue. - // We cannot flush the queue while there are pending commands - // as we might end up with a command being processed twice. - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - } - processCommandQueue(); - insertedCmds.store(0, std::memory_order_relaxed); - nextCmd.store(0, std::memory_order_relaxed); + processCommandQueue(true); pendingCmds++; - idx = nextCmd.fetch_add(1, std::memory_order_relaxed); - } else if (idx > cmds.size()) { - while (cmds.size()) { - // We need to wait for the flushing of the queue - std::this_thread::sleep_for(std::chrono::milliseconds(1)); - idx = nextCmd.load(std::memory_order_relaxed); - } - return updateStats(cmd); + idx = nextCmd.fetch_add(1); } // Save the command. assert(idx < cmds.size()); @@ -91,12 +83,34 @@ void DataProcessingStats::updateStats(CommandSpec cmd) updatedMetricsLapse++; } -void DataProcessingStats::processCommandQueue() +void DataProcessingStats::processCommandQueue(bool onlyIfFull) { + // With a thread pool, commands are added while this runs, and more than one + // thread may want to flush. So one flush at a time, and close the queue first: + // whoever takes a command from now on finds it full and waits here, while + // those who took one already finish writing it. + std::scoped_lock lock(flushMutex); + if (onlyIfFull && nextCmd.load() < cmds.size()) { + return; + } + nextCmd.exchange(cmds.size()); + while (pendingCmds.load() > 0) { + std::this_thread::yield(); + } + // Reopen in this order, so that nothing counted in the new queue is lost, and + // also if a command throws. + struct Reopen { + DataProcessingStats& stats; + ~Reopen() + { + stats.insertedCmds.store(0, std::memory_order_relaxed); + stats.nextCmd.store(0, std::memory_order_release); + } + } reopen{*this}; std::array order; // The range cannot be larger than the number of commands we have. auto range = insertedCmds.load(std::memory_order_relaxed); - if (insertedCmds.load(std::memory_order_relaxed) == 0) { + if (range == 0) { return; } @@ -196,8 +210,6 @@ void DataProcessingStats::processCommandQueue() } // No one should have tried to insert more commands while processing. assert(range == insertedCmds.load(std::memory_order_relaxed)); - nextCmd.store(0, std::memory_order_relaxed); - insertedCmds.store(0, std::memory_order_relaxed); } void DataProcessingStats::flushChangedMetrics(std::function const& callback) diff --git a/Framework/Core/test/test_DataProcessingStats.cxx b/Framework/Core/test/test_DataProcessingStats.cxx index 5f14ead966dc0..d07343edede07 100644 --- a/Framework/Core/test/test_DataProcessingStats.cxx +++ b/Framework/Core/test/test_DataProcessingStats.cxx @@ -16,6 +16,11 @@ #include #include +#include +#include +#include +#include + using namespace o2::framework; enum TestMetricsId { @@ -401,3 +406,40 @@ TEST_CASE("DataProcessingStatsPublishingRepeated") REQUIRE(updated.size() == 2); REQUIRE(count == 10); } + +TEST_CASE("DataProcessingStatsConcurrentUpdates") +{ + // With a thread pool, the loop and the pool threads update the same stats, so + // two of them regularly find the command queue full at once: one flushes it, + // the others have to wait for that and go on. Each thread adds 1 often enough + // to wrap the queue many times over, while one more flushes it directly, like + // the metrics flush on the loop; nothing may hang and nothing may be lost. + // Leaked and detached on purpose: if they hang, the test still fails in time. + auto* stats = new DataProcessingStats(TimingHelpers::defaultRealtimeBaseConfigurator(0, uv_default_loop()), + TimingHelpers::defaultCPUTimeConfigurator(uv_default_loop()), {}); + stats->registerMetric({.name = "dummy_metric", .metricId = DummyMetric}); + constexpr int THREADS = 4; + constexpr int UPDATES = 20000; + auto done = std::make_shared>(0); + for (int t = 0; t < THREADS; ++t) { + std::thread([stats, done]() { + for (int i = 0; i < UPDATES; ++i) { + stats->updateStats({DummyMetric, DataProcessingStats::Op::Add, 1}); + } + (*done)++; + }).detach(); + } + std::thread([stats, done]() { + while (*done < THREADS) { + stats->processCommandQueue(); + } + (*done)++; + }).detach(); + auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (*done <= THREADS && std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + REQUIRE(*done == THREADS + 1); + stats->processCommandQueue(); + CHECK(stats->metrics[DummyMetric] == THREADS * UPDATES); +}