From 6c1150a85d37b9afe4810bb769b25b4b302b29c8 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Mon, 12 Oct 2026 13:16:44 -0700 Subject: [PATCH 1/3] Split RPC command processing into focused helpers Extract backpressure, redirect/forward and commit completion blocks without changing retry control, transaction ownership or exception handling. Add regression coverage for local commit callbacks, receipt fields and replication failure. Measured cognitive complexity drops from 90 to 44; all helpers remain below 50. Ref #7358. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/node/rpc/frontend.h | 383 ++++++++++++++++------------ src/node/rpc/test/frontend_test.cpp | 202 +++++++++++++++ 2 files changed, 418 insertions(+), 167 deletions(-) diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index f3d9f1f58b85..b28d1986ba36 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -706,7 +706,212 @@ namespace ccf } } - // NOLINTNEXTLINE(readability-function-cognitive-complexity) + bool check_backpressure( + const std::shared_ptr& ctx, + ccf::kv::Consensus* current_consensus) + { + if (current_consensus != nullptr) + { + if ( + endpoints.apply_uncommitted_tx_backpressure() && + current_consensus->should_apply_backpressure()) + { + ctx->set_error( + HTTP_STATUS_SERVICE_UNAVAILABLE, + ccf::errors::TooManyPendingTransactions, + "Too many transactions pending commit on the service."); + return false; + } + } + + return true; + } + + bool redirect_or_forward( + ccf::kv::ReadOnlyTx& tx, + const std::shared_ptr& ctx, + const endpoints::EndpointDefinitionPtr& endpoint, + std::optional& + redirections, + ccf::kv::Consensus* current_consensus) + { + // If there's no interface ID, this is already forwarded or otherwise + // special - don't try to redirect it + if (ctx->get_session_context()->interface_id.has_value()) + { + redirections = get_redirections_config( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ctx->get_session_context()->interface_id); + } + + // If a redirections config was specified, then redirections are used + // and no forwarding is done + if (redirections.has_value()) + { + if (check_redirect(tx, ctx, endpoint, *redirections, current_consensus)) + { + return true; + } + } + else + { + bool is_primary = + current_consensus == nullptr || current_consensus->can_replicate(); + const bool forwardable = current_consensus != nullptr; + + if (!is_primary && forwardable) + { + switch (endpoint->properties.forwarding_required) + { + case endpoints::ForwardingRequired::Never: + { + break; + } + + case endpoints::ForwardingRequired::Sometimes: + { + if (ctx->get_session_context()->is_forwarding) + { + forward(ctx, tx, endpoint, current_consensus); + return true; + } + break; + } + + case endpoints::ForwardingRequired::Always: + { + forward(ctx, tx, endpoint, current_consensus); + return true; + } + } + } + } + + return false; + } + + enum class CommitAction + { + Done, + Retry + }; + + CommitAction commit_transaction( + const std::shared_ptr& ctx, + const endpoints::EndpointDefinitionPtr& endpoint, + ccf::EndpointContextImpl& args, + ccf::kv::Consensus* current_consensus, + ccf::kv::TxHistory* current_history) + { + // args owns a valid Tx relating to a non-pending response, which + // should be applied + ccf::kv::CommittableTx& tx = *args.owned_tx; + + // Only capture write set digest and commit evidence if the + // handler has set a consensus committed callback that may need + // them for receipt construction. Avoids unnecessary hashing + // on the common path. + ccf::crypto::Sha256Hash captured_ws_digest; + std::string captured_commit_evidence; + ccf::kv::CommittableTx::WriteSetObserver ws_observer = nullptr; + ccf::endpoints::ConsensusCommittedEndpointFunction committed_func = + ctx->consensus_committed_func; + if (committed_func != nullptr) + { + ws_observer = [&captured_ws_digest, &captured_commit_evidence]( + const ccf::crypto::Sha256Hash& ws_digest, + const std::string& ce) { + captured_ws_digest = ws_digest; + captured_commit_evidence = ce; + }; + } + + ccf::kv::CommitResult result = tx.commit(ctx->claims, ws_observer); + + switch (result) + { + case ccf::kv::CommitResult::SUCCESS: + { + auto tx_id_opt = tx.get_txid(); + if (tx_id_opt.has_value() && current_consensus != nullptr) + { + ccf::TxID tx_id = tx_id_opt.value(); + + try + { + // Only transactions that acquired one or more map handles + // have a TxID, while others (e.g. unauthenticated commands) + // don't. Also, only report a TxID if the consensus is set, as + // the consensus is required to verify that a TxID is valid. + endpoints.execute_endpoint_locally_committed( + endpoint, args, tx_id); + } + catch (const std::exception& e) + { + // run default handler to set transaction id in header + ctx->clear_response_headers(); + ccf::endpoints::default_locally_committed_func(args, tx_id); + ctx->set_error( + HTTP_STATUS_INTERNAL_SERVER_ERROR, + ccf::errors::InternalError, + fmt::format( + "Failed to execute local commit handler func: {}", e.what())); + } + catch (...) + { + // run default handler to set transaction id in header + ctx->clear_response_headers(); + ccf::endpoints::default_locally_committed_func(args, tx_id); + ctx->set_error( + HTTP_STATUS_INTERNAL_SERVER_ERROR, + ccf::errors::InternalError, + "Failed to execute local commit handler func"); + } + + { + if (committed_func != nullptr) + { + ctx->respond_on_commit = + ccf::RpcContextImpl::RespondOnCommitInfo{ + tx_id, + committed_func, + std::move(captured_ws_digest), + std::move(captured_commit_evidence), + ctx->claims}; + } + } + } + + if ( + current_consensus != nullptr && + current_consensus->can_replicate() && current_history != nullptr) + { + current_history->try_emit_signature(); + } + + return CommitAction::Done; + } + + case ccf::kv::CommitResult::FAIL_CONFLICT: + { + break; + } + + case ccf::kv::CommitResult::FAIL_NO_REPLICATE: + { + ctx->clear_response_headers(); + ctx->set_error( + HTTP_STATUS_SERVICE_UNAVAILABLE, + ccf::errors::TransactionReplicationFailed, + "Transaction failed to replicate."); + + return CommitAction::Done; + } + } + + return CommitAction::Retry; + } + void process_command_inner( std::shared_ptr ctx, endpoints::EndpointDefinitionPtr& endpoint, @@ -735,18 +940,9 @@ namespace ccf auto* current_consensus = consensus.load(std::memory_order_acquire); auto* current_history = history.load(std::memory_order_acquire); - if (current_consensus != nullptr) + if (!check_backpressure(ctx, current_consensus)) { - if ( - endpoints.apply_uncommitted_tx_backpressure() && - current_consensus->should_apply_backpressure()) - { - ctx->set_error( - HTTP_STATUS_SERVICE_UNAVAILABLE, - ccf::errors::TooManyPendingTransactions, - "Too many transactions pending commit on the service."); - return; - } + return; } std::unique_ptr tx_p = tables.create_tx_ptr(); @@ -777,57 +973,10 @@ namespace ccf std::optional redirections = std::nullopt; - // If there's no interface ID, this is already forwarded or otherwise - // special - don't try to redirect it - if (ctx->get_session_context()->interface_id.has_value()) - { - redirections = get_redirections_config( - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - *ctx->get_session_context()->interface_id); - } - - // If a redirections config was specified, then redirections are used - // and no forwarding is done - if (redirections.has_value()) + if (redirect_or_forward( + *tx_p, ctx, endpoint, redirections, current_consensus)) { - if (check_redirect( - *tx_p, ctx, endpoint, *redirections, current_consensus)) - { - return; - } - } - else - { - bool is_primary = current_consensus == nullptr || - current_consensus->can_replicate(); - const bool forwardable = current_consensus != nullptr; - - if (!is_primary && forwardable) - { - switch (endpoint->properties.forwarding_required) - { - case endpoints::ForwardingRequired::Never: - { - break; - } - - case endpoints::ForwardingRequired::Sometimes: - { - if (ctx->get_session_context()->is_forwarding) - { - forward(ctx, *tx_p, endpoint, current_consensus); - return; - } - break; - } - - case endpoints::ForwardingRequired::Always: - { - forward(ctx, *tx_p, endpoint, current_consensus); - return; - } - } - } + return; } std::unique_ptr identity = @@ -882,112 +1031,12 @@ namespace ccf "Illegal endpoint implementation"); return; } - // else args owns a valid Tx relating to a non-pending response, which - // should be applied - ccf::kv::CommittableTx& tx = *args.owned_tx; - - // Only capture write set digest and commit evidence if the - // handler has set a consensus committed callback that may need - // them for receipt construction. Avoids unnecessary hashing - // on the common path. - ccf::crypto::Sha256Hash captured_ws_digest; - std::string captured_commit_evidence; - ccf::kv::CommittableTx::WriteSetObserver ws_observer = nullptr; - ccf::endpoints::ConsensusCommittedEndpointFunction committed_func = - ctx->consensus_committed_func; - if (committed_func != nullptr) - { - ws_observer = [&captured_ws_digest, &captured_commit_evidence]( - const ccf::crypto::Sha256Hash& ws_digest, - const std::string& ce) { - captured_ws_digest = ws_digest; - captured_commit_evidence = ce; - }; - } - - ccf::kv::CommitResult result = tx.commit(ctx->claims, ws_observer); - - switch (result) + if ( + commit_transaction( + ctx, endpoint, args, current_consensus, current_history) == + CommitAction::Done) { - case ccf::kv::CommitResult::SUCCESS: - { - auto tx_id_opt = tx.get_txid(); - if (tx_id_opt.has_value() && current_consensus != nullptr) - { - ccf::TxID tx_id = tx_id_opt.value(); - - try - { - // Only transactions that acquired one or more map handles - // have a TxID, while others (e.g. unauthenticated commands) - // don't. Also, only report a TxID if the consensus is set, as - // the consensus is required to verify that a TxID is valid. - endpoints.execute_endpoint_locally_committed( - endpoint, args, tx_id); - } - catch (const std::exception& e) - { - // run default handler to set transaction id in header - ctx->clear_response_headers(); - ccf::endpoints::default_locally_committed_func(args, tx_id); - ctx->set_error( - HTTP_STATUS_INTERNAL_SERVER_ERROR, - ccf::errors::InternalError, - fmt::format( - "Failed to execute local commit handler func: {}", - e.what())); - } - catch (...) - { - // run default handler to set transaction id in header - ctx->clear_response_headers(); - ccf::endpoints::default_locally_committed_func(args, tx_id); - ctx->set_error( - HTTP_STATUS_INTERNAL_SERVER_ERROR, - ccf::errors::InternalError, - "Failed to execute local commit handler func"); - } - - { - if (committed_func != nullptr) - { - ctx->respond_on_commit = - ccf::RpcContextImpl::RespondOnCommitInfo{ - tx_id, - committed_func, - std::move(captured_ws_digest), - std::move(captured_commit_evidence), - ctx->claims}; - } - } - } - - if ( - current_consensus != nullptr && - current_consensus->can_replicate() && - current_history != nullptr) - { - current_history->try_emit_signature(); - } - - return; - } - - case ccf::kv::CommitResult::FAIL_CONFLICT: - { - break; - } - - case ccf::kv::CommitResult::FAIL_NO_REPLICATE: - { - ctx->clear_response_headers(); - ctx->set_error( - HTTP_STATUS_SERVICE_UNAVAILABLE, - ccf::errors::TransactionReplicationFailed, - "Transaction failed to replicate."); - - return; - } + return; } } catch (const ccf::kv::CompactedVersionConflict& e) diff --git a/src/node/rpc/test/frontend_test.cpp b/src/node/rpc/test/frontend_test.cpp index 81aca967f416..d99f0c22e143 100644 --- a/src/node/rpc/test/frontend_test.cpp +++ b/src/node/rpc/test/frontend_test.cpp @@ -1911,6 +1911,208 @@ TEST_CASE("Retry on conflict") } } +class TestCommitHistory : public ccf::NullTxHistory +{ +public: + using ccf::NullTxHistory::NullTxHistory; + + std::function on_signature; + + void try_emit_signature() override + { + on_signature(); + } +}; + +TEST_CASE("Commit completion preserves callbacks and receipt details") +{ + bool wait_for_consensus = true; + bool throw_standard_exception = false; + bool throw_unknown_exception = false; + SUBCASE("Successful local commit") {} + SUBCASE("No consensus callback") + { + wait_for_consensus = false; + } + SUBCASE("Standard exception from local commit callback") + { + throw_standard_exception = true; + } + SUBCASE("Unknown exception from local commit callback") + { + throw_unknown_exception = true; + } + + NetworkState network; + prepare_callers(network); + const auto consensus = + std::dynamic_pointer_cast( + network.tables->get_consensus()); + REQUIRE(consensus != nullptr); + auto history = std::make_shared( + *network.tables, ccf::kv::test::PrimaryNodeId, *kp); + network.tables->set_history(history); + BaseTestFrontend frontend(*network.tables); + + auto session = std::make_shared( + ccf::InvalidSessionId, anonymous_caller_der); + auto request = create_simple_request("/commit"); + auto rpc_ctx = ccf::make_rpc_context(session, request.build_request()); + std::vector events; + std::optional locally_committed_tx_id; + size_t consensus_callback_count = 0; + auto handler = [&](auto& ctx) { + events.push_back("endpoint"); + ctx.tx.template rw>("test_commit")->put(0, 42); + ctx.rpc_ctx->set_claims_digest(ccf::crypto::Sha256Hash("test claims")); + if (wait_for_consensus) + { + ctx.rpc_ctx->set_consensus_committed_function( + [&](auto&) { ++consensus_callback_count; }); + } + ctx.rpc_ctx->set_response_status(HTTP_STATUS_OK); + }; + auto locally_committed = [&](auto& ctx, const ccf::TxID& tx_id) { + events.push_back("local"); + locally_committed_tx_id = tx_id; + CHECK_FALSE(rpc_ctx->respond_on_commit.has_value()); + ctx.rpc_ctx->set_response_header("test-local", "true"); + if (throw_standard_exception) + { + throw std::runtime_error("test failure"); + } + if (throw_unknown_exception) + { + throw 42; + } + ccf::endpoints::default_locally_committed_func(ctx, tx_id); + }; + frontend.make_endpoint("/commit", HTTP_POST, handler) + .set_locally_committed_function(locally_committed) + .install(); + frontend.open(); + publish_frontend_state(frontend, network); + + history->on_signature = [&]() { + const std::vector before_signature = {"endpoint", "local"}; + CHECK(events == before_signature); + CHECK(rpc_ctx->respond_on_commit.has_value() == wait_for_consensus); + events.push_back("signature"); + }; + + frontend.process(rpc_ctx); + + REQUIRE_FALSE(rpc_ctx->response_is_pending); + REQUIRE(locally_committed_tx_id.has_value()); + const std::vector expected_events = { + "endpoint", "local", "signature"}; + CHECK(events == expected_events); + CHECK(consensus_callback_count == 0); + auto response = parse_response(rpc_ctx->serialise_response()); + CHECK( + response.headers[ccf::http::headers::CCF_TX_ID] == + locally_committed_tx_id->to_str()); + if (throw_standard_exception || throw_unknown_exception) + { + CHECK(response.status == HTTP_STATUS_INTERNAL_SERVER_ERROR); + CHECK(response.headers.find("test-local") == response.headers.end()); + const auto message = throw_standard_exception ? + "Failed to execute local commit handler func: test failure" : + "Failed to execute local commit handler func"; + CHECK( + nlohmann::json::parse(response.body)["error"] == + nlohmann::json{ + {"code", ccf::errors::InternalError}, {"message", message}}); + } + else + { + CHECK(response.status == HTTP_STATUS_OK); + CHECK(response.headers["test-local"] == "true"); + } + + if (wait_for_consensus) + { + REQUIRE(rpc_ctx->respond_on_commit.has_value()); + const auto& committed = rpc_ctx->respond_on_commit.value(); + CHECK(committed.tx_id == locally_committed_tx_id.value()); + const auto serialised = consensus->get_latest_data(); + REQUIRE(serialised.has_value()); + const auto expected_digest = + ccf::crypto::Sha256Hash({serialised->data(), serialised->size()}); + CHECK(committed.write_set_digest == expected_digest); + CHECK( + committed.commit_evidence == + encryptor->get_commit_evidence(committed.tx_id)); + CHECK( + committed.claims_digest.value() == + ccf::crypto::Sha256Hash("test claims")); + REQUIRE(committed.committed_func != nullptr); + ccf::endpoints::CommittedTxInfo info{}; + committed.committed_func(info); + CHECK(consensus_callback_count == 1); + } + else + { + CHECK_FALSE(rpc_ctx->respond_on_commit.has_value()); + } +} + +TEST_CASE("Replication failure completes without retry or commit callbacks") +{ + struct FailingConsensus : public ccf::kv::test::PrimaryStubConsensus + { + bool replicate(const ccf::kv::BatchVector&, ccf::View) override + { + return false; + } + }; + + NetworkState network; + prepare_callers(network); + network.tables->set_consensus(std::make_shared()); + auto history = std::make_shared( + *network.tables, ccf::kv::test::PrimaryNodeId, *kp); + network.tables->set_history(history); + BaseTestFrontend frontend(*network.tables); + size_t execution_count = 0; + size_t locally_committed_count = 0; + size_t signature_count = 0; + history->on_signature = [&]() { ++signature_count; }; + auto handler = [&](auto& ctx) { + ++execution_count; + ctx.tx.template rw>("test_commit")->put(0, 42); + ctx.rpc_ctx->set_consensus_committed_function([](auto&) {}); + ctx.rpc_ctx->set_response_header("test-execution", "true"); + ctx.rpc_ctx->set_response_status(HTTP_STATUS_OK); + }; + frontend.make_endpoint("/commit", HTTP_POST, handler) + .set_locally_committed_function( + [&](auto&, const ccf::TxID&) { ++locally_committed_count; }) + .install(); + frontend.open(); + publish_frontend_state(frontend, network); + auto session = std::make_shared( + ccf::InvalidSessionId, anonymous_caller_der); + auto request = create_simple_request("/commit"); + auto rpc_ctx = ccf::make_rpc_context(session, request.build_request()); + + frontend.process(rpc_ctx); + + REQUIRE_FALSE(rpc_ctx->response_is_pending); + CHECK(execution_count == 1); + CHECK(locally_committed_count == 0); + CHECK(signature_count == 0); + CHECK_FALSE(rpc_ctx->respond_on_commit.has_value()); + const auto response = parse_response(rpc_ctx->serialise_response()); + CHECK(response.status == HTTP_STATUS_SERVICE_UNAVAILABLE); + CHECK(response.headers.find("test-execution") == response.headers.end()); + CHECK( + nlohmann::json::parse(response.body)["error"] == + nlohmann::json{ + {"code", ccf::errors::TransactionReplicationFailed}, + {"message", "Transaction failed to replicate."}}); +} + class TestManualConflictsRegistry : public UserEndpointRegistry { public: From 7b51dc01b1f12155a8b85d8ac9abb1d897dc469d Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Mon, 12 Oct 2026 14:29:57 -0700 Subject: [PATCH 2/3] Give RPC commit action an explicit small underlying type Use uint8_t for the private Done/Retry enum and include cstdint directly, matching the existing endpoint enum convention. Fix performance-enum-size under the required clang-tidy configuration without changing values, retry semantics, or suppressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/node/rpc/frontend.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/node/rpc/frontend.h b/src/node/rpc/frontend.h index b28d1986ba36..8ce5b203df13 100644 --- a/src/node/rpc/frontend.h +++ b/src/node/rpc/frontend.h @@ -26,6 +26,7 @@ #define FMT_HEADER_ONLY #include +#include #include #include #include @@ -790,7 +791,7 @@ namespace ccf return false; } - enum class CommitAction + enum class CommitAction : uint8_t { Done, Retry From 7e4a6583010af8b91ec28249a7c94c6bb7689524 Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Fri, 16 Oct 2026 08:50:10 +0100 Subject: [PATCH 3/3] Add 7.0.20 changelog entry Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 8 ++++++++ python/pyproject.toml | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d16f10537cf5..1851866841c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). +## [7.0.20] + +[7.0.20]: https://github.com/microsoft/CCF/releases/tag/ccf-7.0.20 + +### Changed + +- No user-visible changes. Internal request-processing code was restructured without changing behaviour (#8562). + ## [7.0.19] [7.0.19]: https://github.com/microsoft/CCF/releases/tag/ccf-7.0.19 diff --git a/python/pyproject.toml b/python/pyproject.toml index 2bbbc4c90f4e..92e71ee47252 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ccf" -version = "7.0.19" +version = "7.0.20" authors = [ { name="CCF Team", email="CCF-Sec@microsoft.com" }, ]