Skip to content

rppgrpc: client reactors take no gRPC hold, so a write from outside a reaction can reach the reactor after OnDone has deleted it #770

Backlog

Description

@daixtrose

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.

  1. The handle owns the subject's state, not the reactor: publish_subject.hpp L46-L49.
  2. on_next checks is_disposed() without a lock (observer.hpp L84-L89), copies the observer list under m_mutex, unlocks, then takes m_serialized_mutex and delivers from its copy (subject_state.hpp L112-L130).
  3. The list element refers to the reactor by std::reference_wrapper and locks a mutex inside it (base.hpp L66-L79); start_write calls StartWrite → stream_->Write (client_reactor.hpp L66-L69, client_callback.h L267-L269). gRPC counts the write only inside Write (L539).

The end of the call.

  1. When its count reaches zero, gRPC destroys the stream object and then calls OnDone (client_callback.h L645-L657).
  2. OnDone disposes the write subject, completes the read side, and runs delete this (client_reactor.hpp L95-L100).
  3. The dispose takes only m_mutex to 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.

  1. 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_mutex holds no lock the end of the call could wait on.
  2. Hold: client_bidi_reactor::init() calls AddHold() before StartCall(); OnReadDone(false) clears the owner pointer under the mutex and then calls RemoveHold(). Without the hold, gRPC destroys its stream object before OnDone, 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

  1. daixtrose commented on Nov 27, 2026

    @daixtrose
    ContributorAuthor

    This continues the discussion from pull request 772, which fixed client_bidi_reactor and left client_write_reactor open. For readers who start here, the steps so far:

    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:

    • a prototype reactor outside the repository, started through the generated stub;
    • two ways to connect client and server: a real TCP connection on localhost, and gRPC's in-process channel (server->InProcessChannel({}), the one the rppgrpc tests use);
    • gRPC 1.51.1 for everything, and the raw gRPC behaviour again on gRPC 1.72.0;
    • races under AddressSanitizer with LeakSanitizer, and under ThreadSanitizer. For the ThreadSanitizer run I built gRPC 1.51.1 with abseil, protobuf, re2 and c-ares with ThreadSanitizer too, so that it sees gRPC's own locking. A plain gRPC reactor without any rpp code served as control.

    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:

    service Telemetry {
      rpc Upload(stream Measurement) returns (Summary);
    }

    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:

    // Server
    grpc::ServerReadReactor<Measurement>* Upload(grpc::CallbackServerContext*, Summary* summary) override
    {
        struct reader : grpc::ServerReadReactor<Measurement>
        {
            reader() { StartRead(&m_in); }
            void OnReadDone(bool ok) override
            {
                if (ok && ++m_count < 100)
                    return StartRead(&m_in);
                Finish(grpc::Status::OK);   // the call is over, whatever the client still wants to send
            }
            void OnDone() override { delete this; }
    
            Measurement m_in;
            int         m_count{};
        };
        return new reader{};
    }

    The client reads a sensor on its own thread and sends each value:

    // Client
    grpc::ClientContext ctx;
    Summary             summary;
    
    auto* reactor = new rppgrpc::client_write_reactor<Measurement>{};   // deletes itself in OnDone
    stub->async()->Upload(&ctx, &summary, reactor);
    
    auto writer = reactor->get_observer();                 // where the client puts messages in
    reactor->get_observable().subscribe(
        [](rpp::utils::none) {},
        [](const std::exception_ptr&) { /* the call failed */ },
        []() { /* the call ended with OK */ });
    
    reactor->init();                                        // the call starts; from here on gRPC's
                                                            // threads may run OnDone at any time
    
    std::thread sensor{[writer] {                           // the application's own thread
        for (;;)
        {
            Measurement m = read_sensor();                  // takes a while
            writer.on_next(m);                              // <-- ends up in reactor->StartWrite(...)
        }
    }};

    Two threads now work on the same reactor and know nothing of each other:

    • the sensor thread calls writer.on_next(m) whenever a value is ready. Inside, that calls StartWrite on the reactor;
    • a gRPC thread receives the server's Finish, runs the reactor's OnDone, and there the reactor does delete this.

    If the 101st value is ready just when the server's Finish arrives, 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 free
    
    Loading

    2. The tool gRPC gives us: a hold

    AddHold() tells gRPC: "do not run OnDone yet, 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.

    • Too early: the crash is back.
    • Never: OnDone never runs, the user never gets the terminal.

    3. Why client_bidi_reactor has such a moment and client_write_reactor does not

    Same 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)), before OnDone and 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: dropped
    
    Loading

    The 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" and OnDone. If the sensor thread is quiet when the server ends the call, gRPC has nothing it could say, and OnDone is 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 terminal
    
    Loading

    So 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:

    The outside writer is gone when … The reactor sees it as
    it calls on_completed or on_error OnWritesDoneDone (the half-close is confirmed)
    its next message cannot be sent, because the call is dead OnWriteDone(false)
    the last copy of the observer is destroyed the destructor of a shared state behind the observer

    One more release point makes it faster: gRPC reports once per call whether the server's headers arrived (OnReadInitialMetadataDone). false means 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

    How the call ended while the sensor thread was quiet The terminal on get_observable() came
    server finishes with an error at once (0.1 to 2.9 ms), through the header signal
    TryCancel(), deadline, connection refused at once (0.2 to 1.4 ms), through the header signal
    server finishes with OK before the client half-closed at the sensor thread's next write (in my test 300 ms later, which was the pause I had chosen)
    server sent its headers early, then finished at the sensor thread's next write
    • A write or half-close started after the end of the call, under the hold, always came back as a failed reaction. No crash, no hang.
    • RemoveHold() from the sensor thread never ran OnDone on that thread. gRPC moved it to one of its own.
    • 1000 calls with two writing threads writing as fast as they can and the end at a random moment, under AddressSanitizer with LeakSanitizer: no report, no hang, exactly one terminal per call.
    • The same 1000 calls under ThreadSanitizer: no hang, exactly one terminal per call, and no report with a frame in the prototype or in my test code. There were 3 reports, all of one kind: two accesses inside abseil while grpc_init starts 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.

    After the server has ended the call TCP in-process channel
    a new write from the client OnWriteDone(false) OnWriteDone(true)
    header signal after a server error false true
    sequenceDiagram
        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 comes
    
    Loading

    A 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_reactor cannot 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:

    • gRPC gives a reactor that only writes no signal that the call has ended. The only one is OnDone, and OnDone is 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).
    • The only substitute is to guess from failed writes, and the guess is not reliable. Over TCP it works, but it can be late. On the in-process channel it is wrong, on gRPC 1.51.1 and on 1.72.0.
    • So every design that stays inside the reactor trades the crash for an end-of-call notice that is late or missing. That is a different defect, not a fix.

    What follows from that:

    1. For now I would keep the documented limit as it is. The warning on client_write_reactor is honest, and client_bidi_reactor, the case with a real crash behind it, is fixed.
    2. Currently your interceptor is the only complete answer. It is the only place that sees the final status before OnDone. My dislike of the setup on the channel stays, but I have nothing better to offer today.
    3. I do not propose a pull request from this prototype.

    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.

    struct probe : grpc::ClientWriteReactor<Request>
    {
        void OnReadInitialMetadataDone(bool ok) override { log("OnReadInitialMetadataDone", ok); }
        void OnWriteDone(bool ok) override               { log("OnWriteDone", ok); }
        void OnWritesDoneDone(bool ok) override          { log("OnWritesDoneDone", ok); }
        void OnDone(const grpc::Status& s) override      { log("OnDone", s); }
    };
    
    probe               r;
    grpc::ClientContext ctx;
    Response            response;
    Request             first, late;
    
    stub->async()->ClientSide(&ctx, &response, &r);   // generated stub; channel is TCP or server->InProcessChannel({})
    r.AddHold();
    r.StartWrite(&first);
    r.StartCall();
    
    // ... the call ends here in one of six ways: the server calls Finish(OK) or Finish(error), with or without
    //     headers sent before; ctx.TryCancel(); deadline; connection refused ...
    
    std::this_thread::sleep_for(100ms);               // the call is over; OnDone has not run, because of the hold
    
    r.StartWrite(&late);                              // TCP: OnWriteDone(false)
                                                      // in-process, after a Finish by the server: OnWriteDone(true)
    r.StartWritesDone();                              // measured in a separate run: OnWritesDoneDone always arrives
    
    r.RemoveHold();                                   // OnDone follows on a gRPC thread, never on this one
    B. The prototype reactor (the idea of section 4)
    template<typename Request>
    class held_write_reactor final : public grpc::ClientWriteReactor<Request>
    {
        using Base = grpc::ClientWriteReactor<Request>;
    
        struct state                                   // shared with the observer, outlives the reactor
        {
            std::mutex          mutex;
            std::deque<Request> queue;                 // front is in flight
            held_write_reactor* reactor{};             // null once the writer is locked out
            bool                finished{};            // on_completed / on_error was called
            bool                released{};            // writer locked out and hold removed
        };
    
        struct writer_token                            // one per reactor, owned only by the copies of the observer
        {
            std::shared_ptr<state> s;
            ~writer_token() { writer_gone(*s); }       // the last copy of the observer is gone
        };
    
        struct observer_strategy
        {
            std::shared_ptr<writer_token> token;
            void on_next(const Request& v) const        { push(*token->s, v); }
            void on_error(const std::exception_ptr&) const { finish(*token->s); }
            void on_completed() const                   { finish(*token->s); }
            // ...
        };
    
    public:
        void init()
        {
            Base::AddHold();
            auto token = std::move(m_token);           // the reactor itself keeps no writer handle
            Base::StartCall();
        }
    
    private:
        // The one place that removes the hold. Runs at most once per call.
        static void close_and_release(std::unique_lock<std::mutex>& lock, state& s)
        {
            if (s.released)
                return;
            s.released = true;
            auto* r    = std::exchange(s.reactor, nullptr);
            while (s.queue.size() > 1)                 // not yet started: dropped
                s.queue.pop_back();
            lock.unlock();
            r->Base::RemoveHold();
        }
    
        static void push(state& s, const Request& v)   // any thread
        {
            std::lock_guard lock{s.mutex};
            if (s.released || s.finished)
                return;                                // dropped
            s.queue.push_back(v);
            if (s.queue.size() == 1)
                s.reactor->Base::StartWrite(&s.queue.front());
        }
    
        static void finish(state& s)                   // any thread
        {
            std::lock_guard lock{s.mutex};
            if (s.released || s.finished)
                return;
            s.finished = true;
            if (s.queue.empty())
                s.reactor->Base::StartWritesDone();
        }
    
        // The four release points:
        static void writer_gone(state& s)              { std::unique_lock l{s.mutex}; close_and_release(l, s); }
        void OnWritesDoneDone(bool) override           { std::unique_lock l{m_state->mutex}; close_and_release(l, *m_state); }
        void OnReadInitialMetadataDone(bool ok) override
        {
            if (ok)
                return;
            std::unique_lock l{m_state->mutex};
            close_and_release(l, *m_state);
        }
        void OnWriteDone(bool ok) override
        {
            std::unique_lock l{m_state->mutex};
            m_state->queue.pop_front();
            if (m_state->released)
                return;
            if (!ok)
                return close_and_release(l, *m_state);
            if (!m_state->queue.empty())
                Base::StartWrite(&m_state->queue.front());
            else if (m_state->finished)
                Base::StartWritesDone();
        }
    
        void OnDone(const grpc::Status& s) override    // terminal for get_observable(), then delete this
        {
            // ...
            delete this;
        }
    
        std::shared_ptr<state>        m_state = std::make_shared<state>();
        std::shared_ptr<writer_token> m_token = /* token for m_state */;
    };
    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 (int i = 0; i < 200; ++i)                                  // per case
    {
        auto* reactor = new held_write_reactor<Request>{};
        grpc::ClientContext ctx;
        Response            response;
        stub->async()->ClientSide(&ctx, &response, reactor);
    
        auto observer = reactor->get_observer();
        reactor->get_observable().subscribe(record_terminal);
        reactor->init();
    
        writers.start(observer);                                   // 2 threads: observer.on_next(request) in a loop
    
        // one of:
        //  (a) the server calls Finish(OK) after a random number of 1..50 messages
        //  (b) the server calls Finish(RESOURCE_EXHAUSTED) after 1..50 messages
        //  (c) ctx.TryCancel() after a random 0..2000 microseconds
        //  normal: each writer sends 200 values, then on_completed
        //  drop: the last copy of the observer is destroyed after a random 0..2000 microseconds
    
        CHECK(terminal_within(5s));
        CHECK(exactly_one_terminal());
        CHECK(terminal_is_the_expected_one());
        writers.stop();
    }

    For ThreadSanitizer the same test ran against a gRPC that was itself built with -fsanitize=thread.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions