Skip to content

rppgrpc: server_write_reactor calls Finish twice when the client cancels during a write, and gRPC aborts the server process #773

Done

Description

@daixtrose

Version: v2.2.4 and the head of v2 (562869957f5092e692e69ea7898e563582a70ada); rppgrpc is the same in both. gRPC 1.51.1, GCC 14.2, C++20, Linux x86_64.

Summary. A server-streaming method returns a server_write_reactor. The client cancels the call while the server still has a write in flight. The server process then aborts with:

callback_common.h:164]                assertion failed: call_ == nullptr

The reactor calls Finish twice on the same call, and gRPC does not allow that.

The two calls to Finish (server_reactor.hpp):

  1. The cancel makes the write in flight fail. OnWriteDone(false) calls Finish(grpc::Status::OK) (L143-L152).
  2. OnCancel() calls Finish(grpc::Status::CANCELLED) without checking whether Finish was already called (L162-L168).

gRPC's side (read from the source at v1.51.1):

  • The rule: "Every RPC MUST be finished using either Finish or StartWriteAndFinish (but not both), even if the RPC is already cancelled" (server_callback.h L388-L391, on ServerBidiReactor::Finish; ServerWriteReactor::Finish has no comment of its own).
  • OnCancel() also runs after Finish(): the server counts a call as cancelled when its status has not been sent yet (call.cc L876-L878), and the completion op then calls OnCancel() (server_context.cc L204-L241).
  • A second Finish sets the finish tag a second time (server_callback_handlers.h L510-L514). The tag asserts that it has not been set before, and that assertion is active in release builds (callback_common.h L164).

Reproduction. One program with server and client in one process, on the in-process channel. The server queues 50 answers and never completes the observer. The client reads one answer and cancels.

// repro.cpp
#include "repro.grpc.pb.h"

#include <grpcpp/grpcpp.h>
#include <rpp/rpp.hpp>
#include <rppgrpc/rppgrpc.hpp>

#include <cstdio>

class Service final : public repro::Feed::CallbackService
{
    grpc::ServerWriteReactor<repro::Msg>* Stream(grpc::CallbackServerContext*, const repro::Msg*) override
    {
        auto*      reactor = new rppgrpc::server_write_reactor<repro::Msg>();
        repro::Msg msg;
        for (int i = 0; i < 50; ++i) // queued, written one at a time
        {
            msg.set_value(i);
            reactor->get_observer().on_next(msg);
        }
        return reactor; // the observer is not completed: the stream goes on until the client cancels
    }
};

int main()
{
    Service             service;
    grpc::ServerBuilder builder;
    builder.RegisterService(&service);
    auto server = builder.BuildAndStart();
    auto stub   = repro::Feed::NewStub(server->InProcessChannel({}));

    for (int call = 0; call < 200; ++call)
    {
        grpc::ClientContext ctx;
        auto                reader = stub->Stream(&ctx, repro::Msg{});
        repro::Msg          msg;
        reader->Read(&msg); // one answer, then cancel while the server's next write is in flight
        ctx.TryCancel();
        reader->Finish();
    }
    std::puts("200 calls, no abort");
    server->Shutdown();
}
Proto file and CMake file
// repro.proto
syntax = "proto3";

package repro;

message Msg { int32 value = 1; }

service Feed {
  rpc Stream(Msg) returns (stream Msg);
}
# CMakeLists.txt
cmake_minimum_required(VERSION 3.25)
project(rppgrpc_write_double_finish LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 20)

find_package(gRPC CONFIG REQUIRED)
find_program(PROTOC protoc REQUIRED)
find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin REQUIRED)

include(FetchContent)
FetchContent_Declare(rpp
  GIT_REPOSITORY https://github.com/AlexInLog/ReactivePlusPlus.git
  GIT_TAG        v2.2.4
  GIT_SHALLOW    TRUE)
FetchContent_MakeAvailable(rpp)

add_custom_command(
  OUTPUT repro.pb.cc repro.grpc.pb.cc
  COMMAND ${PROTOC} -I ${CMAKE_CURRENT_SOURCE_DIR} --cpp_out=. --grpc_out=.
          --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN} ${CMAKE_CURRENT_SOURCE_DIR}/repro.proto
  DEPENDS repro.proto)
add_library(proto STATIC repro.pb.cc repro.grpc.pb.cc)
target_include_directories(proto PUBLIC ${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(proto PUBLIC gRPC::grpc++)

add_executable(repro repro.cpp)
target_link_libraries(repro PRIVATE proto rpp rppgrpc)

Built with CMake, Ninja and CMAKE_BUILD_TYPE=RelWithDebInfo against the system gRPC 1.51.1. The program aborts on every run; it never prints "200 calls, no abort":

$ ./repro
E1126 00:23:29.254562573      10 callback_common.h:164]                assertion failed: call_ == nullptr
bash: line 1:     9 Aborted                 (core dumped) ./repro
exit code 134

The same program built with -fsanitize=address and run with ASAN_OPTIONS=handle_abort=1 shows where the second Finish comes from (frames shortened):

    #4 grpc::internal::CallbackWithSuccessTag::Set(...) /usr/include/grpcpp/support/callback_common.h:164
    #5 grpc::internal::CallbackServerStreamingHandler<repro::Msg, repro::Msg>::ServerCallbackWriterImpl::Finish(grpc::Status) /usr/include/grpcpp/impl/codegen/server_callback_handlers.h:514
    #6 grpc::ServerWriteReactor<repro::Msg>::Finish(grpc::Status) /usr/include/grpcpp/support/server_callback.h:648
    #7 rppgrpc::server_write_reactor<repro::Msg>::OnCancel() src/extensions/rppgrpc/rppgrpc/server_reactor.hpp:167
    #9 grpc_core::Executor::RunClosures(char const*, grpc_closure_list)

The observer is never completed in this program, so the first Finish can only have come from OnWriteDone(false).

A second path, read from the source, not reproduced. OnCancel() disposes the write subject, but it leaves the write queue and the finished flag as they are (base.hpp L46-L49). Suppose the observer completed while writes were still queued, so only the flag was set (L89-L96). If the last write then completes with ok == true after OnCancel(), handle_write_done() finds the queue empty and the flag set, and calls Finish(OK) again (L51-L64). gRPC runs OnCancel() on its executor, apart from the write callbacks (server_callback.cc L57-L83), and gives no order between the two. server_bidi_reactor has the same path. Pull request 772 removes it: OnCancel() clears the writer's owner there, so a later write completion no longer calls Finish.

Related. Pull request 771 adds a guard to server_bidi_reactor only: every Finish goes through one atomic flag, and only the first caller finishes. The same guard fits server_write_reactor, where finish_writes, OnWriteDone(false) and OnCancel() would all go through it. server_read_reactor calls Finish only in OnReadDone(false), so it has a single Finish by construction.

I am happy to send a pull request with the guard and a test along the lines of the program above.

Activity

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