Repository navigation
Description
Version: v2.2.4; the only commit on v2 after it (562869957f5092e692e69ea7898e563582a70ada) does not touch rppgrpc. gRPC 1.51.1, C++20, Linux x86_64.
Summary. A value emitted into client_bidi_reactor::get_observer() from a thread that is not inside one of the reactor's callbacks is not stopped by OnDone and not waited for. If that thread has already copied the write subject's observer list when OnDone runs, it continues into the reactor after delete this: it locks m_write_mutex, pushes into m_write and calls StartWrite on freed memory. Earlier in the same window, gRPC has already destroyed its stream object before it calls OnDone, so a StartWrite issued then calls Write on a destroyed object even while the reactor still exists. The class documentation warns about this (client_reactor.hpp L31), but the reactor gives the user no way to follow gRPC's rule: the hold has to be released when the call ends, and the only end signal the reactor emits is OnDone, which gRPC does not call while a hold is in place. This issue asks for the hold inside the reactor.
Issue 762 named this case as a suspected related problem, and PR 764 left it out because a hold "would change when OnDone can run"; the fix proposed below does not change that point when no outside write is in flight. Issue 769 is a different problem (the server reactor's half-close).
The write path.
- The handle owns the subject's state, not the reactor: publish_subject.hpp L46-L49.
on_nextchecksis_disposed()without a lock (observer.hpp L84-L89), copies the observer list underm_mutex, unlocks, then takesm_serialized_mutexand delivers from its copy (subject_state.hpp L112-L130).- The list element refers to the reactor by
std::reference_wrapperand locks a mutex inside it (base.hpp L66-L79);start_writecallsStartWrite→stream_->Write(client_reactor.hpp L66-L69, client_callback.h L267-L269). gRPC counts the write only insideWrite(L539).
The end of the call.
- When its count reaches zero, gRPC destroys the stream object and then calls
OnDone(client_callback.h L645-L657). OnDonedisposes the write subject, completes the read side, and runsdelete this(client_reactor.hpp L95-L100).- The dispose takes only
m_mutexto swap the state (subject_state.hpp L153-L156, L178-L185). It does not wait for a writer that holds a copy of the list, and the writer does not re-check the state before delivering (L124-L128).
gRPC's rule for this case (client_callback.h L291-L299): "Holds are needed if (and only if) this stream has operations that take place on it after StartCall but from outside one of the reactions ... the stream will not call OnDone if there are still holds on it." Writes issued inside a reaction are safe, because that reaction's own operation is still counted (L620-L626).
Interleaving. Thread 1 (any application thread): writer.on_next(msg) passes is_disposed(), copies the observer list, releases m_mutex. Thread 2 (gRPC, last reaction of an ended call): count reaches zero, the stream object is destroyed, OnDone disposes the subject (the free m_mutex, returns at once), completes the read side, delete this. Thread 1: takes m_serialized_mutex (alive, it is in the shared state), delivers from its copy, locks m_write_mutex in the freed reactor, push_back into the freed deque, virtual start_write through the freed object.
Reproduction (deterministic for the rppgrpc part). details::base_writer is not final, so a test can stand in for the reactor:
#include <rppgrpc/rppgrpc.hpp>
#include <chrono>
#include <latch>
#include <thread>
struct probe final : rppgrpc::details::base_writer<int> // the write side of client_bidi_reactor
{
probe(std::latch& entered, std::latch& release) : m_entered{entered}, m_release{release} {}
void on_done() { handle_on_done(); delete this; } // what OnDone does: client_reactor.hpp L97 and L99
private:
void start_write(const int&) override { m_entered.count_down(); m_release.wait(); } // a StartWrite that takes a while
void finish_writes(const grpc::Status&) override {}
std::latch& m_entered;
std::latch& m_release;
};
int main()
{
std::latch entered{1}, release{1};
auto* p = new probe{entered, release};
const auto w = p->get_observer();
std::jthread t0{[&] { w.on_next(1); }}; // holds m_serialized_mutex and m_write_mutex inside start_write
entered.wait();
std::jthread t1{[&] { w.on_next(2); }}; // copies the observer list, then waits for m_serialized_mutex
std::this_thread::sleep_for(std::chrono::milliseconds{50});
p->on_done(); // returns at once: the dispose waits for neither thread
release.count_down(); // t1 now pushes into the deque of the deleted probe
}Under AddressSanitizer (GCC 14.2, -fsanitize=address,undefined -O1 -g1 -std=c++23) the program reports a heap-use-after-free on every run. The use is the push_back in observer_strategy::on_next (base.hpp L76); the block was allocated by new probe and freed by on_done(). The report, shortened to the frames that matter:
==9==ERROR: AddressSanitizer: heap-use-after-free on address 0x50f0000000b8
READ of size 8 at 0x50f0000000b8 thread T2
#0 std::deque<int>::push_back(int const&) include/c++/14/bits/stl_deque.h:1540
#1 rppgrpc::details::base_writer<int>::observer_strategy::on_next<int const&>(int const&) const src/extensions/rppgrpc/rppgrpc/details/base.hpp:76
...
#13 rpp::subjects::details::subject_state<int, true>::on_next(int const&) src/rpp/rpp/subjects/details/subject_state.hpp:115
#14 rpp::subjects::details::publish_subject_base<int, true>::observer_strategy::on_next(int const&) const src/rpp/rpp/subjects/publish_subject.hpp:34
...
#16 operator() probe.cpp:26 // t1: w.on_next(2)
0x50f0000000b8 is located 120 bytes inside of 176-byte region [0x50f000000040,0x50f0000000f0)
freed by thread T0 here:
#0 operator delete(void*, unsigned long)
#1 probe::~probe() probe.cpp:7
#2 probe::on_done() probe.cpp:10
#3 main probe.cpp:28 // p->on_done()
previously allocated by thread T0 here:
#0 operator new(unsigned long)
#1 main probe.cpp:22 // new probe{entered, release}
The 50 ms sleep is the only timing assumption (thread t1 parked at subject_state.hpp L124); on_done() returning while t0 is still blocked already shows that the dispose does not wait.
With a real call: a bidirectional stream to a server that never answers, a thread that emits large messages into get_observer() in a loop, and ClientContext::TryCancel() from another thread; repeated a few thousand times under AddressSanitizer.
Proposed fix. Two parts; each alone leaves one half of the window.
- Ownership guard: the write side's mutex, queue and an owner pointer move into a state shared by the reactor and the observer handles, so a late writer locks memory that is alive and finds the owner gone. Without it, a writer parked between the list copy and
m_serialized_mutexholds no lock the end of the call could wait on. - Hold:
client_bidi_reactor::init()callsAddHold()beforeStartCall();OnReadDone(false)clears the owner pointer under the mutex and then callsRemoveHold(). Without the hold, gRPC destroys its stream object beforeOnDone, which no code in the reactor can order against.
// details/base.hpp (sketch)
struct write_state // shared by the reactor and every observer handle; outlives the reactor
{
std::mutex mutex{};
std::deque<TData> queue{};
bool finished{};
base_writer* owner{}; // nullptr once the call's end has been seen
};
struct observer_strategy
{
std::shared_ptr<write_state> state{};
template<rpp::constraint::decayed_same_as<TData> T>
void on_next(T&& message) const
{
std::lock_guard lock{state->mutex};
if (!state->owner)
return;
state->queue.push_back(std::forward<T>(message));
if (state->queue.size() == 1)
state->owner->start_write(state->queue.front());
}
// on_error / on_completed likewise
};
void close_writes() // called from the reaction that ends the read side, before RemoveHold()
{
std::lock_guard lock{m_state->mutex};
m_state->owner = nullptr;
}
// client_reactor.hpp, client_bidi_reactor (sketch)
void init()
{
Base::AddHold(); // writes from outside the reactions after StartCall
details::base_reader<Response>::handle_read_done(true);
Base::StartCall();
}
void OnReadDone(bool ok) override
{
if (!ok)
{
details::base_writer<Request>::close_writes();
Base::RemoveHold();
return;
}
details::base_reader<Response>::handle_read_done();
}The hold is always released: init() posts one read and OnReadDone(true) re-posts it, so exactly one OnReadDone(false) comes per call. RemoveHold() runs inside that reaction while its own operation is still counted (client_callback.h L581-L584, L620-L626), so with no outside write in flight OnDone runs where it runs today; with one in flight it runs after that write's OnWriteDone, which is what the hold is for. StartWrite under the mutex cannot re-enter OnWriteDone on the same thread, because the write tag is not inlined (L611-L617).
Open points: client_write_reactor has no read whose failure marks the end of the call, so its release point needs a decision (the completion of the observer, or OnWriteDone(false)); the shared write state also changes the server reactors' write side, which this issue does not examine.
If this direction is acceptable, I can open a pull request with the change and a test along the lines of the probe above.
Activity
daixtrose commentedon Nov 27, 2026
This continues the discussion from pull request 772, which fixed
client_bidi_reactorand leftclient_write_reactoropen. For readers who start here, the steps so far:client_bidi_reactorfor a client-streaming method through gRPC's generic stub.client_write_reactorwhen the final status has arrived, built in commit 2df410a.There I promised to think longer about
client_write_reactor. I had one idea, built a throwaway prototype and measured it. It does not solve the problem, but the measurements are worth sharing. I tried to write this so that nobody has to know gRPC's internals.What I tested, so you can judge the results:
server->InProcessChannel({}), the one the rppgrpc tests use);1. The problem again, in pictures
Take a service where the client uploads many measurements and the server answers once at the end (a client-streaming method). The code in this section is an illustration that I wrote for this comment and did not compile:
The server is allowed to end the call whenever it wants, also before the client has sent everything. Here it gives up after 100 measurements:
The client reads a sensor on its own thread and sends each value:
Two threads now work on the same reactor and know nothing of each other:
writer.on_next(m)whenever a value is ready. Inside, that callsStartWriteon the reactor;Finish, runs the reactor'sOnDone, and there the reactor doesdelete this.If the 101st value is ready just when the server's
Finisharrives, the sensor thread calls into a reactor that the gRPC thread is deleting:sequenceDiagram participant P as sensor thread participant R as reactor participant G as gRPC thread participant S as server P->>R: writer.on_next(value 100) R->>S: value 100 Note over S: 100 values are enough S-->>G: Finish(OK): the call is over G->>R: OnDone Note over R: delete this P-xR: writer.on_next(value 101) Note over P,R: the reactor is gone: use after free2. The tool gRPC gives us: a hold
AddHold()tells gRPC: "do not runOnDoneyet, somebody outside may still write".RemoveHold()takes that back. While the hold is in place the reactor stays alive.So the fix is simple to say: take a hold in
init(), and remove it at the right moment. The whole difficulty is which moment.OnDonenever runs, the user never gets the terminal.3. Why
client_bidi_reactorhas such a moment andclient_write_reactordoes notSame sensor thread as above in both pictures. The hold is in place from
init()on.client_bidi_reactor(both sides send). This reactor always has a read posted: it is always listening for the next message from the server. When the call ends, gRPC tells it "your read failed" (OnReadDone(false)), beforeOnDoneand exactly once. That is the moment. The merged fix uses it:sequenceDiagram participant P as sensor thread participant R as client_bidi_reactor participant G as gRPC thread participant S as server Note over R: hold in place, one read posted P->>R: writer.on_next(value 100) R->>S: value 100 S-->>G: Finish(OK): the call is over G->>R: OnReadDone(false) Note over R: 1. lock the writer<br/>2. RemoveHold() P->>R: writer.on_next(value 101) Note over P,R: the reactor is still alive and says:<br/>writer is locked, value dropped G->>R: OnDone Note over R: delete this P->>R: writer.on_next(value 102) Note over P,R: only touches a small shared state<br/>that outlives the reactor: droppedThe sensor thread never touches a deleted reactor: until the writer is locked the hold keeps the reactor alive, and afterwards the sensor thread does not get through to it any more.
client_write_reactor(only the client sends). This reactor never reads. gRPC tells it only "your write is done" andOnDone. If the sensor thread is quiet when the server ends the call, gRPC has nothing it could say, andOnDoneis what the hold blocks:sequenceDiagram participant P as sensor thread participant R as client_write_reactor participant G as gRPC thread participant S as server Note over R: hold in place, no read exists P->>R: writer.on_next(value 100) R->>S: value 100 Note over P: waits for the next sensor value S-->>G: Finish(OK): the call is over Note over G,R: gRPC has no reaction for this moment.<br/>OnDone is blocked by the hold. Note over R: does not know that the call is over.<br/>Nobody removes the hold. Note over P,R: the application never gets the terminalSo a hold alone does not help the write reactor: somebody has to tell it that the call is over, or it has to find out in another way.
4. The idea I tested: the hold belongs to the writer
A hold does not really mean "the call is alive". It means "somebody outside may still write". So remove it when that somebody is gone. The reactor can see that without help:
on_completedoron_errorOnWritesDoneDone(the half-close is confirmed)OnWriteDone(false)One more release point makes it faster: gRPC reports once per call whether the server's headers arrived (
OnReadInitialMetadataDone).falsemeans the call ended without a normal answer.For the user nothing changes: generated stub, nothing on the channel, no new class.
5. Results over TCP: it works
get_observable()cameTryCancel(), deadline, connection refusedRemoveHold()from the sensor thread never ranOnDoneon that thread. gRPC moved it to one of its own.grpc_initstarts gRPC's threads. The control without any rpp code shows the same kind of report in some of its runs. Whether that one is a real race in abseil or a false alarm I have not found out.So over TCP the price is: when the server ends the call with OK while the sensor thread is quiet, the user hears about it with the next write. That is how a plain socket without keep-alive behaves, and I could have lived with it.
6. Results over the in-process channel: it fails
The in-process channel behaves differently in exactly the two signals the idea relies on. Same on gRPC 1.51.1 and 1.72.0.
OnWriteDone(false)OnWriteDone(true)falsetruesequenceDiagram participant P as sensor thread participant R as prototype reactor participant G as gRPC (in-process) participant S as server Note over R: hold in place S-->>G: Finish(OK): the call is over P->>R: writer.on_next(value 101) R->>G: StartWrite G->>R: OnWriteDone(true) Note over R: looks like success, so the hold stays P->>R: writer.on_next(value 102) G->>R: OnWriteDone(true) Note over P,S: messages vanish, the terminal never comesA sensor thread that keeps writing never learns that the call is over, and its messages disappear without any sign. In the race test on the in-process channel, 24 of 50 calls that the server ended with OK and 9 of 50 that it ended with an error got their terminal only when my test gave up after 5 seconds and destroyed the observer. Today, without a hold, such a user gets the terminal at once. So on the in-process channel the idea would make things worse.
A second weak point, on both channels: when the last copy of the observer is destroyed without
on_completed, the hold goes away, but nobody tells the server. In my test the call stayed open until its deadline.7. What I conclude
client_write_reactorcannot be made safe for writes from other threads with gRPC's public callback interface alone. I would stop looking for a trick inside the reactor that does it.Why I think so:
OnDone, andOnDoneis exactly what a hold keeps back. The server's answer and the final status arrive in one internal operation that has no reaction of its own (client_callback.h L1023-L1032).What follows from that:
client_write_reactoris honest, andclient_bidi_reactor, the case with a real crash behind it, is fixed.OnDone. My dislike of the setup on the channel stays, but I have nothing better to offer today.One thought I cannot put aside: a write reactor that is allowed to take a hold but is never told that the call is over looks to me like a gap in gRPC itself. If it is one, then everything we build around it in rppgrpc, the interceptor included, is a workaround and not a solution. I have not checked yet whether the gRPC project knows this gap, whether it is intended, or whether a newer version has a reaction for it.
I would like to dig deeper into exactly this before we settle on anything, and I see no reason to hurry: nothing is broken today that the documented limit does not cover. I will come back here with what I find. If you already know how the gRPC people see this, I would be glad to hear it.
Not measured: an unknown method name, and a server process that dies after it has sent its headers. I can share the prototype and the logs if they help.
Appendix: the test code
The blocks below are shortened from the files I ran: logging, timing and counters are removed, the logic is unchanged. I did not compile the shortened form. I can put the complete files into a gist if you want to run them.
A. What gRPC itself does after the end of the call (the numbers in sections 5 and 6)
A plain gRPC reactor without any rpp code, started through the generated stub. It takes a hold, waits until the server has ended the call, and then tries a write and a half-close from a thread that is not a gRPC thread.
B. The prototype reactor (the idea of section 4)
C. The race test (AddressSanitizer, LeakSanitizer, ThreadSanitizer)
Two long-lived threads write as fast as they can. The call ends at a random moment. The test then checks that exactly one terminal arrives, that it is the expected one, and that it arrives within 5 seconds.
For ThreadSanitizer the same test ran against a gRPC that was itself built with
-fsanitize=thread.