From 72edf563349f04d24340e4e7f8c088b55b3e4838 Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Thu, 22 Oct 2026 06:45:04 -0600 Subject: [PATCH] Guard shared_ so a logger may report while close() runs (#14) close() swapped shared_ out with no lock while the logger, on the sending thread, could be reading it through report(). A mutex now guards shared_ alone: close() swaps under it and report() and isEnabled() work from a copy taken under it. Co-Authored-By: Claude Opus 5.5 --- test/test_trace_client.cpp | 34 +++++++++++++++++++++++++++++++++- trace_client.hpp | 38 ++++++++++++++++++++++++++++---------- 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/test/test_trace_client.cpp b/test/test_trace_client.cpp index be4b543..0f379eb 100644 --- a/test/test_trace_client.cpp +++ b/test/test_trace_client.cpp @@ -346,7 +346,7 @@ static void aLoggerThatThrowsDoesNotStopTheSendingThread() { static void aLoggerMayItselfReport() { // The logger runs on the sending thread; a report from inside it is // queued and sent like any other, not a deadlock. The test waits for that - // report() to return before close(): one racing close() is issue #14. + // report() to return before close(): one racing close() is the next test. StubServer server; server.status = 500; trace_client::TraceClient *self = NULL; @@ -372,6 +372,37 @@ static void aLoggerMayItselfReport() { CHECK(got[1].body.find("\"name\":\"logged\"") != std::string::npos); } +static void aLoggerMayReportWhileCloseIsRunning() { + // close() starts while the logger is running and the logger then calls + // report(): nothing orders the two threads, so this is the race of issue + // #14, which ThreadSanitizer reports unless report() and close() share a + // lock. Either outcome for "logged" is allowed; a crash or a hang is not. + StubServer server; + server.status = 500; + trace_client::TraceClient *self = NULL; + std::atomic inLogger(false); + std::atomic returned(false); + trace_client::Logger reporting = [&self, &inLogger, &returned](const std::string &) { + if (inLogger.exchange(true)) return; + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + self->report("logged"); + returned = true; + }; + trace_client::TraceClient client(server.baseUrl(), "MyGame", "1.2.3", "k", true, reporting); + self = &client; + client.report("startup"); + std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); + while (!inLogger && secondsSince(start) < 10) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + CHECK(inLogger); + client.close(); + CHECK(returned); + CHECK(!client.isEnabled()); + std::vector got = server.received(); + CHECK(!got.empty()); + if (got.empty()) return; + CHECK(got[0].body.find("\"name\":\"startup\"") != std::string::npos); +} + static void theLoggerIsNeverCalledOnceCloseReturns() { StubServer server; server.hold(); // the request in flight never answers, so close() gives up on it @@ -1255,6 +1286,7 @@ int main() { {"rejectedKeyIsLoggedNotThrown", rejectedKeyIsLoggedNotThrown}, {"aLoggerThatThrowsDoesNotStopTheSendingThread", aLoggerThatThrowsDoesNotStopTheSendingThread}, {"aLoggerMayItselfReport", aLoggerMayItselfReport}, + {"aLoggerMayReportWhileCloseIsRunning", aLoggerMayReportWhileCloseIsRunning}, {"theLoggerIsNeverCalledOnceCloseReturns", theLoggerIsNeverCalledOnceCloseReturns}, {"missingCurlIsAnUnreachableServer", missingCurlIsAnUnreachableServer}, {"disabledClientSendsNothing", disabledClientSendsNothing}, diff --git a/trace_client.hpp b/trace_client.hpp index fac8349..8026f8f 100644 --- a/trace_client.hpp +++ b/trace_client.hpp @@ -1006,7 +1006,7 @@ class TraceClient { ~TraceClient() { close(); } /** Whether report() will actually send anything. False after close(). */ - bool isEnabled() const { return static_cast(shared_); } + bool isEnabled() const { return static_cast(current()); } /** * Why this client reports nothing: empty when it reports, otherwise one @@ -1035,9 +1035,14 @@ class TraceClient { * then is abandoned. Safe to call more than once, and on a disabled client. */ void close(double timeoutSeconds = TIMEOUT_SECONDS) { - if (!shared_) return; std::shared_ptr shared; - shared.swap(shared_); + try { + std::lock_guard lock(sharedMutex_); + shared.swap(shared_); + } catch (...) { + return; + } + if (!shared) return; try { std::unique_lock lock(shared->mutex); shared->closing = true; @@ -1135,26 +1140,39 @@ class TraceClient { #endif } + // A copy of shared_, taken under its lock: the logger runs on the sending + // thread and may call report() while the program's thread is in close(). + std::shared_ptr current() const { + try { + std::lock_guard lock(sharedMutex_); + return shared_; + } catch (...) { + return std::shared_ptr(); + } + } + void enqueue(const std::string &name, bool hasValue, double value, const Tags &tags) { - if (!shared_ || detail::isBlank(name)) return; + std::shared_ptr shared = current(); + if (!shared || detail::isBlank(name)) return; try { - std::string body = detail::json(shared_->application, name, hasValue, value, + std::string body = detail::json(shared->application, name, hasValue, value, detail::withInstall(detail::withVersion(tags, version_), installId_)); bool full = false; { - std::lock_guard lock(shared_->mutex); - full = shared_->queue.size() >= QUEUE_CAPACITY; + std::lock_guard lock(shared->mutex); + full = shared->queue.size() >= QUEUE_CAPACITY; if (!full) { - shared_->queue.push_back(body); - shared_->changed.notify_all(); + shared->queue.push_back(body); + shared->changed.notify_all(); } } - if (full) shared_->log("queue full, dropped " + name); + if (full) shared->log("queue full, dropped " + name); } catch (...) { // a report must never be the reason a program stops } } + mutable std::mutex sharedMutex_; // guards shared_ alone std::shared_ptr shared_; std::thread thread_; std::string version_;