Repository navigation
Description
Summary
report() called from inside the Logger can race with close() on the program's thread. ThreadSanitizer reports this as a data race on TraceClient::shared_.
Where
TraceClient::close()(trace_client.hpp:1038-1040) doesshared.swap(shared_)first, with no lock held, and only then waits for the sending thread to drain.TraceClient::enqueue()(trace_client.hpp:1139) readsshared_(if (!shared_ || ...), thenshared_->...) with no lock held.- The
Loggerruns on the sending thread (deliver→Shared::log,trace_client.hpp:819-823). ThelogMutexcomment inShared(trace_client.hpp:435) says "a logger may itself call report()".
close() drains the queue after the swap, so a report that fails during the drain reaches the logger. If that logger calls report(), the sending thread reads shared_ while the program's thread writes it. This is not limited to a contrived test: a logger that reports its own drops (e.g. as a "trace-drop" event) is enough, as long as a report fails while close() is draining.
Evidence
This was found while adding aLoggerMayItselfReport in PR #13. In the first version of that test, the main thread waited for the stub server to see both requests and then called close(). TSan (CI job linux-sanitizers (thread), run 39592415441) reported:
WARNING: ThreadSanitizer: data race
Write: std::__shared_ptr<Shared>::swap ... TraceClient::close(double) trace_client.hpp:1040
Previous read: __shared_ptr::operator bool ... TraceClient::enqueue(...) trace_client.hpp:1139
... aLoggerMayItselfReport()::$_0 ... Shared::log trace_client.hpp:443 ... deliver trace_client.hpp:823
SUMMARY: ThreadSanitizer: data race trace_client.hpp:1040 in trace_client::TraceClient::close(double)
PR #13 keeps the test but makes the logger hand control back to the main thread before close() runs. That establishes a happens-before edge, so the test checks only "a logger may report", not this race.
Possible directions (owner's call)
- Have
enqueuereach the queue through state the sending thread owns, e.g. aclosingcheck undershared->mutex, so it never readsTraceClient::shared_from the sending thread. This needsshared_itself to be read safely, e.g. through a copy taken under a lock or viastd::atomic_loadon theshared_ptr, which C++11 provides. - Or document that
report()from inside the logger is only safe while no other thread is callingclose(), and correct thelogMutexcomment.
A test for the fix could reuse aLoggerMayItselfReport from PR #13 without its handshake: the server returns 500 and the main thread calls close() while the logger reports. It should fail under TSan before the fix and pass after.
This issue was drafted during a Gardener session (https://github.com/Stephenson-Software/gardener).
drafted by Claude on behalf of Daniel Stephenson
Activity
Wait for the logger's report() to return before close() in the test
Test the Logger's promises: throwing, reporting, silent after close (#13
Guard shared_ so a logger may report while close() runs (#14) (#15)