From 363cf84bb8c4bc6cab7ed1cf8c00b6093c7751d8 Mon Sep 17 00:00:00 2001 From: Markus Werle Date: Wed, 25 Nov 2026 23:50:04 +0100 Subject: [PATCH 1/4] rppgrpc: client_bidi_reactor holds the call for writes from outside the reactions Co-Authored-By: Claude Opus 5.5 --- .../rppgrpc/rppgrpc/client_reactor.hpp | 13 +- .../rppgrpc/rppgrpc/details/base.hpp | 72 ++++-- src/tests/rppgrpc/test_async_client.cpp | 218 ++++++++++++++++++ 3 files changed, 280 insertions(+), 23 deletions(-) diff --git a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp index 68c4f9924..aab301f61 100644 --- a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp +++ b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp @@ -28,7 +28,7 @@ namespace rppgrpc * - to access values FROM stream you can subscribe to observable obtained via `reactor->get_observable()` (same observable WOULD emit on_completed in case of successful stream termination and on_error in case of some errors with grpc stream) * - to pass values TO stream you can emit values to observer obtained via `reactor->get_observer()` * - * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`. Obtain the observer and emit the first values before `init()`: they are posted and sent once the call starts. Emitting from outside the reactor's callbacks after `init()` races with the end of the call (gRPC requires a hold for that, see `grpc::ClientBidiReactor::AddHold`). + * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`, so obtain the observer and the observable before `init()` and do not use the reactor afterwards. The observer may be used from any thread, also after `init()`: the reactor holds the call (see `grpc::ClientBidiReactor::AddHold`) until its read side has ended, and values emitted after that are dropped. * * @snippet client_reactor.cpp bidi_reactor * @@ -46,6 +46,9 @@ namespace rppgrpc void init() { + // The observer may write from outside the reactions after StartCall(), which gRPC allows + // only under a hold. OnReadDone(false) releases it. + Base::AddHold(); // The first read is posted before StartCall(): gRPC keeps it until the call starts and // counts it as an outstanding operation. StartCall() is the last use of the reactor in // init(), because a call that ends at once may run OnDone (and so `delete this`) on a @@ -79,7 +82,15 @@ namespace rppgrpc void OnReadDone(bool ok) override { if (!ok) + { + // One read is always posted, so each call ends its read side exactly once, here. + // A write that took the observer's lock before close_writes() has called StartWrite + // and is counted by gRPC, so OnDone comes after its OnWriteDone; later writes are + // dropped. This reaction is itself still counted, so RemoveHold() does not run OnDone. + details::base_writer::close_writes(); + Base::RemoveHold(); return; + } details::base_reader::handle_read_done(); } diff --git a/src/extensions/rppgrpc/rppgrpc/details/base.hpp b/src/extensions/rppgrpc/rppgrpc/details/base.hpp index f1f388b39..7cd210c55 100644 --- a/src/extensions/rppgrpc/rppgrpc/details/base.hpp +++ b/src/extensions/rppgrpc/rppgrpc/details/base.hpp @@ -19,6 +19,7 @@ #include "rpp/subjects/publish_subject.hpp" #include +#include #include namespace rppgrpc::details @@ -29,7 +30,8 @@ namespace rppgrpc::details public: base_writer() { - m_subject.get_observable().subscribe(typename details::base_writer::observer_strategy{*this}); + m_state->owner = this; + m_subject.get_observable().subscribe(typename details::base_writer::observer_strategy{m_state}); } virtual ~base_writer() noexcept = default; @@ -45,54 +47,82 @@ namespace rppgrpc::details void handle_on_done() { + close_writes(); m_subject.get_disposable().dispose(); } + // Values and terminals emitted to the observer after this call reach neither this object nor its stream. + // It waits for an emission that is inside start_write or finish_writes. + void close_writes() + { + std::lock_guard lock{m_state->mutex}; + m_state->owner = nullptr; + } + void handle_write_done() { - std::lock_guard lock{m_write_mutex}; - m_write.pop_front(); + std::lock_guard lock{m_state->mutex}; + m_state->queue.pop_front(); - if (!m_write.empty()) + if (!m_state->queue.empty()) { - start_write(m_write.front()); + start_write(m_state->queue.front()); } - else if (m_finished) + else if (m_state->finished) { finish_writes(grpc::Status::OK); } } + // Shared by this object and the observer subscribed to the subject, so it outlives this object: an emission + // that has passed the subject when this object ends still locks a live mutex and finds no owner. + struct write_state + { + std::mutex mutex{}; + std::deque queue{}; + bool finished{}; + base_writer* owner{}; + }; + struct observer_strategy { static constexpr auto preferred_disposables_mode = rpp::details::observers::disposables_mode::Auto; - std::reference_wrapper owner{}; + std::shared_ptr state{}; template T> void on_next(T&& message) const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_write.push_back(std::forward(message)); - if (owner.get().m_write.size() == 1) - owner.get().start_write(owner.get().m_write.front()); + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; + + state->queue.push_back(std::forward(message)); + if (state->queue.size() == 1) + state->owner->start_write(state->queue.front()); } void on_error(const std::exception_ptr&) const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_finished = true; + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; - if (owner.get().m_write.size() == 0) - owner.get().finish_writes(grpc::Status{grpc::StatusCode::INTERNAL, "Internal error happens"}); + state->finished = true; + + if (state->queue.size() == 0) + state->owner->finish_writes(grpc::Status{grpc::StatusCode::INTERNAL, "Internal error happens"}); } void on_completed() const { - std::lock_guard lock{owner.get().m_write_mutex}; - owner.get().m_finished = true; + std::lock_guard lock{state->mutex}; + if (!state->owner) + return; + + state->finished = true; - if (owner.get().m_write.size() == 0) - owner.get().finish_writes(grpc::Status::OK); + if (state->queue.size() == 0) + state->owner->finish_writes(grpc::Status::OK); } static constexpr bool is_disposed() { return false; } @@ -102,9 +132,7 @@ namespace rppgrpc::details private: rpp::subjects::serialized_publish_subject m_subject{}; - std::mutex m_write_mutex{}; - std::deque m_write{}; - bool m_finished{}; + std::shared_ptr m_state = std::make_shared(); }; template diff --git a/src/tests/rppgrpc/test_async_client.cpp b/src/tests/rppgrpc/test_async_client.cpp index e4d0f1bdc..3d58a2695 100644 --- a/src/tests/rppgrpc/test_async_client.cpp +++ b/src/tests/rppgrpc/test_async_client.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -13,7 +14,12 @@ #include "rpp_trompeloil.hpp" +#include #include +#include +#include +#include +#include namespace { @@ -23,6 +29,35 @@ namespace IMPLEMENT_MOCK3(ClientSide); IMPLEMENT_MOCK2(Bidirectional); }; + + // The write side of the reactors, with a start_write that waits until it is released. + // on_done() does what the reactors' OnDone does with their write side: handle_on_done(), then `delete this`. + struct blocking_writer final : rppgrpc::details::base_writer + { + blocking_writer(std::latch& entered, std::latch& release) + : m_entered{entered} + , m_release{release} + { + } + + void on_done() + { + handle_on_done(); + delete this; + } + + private: + void start_write(const int&) override + { + m_entered.count_down(); + m_release.wait(); + } + + void finish_writes(const grpc::Status&) override { } + + std::latch& m_entered; + std::latch& m_release; + }; } // namespace TEST_CASE("async client reactor") @@ -421,3 +456,186 @@ TEST_CASE("async client reactor: call that ends during init()") server->Shutdown(); server->Wait(); } + +TEST_CASE("async client reactor: write that is under way when the call ends") +{ + // t0 is inside start_write. t1 has entered the observer and waits behind t0. Then the write side ends + // and its owner is deleted, as in OnDone. Neither thread may touch the deleted owner afterwards: a write + // that does is a use-after-free; AddressSanitizer reports it. + std::latch entered{1}; + std::latch release{1}; + auto* const writer = new blocking_writer{entered, release}; + const auto observer = writer->get_observer(); + + std::thread t0{[&] { observer.on_next(1); }}; + entered.wait(); + std::thread t1{[&] { observer.on_next(2); }}; + std::this_thread::sleep_for(std::chrono::milliseconds{50}); // t1 waits behind t0 + + auto done = std::async(std::launch::async, [writer] { writer->on_done(); }); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); // on_done() runs while t0 is inside start_write + release.count_down(); + + done.get(); + t0.join(); + t1.join(); +} + +TEST_CASE("async client reactor: writes from other threads while the call ends") +{ + // Threads emit into the reactor's observer after init() while the call ends. A write that reaches the + // reactor after OnDone, or its stream after gRPC has destroyed it, is a use-after-free; AddressSanitizer + // reports it. + constexpr int iterations = 200; + constexpr int writers = 2; + constexpr uint32_t writes = 1000; + + grpc::ServerBuilder builder{}; + auto mock_service = std::make_unique(); + int server_reads = 0; // the server returns OK after this many reads, or when the client's side ends + ALLOW_CALL(*mock_service, Bidirectional(trompeloeil::_, trompeloeil::_)) + .RETURN(grpc::Status::OK) + .LR_SIDE_EFFECT({ + Request request{}; + for (int i = 0; i < server_reads && _2->Read(&request); ++i) + { + } + }); + builder.RegisterService(mock_service.get()); + + auto server = builder.BuildAndStart(); + const auto stub = TestService::NewStub(server->InProcessChannel({}), {}); + + // Starts one call, emits from `writers` threads, ends the call with `end_call` and waits for the reactor's + // terminal, which it emits from OnDone. + const auto run_call = [&](const auto& end_call) { + grpc::ClientContext ctx{}; + const auto done = std::make_shared>(); + const auto reactor = new rppgrpc::client_bidi_reactor(); + reactor->get_observable().subscribe([](const Response&) { }, + [done](const std::exception_ptr&) { done->set_value(); }, + [done] { done->set_value(); }); + stub->async()->Bidirectional(&ctx, reactor); + const auto observer = reactor->get_observer(); + reactor->init(); + + std::atomic_bool stop{}; + std::vector threads{}; + for (int i = 0; i < writers; ++i) + { + threads.emplace_back([&] { + Request request{}; + for (uint32_t v = 0; v < writes && !stop; ++v) + { + request.set_value(v); + observer.on_next(request); + } + }); + } + end_call(ctx); + const bool ended = done->get_future().wait_for(std::chrono::seconds{5}) == std::future_status::ready; + stop = true; + for (auto& t : threads) + t.join(); + return ended; + }; + + SUBCASE("server finishes the call") + { + server_reads = 10; + for (int i = 0; i < iterations; ++i) + REQUIRE(run_call([](grpc::ClientContext&) { })); + } + SUBCASE("client cancels the call") + { + server_reads = std::numeric_limits::max(); + for (int i = 0; i < iterations; ++i) + REQUIRE(run_call([](grpc::ClientContext& ctx) { ctx.TryCancel(); })); + } + + server->Shutdown(); + server->Wait(); +} + +TEST_CASE("async client reactor: bidirectional call reaches OnDone however it ends") +{ + // Each call gets a write from outside the reactions after init(), and must still reach OnDone, which emits + // the observable's terminal and deletes the reactor (LeakSanitizer reports a reactor that is never deleted). + // A context cancelled before init() is covered by "call that ends during init()". + grpc::ServerBuilder builder{}; + auto mock_service = std::make_unique(); + grpc::Status server_status = grpc::Status::OK; + bool server_reads = false; // the server reads until the client's side ends, then returns + ALLOW_CALL(*mock_service, Bidirectional(trompeloeil::_, trompeloeil::_)) + .LR_RETURN(server_status) + .LR_SIDE_EFFECT({ + Request request{}; + while (server_reads && _2->Read(&request)) + { + } + }); + builder.RegisterService(mock_service.get()); + + auto server = builder.BuildAndStart(); + std::shared_ptr channel = server->InProcessChannel({}); + grpc::ClientContext ctx{}; + + enum class terminal + { + none, + completed, + error + }; + + // Starts one call on `channel`, writes once after init(), ends the call with `end_call` and returns the + // terminal the reactor emitted from OnDone. + const auto run_call = [&](const auto& end_call) { + const auto stub = TestService::NewStub(channel, {}); + const auto result = std::make_shared>(); + const auto reactor = new rppgrpc::client_bidi_reactor(); + reactor->get_observable().subscribe([](const Response&) { }, + [result](const std::exception_ptr&) { result->set_value(terminal::error); }, + [result] { result->set_value(terminal::completed); }); + stub->async()->Bidirectional(&ctx, reactor); + const auto observer = reactor->get_observer(); + reactor->init(); + observer.on_next(Request{}); + end_call(); + auto f = result->get_future(); + return f.wait_for(std::chrono::seconds{5}) == std::future_status::ready ? f.get() : terminal::none; + }; + + SUBCASE("server finishes with OK") + { + CHECK(run_call([] { }) == terminal::completed); + } + SUBCASE("server finishes with an error status") + { + server_status = grpc::Status{grpc::StatusCode::INTERNAL, "server error"}; + CHECK(run_call([] { }) == terminal::error); + } + SUBCASE("client cancels") + { + server_reads = true; + CHECK(run_call([&] { ctx.TryCancel(); }) == terminal::error); + } + SUBCASE("deadline expires") + { + server_reads = true; + ctx.set_deadline(std::chrono::system_clock::now() + std::chrono::milliseconds{100}); + CHECK(run_call([] { }) == terminal::error); + } + SUBCASE("server shuts down during the call") + { + server_reads = true; + CHECK(run_call([&] { server->Shutdown(std::chrono::system_clock::now()); }) == terminal::error); + } + SUBCASE("connection refused, before any read succeeds") + { + channel = grpc::CreateChannel("127.0.0.1:1", grpc::InsecureChannelCredentials()); + CHECK(run_call([] { }) == terminal::error); + } + + server->Shutdown(); + server->Wait(); +} From 04ce3d5714703edb5bd3e52a8b528628895af850 Mon Sep 17 00:00:00 2001 From: Markus Werle Date: Thu, 26 Nov 2026 00:38:49 +0100 Subject: [PATCH 2/4] rppgrpc: base_writer is not copyable; new client tests pass clang-tidy and build with GCC 10 Co-Authored-By: Claude Opus 5.5 --- .../rppgrpc/rppgrpc/details/base.hpp | 4 ++ src/tests/rppgrpc/test_async_client.cpp | 59 +++++++++++-------- 2 files changed, 39 insertions(+), 24 deletions(-) diff --git a/src/extensions/rppgrpc/rppgrpc/details/base.hpp b/src/extensions/rppgrpc/rppgrpc/details/base.hpp index 7cd210c55..c91f6bee3 100644 --- a/src/extensions/rppgrpc/rppgrpc/details/base.hpp +++ b/src/extensions/rppgrpc/rppgrpc/details/base.hpp @@ -34,6 +34,10 @@ namespace rppgrpc::details m_subject.get_observable().subscribe(typename details::base_writer::observer_strategy{m_state}); } + // The observer's shared state points back at this object, so a copy would write through the original. + base_writer(const base_writer&) = delete; + base_writer& operator=(const base_writer&) = delete; + virtual ~base_writer() noexcept = default; auto get_observer() const diff --git a/src/tests/rppgrpc/test_async_client.cpp b/src/tests/rppgrpc/test_async_client.cpp index 3d58a2695..a3e2a4f60 100644 --- a/src/tests/rppgrpc/test_async_client.cpp +++ b/src/tests/rppgrpc/test_async_client.cpp @@ -14,12 +14,11 @@ #include "rpp_trompeloil.hpp" +#include #include #include -#include #include #include -#include namespace { @@ -30,13 +29,13 @@ namespace IMPLEMENT_MOCK2(Bidirectional); }; - // The write side of the reactors, with a start_write that waits until it is released. + // The write side of the reactors, with a start_write that signals `entered` and waits for `release`. // on_done() does what the reactors' OnDone does with their write side: handle_on_done(), then `delete this`. struct blocking_writer final : rppgrpc::details::base_writer { - blocking_writer(std::latch& entered, std::latch& release) + blocking_writer(std::promise& entered, std::shared_future release) : m_entered{entered} - , m_release{release} + , m_release{std::move(release)} { } @@ -49,14 +48,14 @@ namespace private: void start_write(const int&) override { - m_entered.count_down(); + m_entered.set_value(); m_release.wait(); } void finish_writes(const grpc::Status&) override { } - std::latch& m_entered; - std::latch& m_release; + std::promise& m_entered; + std::shared_future m_release; }; } // namespace @@ -462,19 +461,19 @@ TEST_CASE("async client reactor: write that is under way when the call ends") // t0 is inside start_write. t1 has entered the observer and waits behind t0. Then the write side ends // and its owner is deleted, as in OnDone. Neither thread may touch the deleted owner afterwards: a write // that does is a use-after-free; AddressSanitizer reports it. - std::latch entered{1}; - std::latch release{1}; - auto* const writer = new blocking_writer{entered, release}; - const auto observer = writer->get_observer(); + std::promise entered{}; + std::promise release{}; + auto* const writer = new blocking_writer{entered, release.get_future().share()}; + const auto observer = writer->get_observer(); std::thread t0{[&] { observer.on_next(1); }}; - entered.wait(); + entered.get_future().wait(); std::thread t1{[&] { observer.on_next(2); }}; std::this_thread::sleep_for(std::chrono::milliseconds{50}); // t1 waits behind t0 auto done = std::async(std::launch::async, [writer] { writer->on_done(); }); std::this_thread::sleep_for(std::chrono::milliseconds{50}); // on_done() runs while t0 is inside start_write - release.count_down(); + release.set_value(); done.get(); t0.join(); @@ -507,7 +506,8 @@ TEST_CASE("async client reactor: writes from other threads while the call ends") const auto stub = TestService::NewStub(server->InProcessChannel({}), {}); // Starts one call, emits from `writers` threads, ends the call with `end_call` and waits for the reactor's - // terminal, which it emits from OnDone. + // terminal, which it emits from OnDone. The context must outlive the call: after a timeout the call is + // cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). const auto run_call = [&](const auto& end_call) { grpc::ClientContext ctx{}; const auto done = std::make_shared>(); @@ -519,24 +519,30 @@ TEST_CASE("async client reactor: writes from other threads while the call ends") const auto observer = reactor->get_observer(); reactor->init(); - std::atomic_bool stop{}; - std::vector threads{}; - for (int i = 0; i < writers; ++i) + std::atomic_bool stop{}; + std::array threads{}; + for (auto& t : threads) { - threads.emplace_back([&] { + t = std::thread{[&] { Request request{}; for (uint32_t v = 0; v < writes && !stop; ++v) { request.set_value(v); observer.on_next(request); } - }); + }}; } end_call(ctx); - const bool ended = done->get_future().wait_for(std::chrono::seconds{5}) == std::future_status::ready; - stop = true; + auto on_done = done->get_future(); + const bool ended = on_done.wait_for(std::chrono::seconds{5}) == std::future_status::ready; + stop = true; for (auto& t : threads) t.join(); + if (!ended) + { + ctx.TryCancel(); + on_done.wait(); + } return ended; }; @@ -588,7 +594,8 @@ TEST_CASE("async client reactor: bidirectional call reaches OnDone however it en }; // Starts one call on `channel`, writes once after init(), ends the call with `end_call` and returns the - // terminal the reactor emitted from OnDone. + // terminal the reactor emitted from OnDone. The context must outlive the call: after a timeout the call is + // cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). const auto run_call = [&](const auto& end_call) { const auto stub = TestService::NewStub(channel, {}); const auto result = std::make_shared>(); @@ -602,7 +609,11 @@ TEST_CASE("async client reactor: bidirectional call reaches OnDone however it en observer.on_next(Request{}); end_call(); auto f = result->get_future(); - return f.wait_for(std::chrono::seconds{5}) == std::future_status::ready ? f.get() : terminal::none; + if (f.wait_for(std::chrono::seconds{5}) == std::future_status::ready) + return f.get(); + ctx.TryCancel(); + f.wait(); + return terminal::none; }; SUBCASE("server finishes with OK") From 2efcd8d54c6c8bb38547f796def4df617f0b3150 Mon Sep 17 00:00:00 2001 From: Markus Werle Date: Thu, 26 Nov 2026 00:54:19 +0100 Subject: [PATCH 3/4] rppgrpc: a write completion after the write side has closed starts no further write or finish Co-Authored-By: Claude Opus 5.5 --- .../rppgrpc/rppgrpc/client_reactor.hpp | 6 ++-- .../rppgrpc/rppgrpc/details/base.hpp | 5 ++- src/tests/rppgrpc/test_async_client.cpp | 33 +++++++++++++++++++ 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp index aab301f61..1eb642e5a 100644 --- a/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp +++ b/src/extensions/rppgrpc/rppgrpc/client_reactor.hpp @@ -28,7 +28,7 @@ namespace rppgrpc * - to access values FROM stream you can subscribe to observable obtained via `reactor->get_observable()` (same observable WOULD emit on_completed in case of successful stream termination and on_error in case of some errors with grpc stream) * - to pass values TO stream you can emit values to observer obtained via `reactor->get_observer()` * - * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`, so obtain the observer and the observable before `init()` and do not use the reactor afterwards. The observer may be used from any thread, also after `init()`: the reactor holds the call (see `grpc::ClientBidiReactor::AddHold`) until its read side has ended, and values emitted after that are dropped. + * @warning After `init()` the call may end at any moment (connection refused, deadline, cancel) and the reactor deletes itself in `OnDone`, so obtain the observer and the observable before `init()` and do not use the reactor afterwards. The observer may be used from any thread, also after `init()`: the reactor holds the call (see `grpc::ClientBidiReactor::AddHold`) until its read side has ended; values still queued then, and values emitted after that, are dropped. * * @snippet client_reactor.cpp bidi_reactor * @@ -85,8 +85,8 @@ namespace rppgrpc { // One read is always posted, so each call ends its read side exactly once, here. // A write that took the observer's lock before close_writes() has called StartWrite - // and is counted by gRPC, so OnDone comes after its OnWriteDone; later writes are - // dropped. This reaction is itself still counted, so RemoveHold() does not run OnDone. + // and is counted by gRPC, so OnDone comes after its OnWriteDone; later and still queued + // writes are dropped. This reaction is itself still counted, so RemoveHold() does not run OnDone. details::base_writer::close_writes(); Base::RemoveHold(); return; diff --git a/src/extensions/rppgrpc/rppgrpc/details/base.hpp b/src/extensions/rppgrpc/rppgrpc/details/base.hpp index c91f6bee3..4adc20a23 100644 --- a/src/extensions/rppgrpc/rppgrpc/details/base.hpp +++ b/src/extensions/rppgrpc/rppgrpc/details/base.hpp @@ -55,7 +55,7 @@ namespace rppgrpc::details m_subject.get_disposable().dispose(); } - // Values and terminals emitted to the observer after this call reach neither this object nor its stream. + // Values and terminals emitted to the observer after this call, and values still queued, reach neither this object nor its stream. // It waits for an emission that is inside start_write or finish_writes. void close_writes() { @@ -68,6 +68,9 @@ namespace rppgrpc::details std::lock_guard lock{m_state->mutex}; m_state->queue.pop_front(); + if (!m_state->owner) + return; + if (!m_state->queue.empty()) { start_write(m_state->queue.front()); diff --git a/src/tests/rppgrpc/test_async_client.cpp b/src/tests/rppgrpc/test_async_client.cpp index a3e2a4f60..f52358b88 100644 --- a/src/tests/rppgrpc/test_async_client.cpp +++ b/src/tests/rppgrpc/test_async_client.cpp @@ -19,6 +19,7 @@ #include #include #include +#include namespace { @@ -57,6 +58,20 @@ namespace std::promise& m_entered; std::shared_future m_release; }; + + // The write side of the reactors, recording what it passes to the stream. + struct recording_writer final : rppgrpc::details::base_writer + { + using base_writer::close_writes; + using base_writer::handle_write_done; + + std::vector writes{}; + int finishes{}; + + private: + void start_write(const int& v) override { writes.push_back(v); } + void finish_writes(const grpc::Status&) override { ++finishes; } + }; } // namespace TEST_CASE("async client reactor") @@ -480,6 +495,24 @@ TEST_CASE("async client reactor: write that is under way when the call ends") t1.join(); } +TEST_CASE("async client reactor: values still queued when the write side closes are dropped") +{ + // A reactor closes its write side once its stream has ended (client_bidi_reactor in OnReadDone(false)). + // The completion of the write that was in flight then starts neither the next queued value nor the + // half-close. + recording_writer writer{}; + const auto observer = writer.get_observer(); + observer.on_next(1); + observer.on_next(2); + observer.on_completed(); + + writer.close_writes(); + writer.handle_write_done(); // OnWriteDone(true) for the value 1 + + CHECK(writer.writes == std::vector{1}); + CHECK(writer.finishes == 0); +} + TEST_CASE("async client reactor: writes from other threads while the call ends") { // Threads emit into the reactor's observer after init() while the call ends. A write that reaches the From b093fe72364ebc8d7998973820fb21303dfa2299 Mon Sep 17 00:00:00 2001 From: Markus Werle Date: Thu, 26 Nov 2026 22:50:18 +0100 Subject: [PATCH 4/4] rppgrpc: client tests reuse their writer threads, prove that closing waits for the write under way, own the blocking writer by unique_ptr Co-Authored-By: Claude Opus 5.5 --- src/tests/rppgrpc/test_async_client.cpp | 154 ++++++++++++++++++------ 1 file changed, 120 insertions(+), 34 deletions(-) diff --git a/src/tests/rppgrpc/test_async_client.cpp b/src/tests/rppgrpc/test_async_client.cpp index f52358b88..7bdd48837 100644 --- a/src/tests/rppgrpc/test_async_client.cpp +++ b/src/tests/rppgrpc/test_async_client.cpp @@ -14,10 +14,13 @@ #include "rpp_trompeloil.hpp" -#include #include +#include #include #include +#include +#include +#include #include #include @@ -31,21 +34,16 @@ namespace }; // The write side of the reactors, with a start_write that signals `entered` and waits for `release`. - // on_done() does what the reactors' OnDone does with their write side: handle_on_done(), then `delete this`. struct blocking_writer final : rppgrpc::details::base_writer { + using base_writer::handle_on_done; + blocking_writer(std::promise& entered, std::shared_future release) : m_entered{entered} , m_release{std::move(release)} { } - void on_done() - { - handle_on_done(); - delete this; - } - private: void start_write(const int&) override { @@ -53,6 +51,7 @@ namespace m_release.wait(); } + // The test emits no terminal, so the write side is never finished. void finish_writes(const grpc::Status&) override { } std::promise& m_entered; @@ -72,6 +71,96 @@ namespace void start_write(const int& v) override { writes.push_back(v); } void finish_writes(const grpc::Status&) override { ++finishes; } }; + + // Threads that live as long as this object. start() hands them an observer, and each of them emits up to + // `writes` values into it until stop() is called. stop() returns once every thread has left the observer. + class writer_threads + { + public: + explicit writer_threads(size_t count) + { + for (size_t i = 0; i < count; ++i) + m_threads.emplace_back([this] { run(); }); + } + + writer_threads(const writer_threads&) = delete; + writer_threads& operator=(const writer_threads&) = delete; + + ~writer_threads() + { + { + std::lock_guard lock{m_mutex}; + m_exit = true; + } + m_cv.notify_all(); + for (auto& t : m_threads) + t.join(); + } + + void start(rpp::dynamic_observer observer, uint32_t writes) + { + { + std::lock_guard lock{m_mutex}; + m_observer.emplace(std::move(observer)); + m_writes = writes; + m_stop = false; + m_running = m_threads.size(); + ++m_round; + } + m_cv.notify_all(); + } + + void stop() + { + m_stop = true; + std::unique_lock lock{m_mutex}; + m_cv.wait(lock, [this] { return m_running == 0; }); + m_observer.reset(); + } + + private: + void run() + { + size_t round = 0; + while (true) + { + const rpp::dynamic_observer* observer{}; + uint32_t writes{}; + { + std::unique_lock lock{m_mutex}; + m_cv.wait(lock, [&] { return m_exit || m_round != round; }); + if (m_exit) + return; + round = m_round; + observer = &*m_observer; + writes = m_writes; + } + + Request request{}; + for (uint32_t v = 0; v < writes && !m_stop; ++v) + { + request.set_value(v); + observer->on_next(request); + } + + { + std::lock_guard lock{m_mutex}; + --m_running; + } + m_cv.notify_all(); + } + } + + std::mutex m_mutex{}; + std::condition_variable m_cv{}; + std::optional> m_observer{}; + uint32_t m_writes{}; + size_t m_round{}; + size_t m_running{}; + bool m_exit{}; + std::atomic_bool m_stop{}; + std::vector m_threads{}; + }; } // namespace TEST_CASE("async client reactor") @@ -474,11 +563,12 @@ TEST_CASE("async client reactor: call that ends during init()") TEST_CASE("async client reactor: write that is under way when the call ends") { // t0 is inside start_write. t1 has entered the observer and waits behind t0. Then the write side ends - // and its owner is deleted, as in OnDone. Neither thread may touch the deleted owner afterwards: a write - // that does is a use-after-free; AddressSanitizer reports it. + // and its owner is destroyed, as in OnDone. Ending the write side waits until t0 has left start_write, + // and neither thread may touch the destroyed owner afterwards: a write that does is a use-after-free; + // AddressSanitizer reports it. std::promise entered{}; std::promise release{}; - auto* const writer = new blocking_writer{entered, release.get_future().share()}; + auto writer = std::make_unique(entered, release.get_future().share()); const auto observer = writer->get_observer(); std::thread t0{[&] { observer.on_next(1); }}; @@ -486,11 +576,18 @@ TEST_CASE("async client reactor: write that is under way when the call ends") std::thread t1{[&] { observer.on_next(2); }}; std::this_thread::sleep_for(std::chrono::milliseconds{50}); // t1 waits behind t0 - auto done = std::async(std::launch::async, [writer] { writer->on_done(); }); - std::this_thread::sleep_for(std::chrono::milliseconds{50}); // on_done() runs while t0 is inside start_write + std::atomic_bool closed{}; + auto done = std::async(std::launch::async, [&] { + writer->handle_on_done(); + closed = true; + writer.reset(); + }); + std::this_thread::sleep_for(std::chrono::milliseconds{50}); // handle_on_done() runs while t0 is inside start_write + CHECK_FALSE(closed.load()); // and has not returned release.set_value(); done.get(); + CHECK(closed.load()); t0.join(); t1.join(); } @@ -519,7 +616,7 @@ TEST_CASE("async client reactor: writes from other threads while the call ends") // reactor after OnDone, or its stream after gRPC has destroyed it, is a use-after-free; AddressSanitizer // reports it. constexpr int iterations = 200; - constexpr int writers = 2; + constexpr size_t writers = 2; constexpr uint32_t writes = 1000; grpc::ServerBuilder builder{}; @@ -538,9 +635,12 @@ TEST_CASE("async client reactor: writes from other threads while the call ends") auto server = builder.BuildAndStart(); const auto stub = TestService::NewStub(server->InProcessChannel({}), {}); - // Starts one call, emits from `writers` threads, ends the call with `end_call` and waits for the reactor's - // terminal, which it emits from OnDone. The context must outlive the call: after a timeout the call is - // cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). + // The same `writers` threads serve every call of a subcase. + writer_threads threads{writers}; + + // Starts one call, lets the writer threads emit into its observer, ends the call with `end_call` and waits for + // the reactor's terminal, which it emits from OnDone. The context must outlive the call: after a timeout the + // call is cancelled and OnDone is still awaited (a call that never ends is left to the process timeout). const auto run_call = [&](const auto& end_call) { grpc::ClientContext ctx{}; const auto done = std::make_shared>(); @@ -549,28 +649,14 @@ TEST_CASE("async client reactor: writes from other threads while the call ends") [done](const std::exception_ptr&) { done->set_value(); }, [done] { done->set_value(); }); stub->async()->Bidirectional(&ctx, reactor); - const auto observer = reactor->get_observer(); + auto observer = reactor->get_observer().as_dynamic(); reactor->init(); - std::atomic_bool stop{}; - std::array threads{}; - for (auto& t : threads) - { - t = std::thread{[&] { - Request request{}; - for (uint32_t v = 0; v < writes && !stop; ++v) - { - request.set_value(v); - observer.on_next(request); - } - }}; - } + threads.start(std::move(observer), writes); end_call(ctx); auto on_done = done->get_future(); const bool ended = on_done.wait_for(std::chrono::seconds{5}) == std::future_status::ready; - stop = true; - for (auto& t : threads) - t.join(); + threads.stop(); if (!ended) { ctx.TryCancel();