From 17076839c5a158a6700b044b84f3c2fd2bf4f87c Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 13:57:33 +0000 Subject: [PATCH 01/10] Fence local writes against step-down with a role lock A local writer (RPC transaction, emit_signature, snapshot evidence) could publish to the KV and Merkle history after its node had stepped down, racing follower execute_append_entries_sync. This made the follower reject valid entries or retain a stale leaf. Store now has a role_rwlock and a can_write_locally flag. Local writes take a shared permit before mutating maps, version or history, and release it before replicate. Aft closes the gate under unique_lock on every demotion (including RetiredCommitted, after compact returns), rolls back to last_idx only on a writable->non-writable transition, and reopens it only on become_leader. replicate no longer rolls back. next_txid returns nullopt when local writes are disabled. Store::commit now also checks rollback_count before appending to history, not just to the chunker. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- .../local-writes-fenced-on-step-down.fixed.md | 1 + src/consensus/aft/cft.h | 52 ++- src/consensus/aft/cft_types.h | 24 ++ src/consensus/aft/test/logging_stub.h | 12 + src/consensus/aft/test/main.cpp | 4 +- .../aft/test/view_straddling_common.h | 88 +++-- .../aft/test/view_straddling_history.cpp | 327 +++++++++++++----- .../aft/test/view_straddling_rollback.cpp | 16 +- src/kv/committable_tx.h | 40 ++- src/kv/kv_types.h | 54 ++- src/kv/store.h | 119 ++++++- src/kv/test/kv_serialisation.cpp | 4 +- src/kv/test/kv_test.cpp | 38 +- src/kv/test/null_tx_history.h | 7 +- src/node/history.h | 10 +- src/node/test/historical_queries.cpp | 2 +- src/node/test/history.cpp | 8 +- 17 files changed, 637 insertions(+), 169 deletions(-) create mode 100644 .changes/local-writes-fenced-on-step-down.fixed.md diff --git a/.changes/local-writes-fenced-on-step-down.fixed.md b/.changes/local-writes-fenced-on-step-down.fixed.md new file mode 100644 index 000000000000..c16c9fd4b9b3 --- /dev/null +++ b/.changes/local-writes-fenced-on-step-down.fixed.md @@ -0,0 +1 @@ +A primary that steps down no longer races local transactions, signatures or snapshot evidence against incoming replication, which could cause the node to reject valid entries or diverge from the service's ledger. diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 2f141212cc58..3f457ef9df9a 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -170,6 +170,10 @@ namespace aft // append entries bool public_only = false; + // Whether this has set the Store's term, which can only be initialised + // once, and must later be updated by rollback. + bool store_term_initialised = false; + // Randomness std::uniform_int_distribution distrib; std::default_random_engine rand; @@ -213,7 +217,12 @@ namespace aft ledger(std::move(ledger_)), channels(std::move(channels_)) - {} + { + // Only a primary accepts local writes. The Store may already hold + // state, from a snapshot or a recovered ledger, which must not be + // rolled back here. + store->disable_local_writes(); + } ~Aft() override = default; @@ -664,9 +673,10 @@ namespace aft if (state->leadership_state.load() != ccf::kv::LeadershipState::Leader) { + // Local writes were disabled, and the speculative local state these + // entries belong to discarded, when this node stopped being leader. CFT_DEBUG_FMT( "Failed to replicate {} items: not leader", entries.size()); - rollback(state->last_idx); return false; } @@ -685,7 +695,6 @@ namespace aft CFT_DEBUG_FMT( "Failed to replicate {} items: node retirement is complete", entries.size()); - rollback(state->last_idx); return false; } @@ -2072,6 +2081,19 @@ namespace aft } } + // Stops the Store accepting local writes, once local writers that may + // still publish have finished. If it was accepting them, discards the + // speculative local state they wrote beyond last_idx, which no further + // local writer can add to. Must be called with state->lock held, and not + // under any Store lock. + void close_local_writes() + { + if (store->disable_local_writes()) + { + rollback(state->last_idx); + } + } + void become_pre_vote_candidate() { if (configurations.empty()) @@ -2086,6 +2108,7 @@ namespace aft state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); + close_local_writes(); reset_votes_for_me(); restart_election_timeout(); @@ -2128,6 +2151,7 @@ namespace aft voted_for = state->node_id; reset_votes_for_me(); state->current_view++; + close_local_writes(); restart_election_timeout(); reset_last_ack_timeouts(); @@ -2167,16 +2191,27 @@ namespace aft { rollback(election_index); } - else + else if (!store_term_initialised) { // but we still want the KV to know which term we're in store->initialise_term(state->current_view); + store_term_initialised = true; + } + else + { + // The KV's term was already set, by an earlier election or rollback, + // so update it without discarding anything. + rollback(state->last_idx); } state->leadership_state.store(ccf::kv::LeadershipState::Leader); leader_id = state->node_id; should_sign = true; + // The KV is now in this term, and holds no speculative state from an + // earlier one, so local writes can start. + store->enable_local_writes(); + using namespace std::chrono_literals; timeout_elapsed = 0ms; @@ -2218,6 +2253,7 @@ namespace aft reset_last_ack_timeouts(); state->leadership_state.store(ccf::kv::LeadershipState::Follower); + close_local_writes(); CFT_INFO_FMT( "Becoming follower {}: {}.{}", state->node_id, @@ -2608,6 +2644,13 @@ namespace aft CFT_DEBUG_FMT("Compacting..."); store->compact(idx); + // Compaction may have run the hook that completes this node's + // retirement, which cannot itself stop local writes because it runs + // under the Store's locks. + if (is_retired_committed()) + { + close_local_writes(); + } ledger->commit(idx); if (commit_observer != nullptr) @@ -2690,6 +2733,7 @@ namespace aft } store->rollback({get_term_internal(idx), idx}, state->current_view); + store_term_initialised = true; CFT_DEBUG_FMT("Setting term in store to: {}", state->current_view); ledger->truncate(idx); diff --git a/src/consensus/aft/cft_types.h b/src/consensus/aft/cft_types.h index f55092a3be27..602d02416d17 100644 --- a/src/consensus/aft/cft_types.h +++ b/src/consensus/aft/cft_types.h @@ -29,6 +29,11 @@ namespace aft virtual void rollback( const ccf::TxID& tx_id, Term term_of_next_version) = 0; virtual void initialise_term(Term t) = 0; + // Stops accepting local writes, waiting for local writers that may still + // publish to finish. Returns true if local writes were accepted until now, + // in which case the caller must discard any speculative local state. + virtual bool disable_local_writes() = 0; + virtual void enable_local_writes() = 0; virtual std::unique_ptr deserialize( std::vector data, bool public_only = false, @@ -71,6 +76,25 @@ namespace aft } } + bool disable_local_writes() override + { + auto p = x.lock(); + if (p) + { + return p->disable_local_writes(); + } + return false; + } + + void enable_local_writes() override + { + auto p = x.lock(); + if (p) + { + p->enable_local_writes(); + } + } + std::unique_ptr deserialize( const std::vector data, bool public_only = false, diff --git a/src/consensus/aft/test/logging_stub.h b/src/consensus/aft/test/logging_stub.h index a47b42f92f73..96d23a367460 100644 --- a/src/consensus/aft/test/logging_stub.h +++ b/src/consensus/aft/test/logging_stub.h @@ -370,6 +370,18 @@ namespace aft virtual void initialise_term(Term t) {} + bool local_writes_enabled = true; + + virtual bool disable_local_writes() + { + return std::exchange(local_writes_enabled, false); + } + + virtual void enable_local_writes() + { + local_writes_enabled = true; + } + ccf::kv::Version current_version() { return ccf::kv::NoVersion; diff --git a/src/consensus/aft/test/main.cpp b/src/consensus/aft/test/main.cpp index 4a51e65ca4de..8f8da8f35a1c 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -3492,7 +3492,7 @@ DOCTEST_TEST_CASE( ccf::kv::Version append_signature() { - const auto txid = sender_store.next_txid(); + const auto txid = sender_store.next_txid().value(); auto tx = sender_store.create_reserved_tx(txid); tx.rw(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); tx.rw(serialised_tree)->put({}); @@ -3508,7 +3508,7 @@ DOCTEST_TEST_CASE( size_t value, const std::optional& new_config = std::nullopt) { - const auto txid = sender_store.next_txid(); + const auto txid = sender_store.next_txid().value(); auto tx = sender_store.create_reserved_tx(txid); tx.rw(values)->put(key, value); if (new_config.has_value()) diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index d424495e34cb..3d9ef69d3acd 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -10,6 +10,7 @@ #include "kv/store.h" #include "test_common.h" +#include #include #include #include @@ -21,7 +22,6 @@ namespace straddling { using TestMap = ccf::kv::Map; - using Cft = aft::Aft; class BaselinePendingTx : public ccf::kv::PendingTx { @@ -129,29 +129,62 @@ namespace straddling }; // Behaves like ccf::kv::MovePendingTx, the PendingTx of every normal - // transaction: hands over an already-serialised entry and cannot fail. It - // pauses first, modelling the committing thread being descheduled after - // Store::commit() has checked the transaction's view and released - // version_lock, but before it reaches CFT. In production this is the - // thread blocking on aft::State::lock while an election holds it. - class PausingMovePendingTx : public ccf::kv::PendingTx + // transaction: hands over an already-serialised entry and cannot fail. If + // given a pause, it pauses first, while Store::commit() holds the Store's + // role lock shared, modelling the committing thread being descheduled + // while it publishes the entry. + class ReadyPendingTx : public ccf::kv::PendingTx { ccf::kv::PendingTxInfo info; - CommitPause& pause; + CommitPause* pause; public: - PausingMovePendingTx(ccf::kv::PendingTxInfo&& info_, CommitPause& pause_) : + ReadyPendingTx( + ccf::kv::PendingTxInfo&& info_, CommitPause* pause_ = nullptr) : info(std::move(info_)), pause(pause_) {} ccf::kv::PendingTxInfo call() override { - pause.pause(); + if (pause != nullptr) + { + pause->pause(); + } return std::move(info); } }; + // Pauses the next call to replicate() once armed, before it takes CFT's + // lock. This models the committing thread being descheduled after + // Store::commit() has published the entry locally and released the + // Store's locks, but before it reaches CFT. In production this is the + // thread blocking on aft::State::lock while an election holds it. + class PausingCft : public aft::Aft + { + std::atomic next_pause = nullptr; + + public: + using aft::Aft::Aft; + + void pause_next_replicate(CommitPause& pause) + { + next_pause.store(&pause); + } + + bool replicate(const ccf::kv::BatchVector& entries, aft::Term term) override + { + auto* pause = next_pause.exchange(nullptr); + if (pause != nullptr) + { + pause->pause(); + } + return aft::Aft::replicate(entries, term); + } + }; + + using Cft = PausingCft; + static std::optional read_value( ccf::kv::Store& store, TestMap& table, size_t key) { @@ -164,6 +197,7 @@ namespace straddling const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId; std::shared_ptr store = std::make_shared(); TestMap table{"public:table"}; + std::shared_ptr state = std::make_shared(node_id); std::shared_ptr cft; ccf::View initial_view = 0; @@ -175,13 +209,28 @@ namespace straddling // Split from the constructor so that a derived fixture can install a // history before CFT is created and the baseline is committed. void start() + { + start_consensus(); + const auto baseline_txid = store->next_txid().value(); + REQUIRE( + store->commit( + baseline_txid, + std::make_unique(baseline_txid, *store, table), + true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(store->current_txid() == ccf::TxID(initial_view, 1)); + REQUIRE(cft->get_committed_seqno() == 1); + REQUIRE(cft->ledger->ledger.size() == 1); + } + + // Creates CFT and makes this node primary, with nothing committed. + void start_consensus() { cft = std::make_shared( cft_settings, std::make_unique>(store), std::make_unique(node_id), std::make_shared(), - std::make_shared(node_id), + state, nullptr); store->set_consensus(cft); @@ -190,23 +239,20 @@ namespace straddling cft->add_configuration(0, configuration); cft->force_become_primary(); initial_view = cft->get_view(); + } - const auto baseline_txid = store->next_txid(); - REQUIRE( - store->commit( - baseline_txid, - std::make_unique(baseline_txid, *store, table), - true) == ccf::kv::CommitResult::SUCCESS); - REQUIRE(store->current_txid() == ccf::TxID(initial_view, 1)); - REQUIRE(cft->get_committed_seqno() == 1); - REQUIRE(cft->ledger->ledger.size() == 1); + // Lose leadership, discarding everything after CFT's last index once + // in-flight local writers have finished publishing. + void step_down() + { + cft->become_aware_of_new_term(cft->get_view() + 1); } // Lose leadership, then win a later election. become_leader() rolls the // Store back to the last committable index (1) under the new view. ccf::View reelect() { - cft->become_aware_of_new_term(cft->get_view() + 1); + step_down(); cft->force_become_primary(); return cft->get_view(); } diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index c6913724ff93..45e8a2d5a8ae 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -1,23 +1,25 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache 2.0 License. -// A transaction which CFT is going to reject must never be published -// to the ledger history. Readers of the history, for instance -// set_root_on_proposals(), take no Store lock, so a transiently appended -// digest would give them a root which is in neither the KV nor the ledger. +// A transaction which CFT is going to reject must not remain published in +// the ledger history. Readers of the history, for instance +// set_root_on_proposals(), take no Store lock, so a stale digest would give +// them a root which is in neither the KV nor the ledger. On a follower, a +// stale digest would also prevent the root signed by the primary from +// matching, and the follower would reject valid entries. // -// Store::commit() checks the transaction's view under version_lock, then -// releases that lock before appending to the history. A rollback can land in -// that window. The guard is the view captured under version_lock, which is -// passed to TxHistory::append_entry() and compared against the history's own -// view under the history lock, dropping the append if they differ. +// Store::commit() publishes a local transaction to the history while it +// holds the Store's role lock shared, and CFT discards everything published +// after its last index once it has taken that lock exclusively, when the +// node stops being primary. A local writer therefore either finishes +// publishing before the node steps down, and is discarded, or is refused. // // Interleaving, from PR #8223: // -// - Tx A passes Store::commit()'s view check under version_lock, which is -// then released. +// - Tx A is published locally by Store::commit(), which then releases its +// locks before calling CFT. // - An election rolls the Store and the ledger history back to seqno 1. -// - A appends its digest to the history, then CFT rejects it. +// - CFT rejects A, which must not reappear in the history. #include "node/history.h" #include "view_straddling_common.h" @@ -28,48 +30,40 @@ using namespace straddling; namespace { - // A history which pauses once, on the next append_entry() call after it is - // armed, after the base class has done its work and released its lock. What - // it has published at that point is exactly what any concurrent reader of - // the history would see. - class PausableHistory : public ccf::MerkleTxHistory + struct HistoryFixture : public Fixture { - std::atomic armed = false; - - public: - using ccf::MerkleTxHistory::MerkleTxHistory; - - CommitPause pause; + ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); + std::shared_ptr history; - void arm() + HistoryFixture() { - armed.store(true); + history = + std::make_shared(*store, node_id, *node_kp); + store->set_history(history); + start(); } - void append_entry( - const ccf::crypto::Sha256Hash& digest, - std::optional expected_term_of_next_version = - std::nullopt) override + ccf::crypto::Sha256Hash root() { - ccf::MerkleTxHistory::append_entry(digest, expected_term_of_next_version); - - if (armed.exchange(false)) - { - pause.pause(); - } + const auto [txid, root, term] = + history->get_replicated_state_txid_and_root(); + return root; } - }; - struct HistoryFixture : public Fixture - { - ccf::crypto::ECKeyPairPtr node_kp = ccf::crypto::make_ec_key_pair(); - std::shared_ptr history; + ccf::SeqNo history_seqno() + { + const auto [txid, root, term] = + history->get_replicated_state_txid_and_root(); + return txid.seqno; + } - HistoryFixture() + // Applies a write at the next TxID, without committing it to the Store. + std::pair prepare(size_t key) { - history = std::make_shared(*store, node_id, *node_kp); - store->set_history(history); - start(); + const auto txid = store->next_txid().value(); + auto tx = store->create_reserved_tx(txid); + tx.rw(table)->put(key, key); + return {txid, tx.commit_reserved()}; } }; } @@ -80,64 +74,227 @@ TEST_CASE( { HistoryFixture fixture; - const auto [baseline_txid, baseline_root, _] = - fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(baseline_txid.seqno == 1); + const auto baseline_root = fixture.root(); + REQUIRE(fixture.history_seqno() == 1); INFO("Apply and serialise A at seqno 2 in the initial view"); - const auto stale_txid = fixture.store->next_txid(); + auto [stale_txid, stale_info] = fixture.prepare(1); REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); - auto stale_info = [&]() { - auto tx = fixture.store->create_reserved_tx(stale_txid); - tx.rw(fixture.table)->put(1, 2); - return tx.commit_reserved(); - }(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); - INFO("A enters Store::commit, passes its view check, then is descheduled"); - CommitPause commit_pause; + INFO( + "A is published locally by Store::commit, then is descheduled before " + "reaching consensus"); + CommitPause replicate_pause; + fixture.cft->pause_next_replicate(replicate_pause); std::optional stale_result; - Worker stale_worker({&commit_pause, &fixture.history->pause}, [&]() { + Worker stale_worker({&replicate_pause}, [&]() { stale_result = fixture.store->commit( stale_txid, - std::make_unique( - std::move(stale_info), commit_pause), + std::make_unique(std::move(stale_info)), false); }); - REQUIRE(commit_pause.wait_until_paused()); + REQUIRE(replicate_pause.wait_until_paused()); + REQUIRE(fixture.history_seqno() == 2); INFO("Lose leadership and win a later election, rolling back to seqno 1"); fixture.reelect(); - { - const auto [rolled_back_txid, rolled_back_root, rolled_back_term] = - fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(rolled_back_txid.seqno == 1); - REQUIRE(rolled_back_root == baseline_root); - } - - INFO("Resume A, and observe the history once its append has completed"); - fixture.history->arm(); - commit_pause.release(); - REQUIRE(fixture.history->pause.wait_until_paused()); - { - const auto [observed_txid, observed_root, observed_term] = - fixture.history->get_replicated_state_txid_and_root(); - CHECK(observed_txid.seqno == 1); - CHECK(observed_root == baseline_root); - } - fixture.history->pause.release(); - stale_worker.join(); + REQUIRE(fixture.history_seqno() == 1); + REQUIRE(fixture.root() == baseline_root); - INFO("cft rejects A, and history, KV and ledger agree"); + INFO("Resume A: cft rejects it, and history, KV and ledger agree"); + replicate_pause.release(); + stale_worker.join(); REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); - { - const auto [final_txid, final_root, final_term] = - fixture.history->get_replicated_state_txid_and_root(); - CHECK(final_txid.seqno == 1); - CHECK(final_root == baseline_root); - } + CHECK(fixture.history_seqno() == 1); + CHECK(fixture.root() == baseline_root); + CHECK(fixture.store->current_txid().seqno == 1); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(fixture.cft->ledger->ledger.size() == 1); +} + +TEST_CASE( + "Stepping down waits for an in-flight local writer, then discards it" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + + const auto baseline_root = fixture.root(); + + INFO("A enters Store::commit and is descheduled while publishing"); + auto [txid, info] = fixture.prepare(1); + CommitPause publish_pause; + std::optional result; + Worker writer({&publish_pause}, [&]() { + result = fixture.store->commit( + txid, + std::make_unique(std::move(info), &publish_pause), + false); + }); + REQUIRE(publish_pause.wait_until_paused()); + + INFO("Stepping down cannot complete while A is publishing"); + std::atomic stepped_down = false; + std::thread demoter([&]() { + fixture.step_down(); + stepped_down.store(true); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + CHECK_FALSE(stepped_down.load()); + + INFO("Once A has published, stepping down discards it"); + publish_pause.release(); + writer.join(); + demoter.join(); + REQUIRE(stepped_down.load()); + REQUIRE(result.has_value()); + CHECK(result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.history_seqno() == 1); + CHECK(fixture.root() == baseline_root); CHECK(fixture.store->current_txid().seqno == 1); + CHECK_FALSE(read_value(*fixture.store, fixture.table, 1).has_value()); CHECK(fixture.cft->get_last_idx() == 1); CHECK(fixture.cft->ledger->ledger.size() == 1); } + +TEST_CASE( + "A follower refuses local writes and signatures, but not reads" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + fixture.history->set_endorsed_certificate(fixture.node_kp->self_sign( + "CN=Node", + ccf::ds::to_x509_time_string(std::chrono::system_clock::now()), + ccf::ds::to_x509_time_string( + std::chrono::system_clock::now() + std::chrono::hours(24)))); + + INFO("A transaction starts while the node is primary"); + auto stale_tx = fixture.store->create_tx(); + stale_tx.rw(fixture.table)->put(1, 1); + + fixture.step_down(); + const auto baseline_root = fixture.root(); + const auto baseline_txid = fixture.store->current_txid(); + + INFO("A signature, which is reserved directly, is not emitted"); + CHECK_FALSE(fixture.store->next_txid().has_value()); + fixture.history->emit_signature(); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); + + INFO("Writes are refused, whether started before or after stepping down"); + CHECK(stale_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + auto tx = fixture.store->create_tx(); + tx.rw(fixture.table)->put(2, 2); + CHECK(tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); + + INFO("A read-only transaction still commits"); + auto ro_tx = fixture.store->create_tx(); + CHECK(ro_tx.rw(fixture.table)->get(0) == 1); + CHECK(ro_tx.commit() == ccf::kv::CommitResult::SUCCESS); + + INFO("A snapshot cannot be requested"); + auto snapshot_tx = fixture.store->create_tx(); + CHECK(snapshot_tx.ro(fixture.table)->get(0) == 1); + snapshot_tx.set_tx_flag( + ccf::kv::CommittableTx::TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); + CHECK(snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK_FALSE(fixture.store->flag_enabled( + ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE)); + + INFO("Writes are accepted again once the node is re-elected"); + fixture.cft->force_become_primary(); + auto new_tx = fixture.store->create_tx(); + new_tx.rw(fixture.table)->put(3, 3); + CHECK(new_tx.commit() == ccf::kv::CommitResult::SUCCESS); + CHECK(fixture.store->next_txid().has_value()); +} + +TEST_CASE( + "Completing retirement on global commit stops local writes" * + doctest::test_suite("view_straddling_history")) +{ + HistoryFixture fixture; + + INFO( + "As in production, a global hook run by compaction completes this " + "node's retirement, under the Store's locks"); + TestMap retired{"public:retired"}; + fixture.store->set_global_hook( + retired.get_name(), + TestMap::wrap_commit_hook( + [&fixture](ccf::kv::Version version, const TestMap::Write&) { + fixture.cft->set_retired_committed(version, {fixture.node_id}); + })); + + // Retirement is otherwise driven by reconfiguration, which needs more + // nodes, so start from its last phase before RetiredCommitted. + fixture.state->membership_state = ccf::kv::MembershipState::Retired; + fixture.state->retirement_phase = ccf::kv::RetirementPhase::Completed; + fixture.state->retirement_idx = 1; + fixture.state->retirement_committable_idx = 1; + + INFO("Committing the retirement completes it, without deadlocking"); + const auto txid = fixture.store->next_txid().value(); + auto tx = fixture.store->create_reserved_tx(txid); + tx.rw(retired)->put(0, 0); + REQUIRE( + fixture.store->commit( + txid, std::make_unique(tx.commit_reserved()), true) == + ccf::kv::CommitResult::SUCCESS); + REQUIRE(fixture.cft->get_committed_seqno() == 2); + REQUIRE(fixture.cft->is_retired_committed()); + + const auto baseline_root = fixture.root(); + const auto baseline_txid = fixture.store->current_txid(); + + INFO("Local writes are refused"); + CHECK_FALSE(fixture.store->next_txid().has_value()); + auto write_tx = fixture.store->create_tx(); + write_tx.rw(fixture.table)->put(1, 1); + CHECK(write_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + + INFO("And remain refused, since a retired node cannot become primary"); + fixture.cft->force_become_primary(); + CHECK_FALSE(fixture.store->next_txid().has_value()); + auto later_tx = fixture.store->create_tx(); + later_tx.rw(fixture.table)->put(2, 2); + CHECK(later_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.store->current_txid() == baseline_txid); + CHECK(fixture.root() == baseline_root); +} + +TEST_CASE( + "A node can be re-elected before anything is committed" * + doctest::test_suite("view_straddling_history")) +{ + Fixture fixture; + fixture.start_consensus(); + REQUIRE(fixture.cft->get_committed_seqno() == 0); + + INFO( + "A transaction, such as the genesis transaction, is replicated but not " + "committed in the first term"); + auto tx = fixture.store->create_tx(); + tx.rw(fixture.table)->put(1, 1); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + REQUIRE(fixture.cft->get_last_idx() == 1); + REQUIRE(fixture.cft->get_committed_seqno() == 0); + + INFO("Re-election keeps it, and moves the Store to the new term"); + fixture.step_down(); + REQUIRE_NOTHROW(fixture.cft->force_become_primary()); + const auto view = fixture.cft->get_view(); + REQUIRE(view > fixture.initial_view); + CHECK(fixture.cft->get_last_idx() == 1); + CHECK(read_value(*fixture.store, fixture.table, 1) == 1); + + auto next_tx = fixture.store->create_tx(); + next_tx.rw(fixture.table)->put(2, 2); + CHECK(next_tx.commit() == ccf::kv::CommitResult::SUCCESS); + CHECK(next_tx.get_txid() == ccf::TxID(view, 2)); + CHECK(fixture.cft->get_last_idx() == 2); +} diff --git a/src/consensus/aft/test/view_straddling_rollback.cpp b/src/consensus/aft/test/view_straddling_rollback.cpp index 4a903058fb43..dc0b65319888 100644 --- a/src/consensus/aft/test/view_straddling_rollback.cpp +++ b/src/consensus/aft/test/view_straddling_rollback.cpp @@ -16,10 +16,10 @@ // src/consensus/aft/cft.h): // // - Tx A is applied locally in view V and given TxID V.2. It enters -// Store::commit(), passes the view check, and is descheduled before it +// Store::commit(), is published locally, and is descheduled before it // reaches CFT. -// - An election happens. The node wins in view W > V, and become_leader() -// rolls the Store back past A, to seqno 1. +// - An election happens. Stepping down rolls the Store back past A, to seqno +// 1, and the node then wins in view W > V. // - Tx B is applied locally in view W and given TxID W.2. It has not yet // entered Store::commit(). // - A continues. CFT rejects it. If that rejection rolls the Store @@ -58,7 +58,7 @@ TEST_CASE( fixture.start(); INFO("Apply and serialise A at seqno 2 in the initial view"); - const auto stale_txid = fixture.store->next_txid(); + const auto stale_txid = fixture.store->next_txid().value(); REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 2)); auto stale_info = [&]() { auto tx = fixture.store->create_reserved_tx(stale_txid); @@ -68,14 +68,16 @@ TEST_CASE( REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); REQUIRE(read_value(*fixture.store, fixture.table, 1) == 2); - INFO("A enters Store::commit, passes its view check, then is descheduled"); + INFO( + "A enters Store::commit, is published locally, then is descheduled " + "before reaching consensus"); CommitPause stale_pause; + fixture.cft->pause_next_replicate(stale_pause); std::optional stale_result; Worker stale_worker({&stale_pause}, [&]() { stale_result = fixture.store->commit( stale_txid, - std::make_unique( - std::move(stale_info), stale_pause), + std::make_unique(std::move(stale_info)), false); }); REQUIRE(stale_pause.wait_until_paused()); diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 97eb1a2c9fae..2bf358e936f4 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -259,6 +259,21 @@ namespace ccf::kv } } #endif + const auto force_ledger_chunk = + tx_flag_enabled(TxFlag::LEDGER_CHUNK_AT_NEXT_SIGNATURE); + const auto snapshot_at_next_signature = + tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); + + // Held from before any write is applied until the Store flags have been + // applied, so that consensus cannot discard local state in between. + // Read-only transactions that set no Store flag do not need it, and can + // commit on any node. + LocalWritePermit permit; + if (has_writes() || snapshot_at_next_signature) + { + permit = pimpl->store->acquire_local_write_permit(); + } + { MapSetLockGuard map_set_guard(*pimpl->store, maps_created); #ifdef CCF_KV_TRACING @@ -268,7 +283,8 @@ namespace ccf::kv c = apply_changes( all_changes, [&]() { - auto resolution = pimpl->store->next_version(pimpl->commit_view); + auto resolution = + pimpl->store->next_version(pimpl->commit_view, permit); commit_term_changed = !resolution.has_value(); if (!resolution.has_value()) { @@ -304,14 +320,22 @@ namespace ccf::kv return CommitResult::FAIL_CONFLICT; } + if ( + c.value() == NoVersion && snapshot_at_next_signature && + !permit.allows_writes()) + { + // A snapshot can only be requested on a node that will emit the next + // signature. + LOG_TRACE_FMT( + "Could not request a snapshot because this node does not accept " + "local writes"); + KV_TRACE(trace_commit.result("no_replicate", 0)); + return CommitResult::FAIL_NO_REPLICATE; + } + committed = true; version = c.value(); - const auto force_ledger_chunk = - tx_flag_enabled(TxFlag::LEDGER_CHUNK_AT_NEXT_SIGNATURE); - const auto snapshot_at_next_signature = - tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); - if (version == NoVersion) { // Read-only transaction. It has no version to attach a ledger chunk @@ -349,6 +373,10 @@ namespace ccf::kv } } + // Store::commit() acquires its own permit, and the write set observer + // may call into the Store, so this must not be held past here. + permit.release(); + // From here, we have received a unique commit version and made // modifications to our local kv. If we fail in any way, we cannot // recover. diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index e88bc7e40065..5277d43cee10 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -10,6 +10,7 @@ #include "ccf/ds/hex.h" #include "ccf/ds/join.h" #include "ccf/ds/json.h" +#include "ccf/ds/locking.h" #include "ccf/ds/net_address.h" #include "ccf/ds/nonstd.h" #include "ccf/entity_id.h" @@ -36,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -830,6 +832,46 @@ namespace ccf::kv consume_commit_evidence_digest() = 0; }; + // A shared hold on a Store's role lock. While it is held, the Store cannot + // switch between accepting and refusing local writes, so a local writer can + // apply and publish its writes without a concurrent demotion discarding them + // underneath it. + class LocalWritePermit + { + private: + std::shared_lock guard; + bool writable = false; + + public: + LocalWritePermit() = default; + + LocalWritePermit( + std::shared_lock&& guard_, bool writable_) : + guard(std::move(guard_)), + writable(writable_) + {} + + LocalWritePermit(LocalWritePermit&&) = default; + LocalWritePermit& operator=(LocalWritePermit&&) = default; + LocalWritePermit(const LocalWritePermit&) = delete; + LocalWritePermit& operator=(const LocalWritePermit&) = delete; + ~LocalWritePermit() = default; + + [[nodiscard]] bool allows_writes() const + { + return guard.owns_lock() && writable; + } + + void release() + { + writable = false; + if (guard.owns_lock()) + { + guard.unlock(); + } + } + }; + class AbstractStore { public: @@ -847,9 +889,17 @@ namespace ccf::kv virtual void lock_map_set() = 0; virtual void unlock_map_set() = 0; + // Acquires the role lock shared. A local writer holds the returned permit + // from before it applies its writes until it has applied any Store flags, + // and must not acquire another permit while holding it. + virtual LocalWritePermit acquire_local_write_permit() = 0; + // Returns nullopt if the permit does not allow local writes, or if the + // commit term has moved on from expected_commit_term. virtual std::optional> next_version( - Term expected_commit_term) = 0; - virtual ccf::TxID next_txid() = 0; + Term expected_commit_term, const LocalWritePermit& permit) = 0; + // Reserves the next TxID, or returns nullopt if this Store does not + // currently accept local writes. + virtual std::optional next_txid() = 0; virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; diff --git a/src/kv/store.h b/src/kv/store.h index 51e2873c5236..82786fdef8fd 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -121,6 +121,21 @@ namespace ccf::kv std::atomic readiness = StoreReadiness::Ready; + // Fences local writers (CommittableTx::commit(), next_txid() and + // Store::commit()) against consensus changing this node's role. Local + // writers hold it shared while they apply and publish writes, to the KV + // and the ledger history. Consensus takes it exclusively, under its own + // lock, to stop accepting local writes when this node stops being primary, + // and to start accepting them again when it becomes primary. Lock order: + // commit_lock -> consensus lock -> role_rwlock -> maps_lock -> + // version_lock -> history lock. It must never be held across a call into + // consensus, nor acquired recursively. + ccf::ds::SharedMutex role_rwlock; + // Only modified under role_rwlock held exclusively. A Store without + // consensus accepts local writes; consensus disables them when it binds to + // the Store, until it becomes primary. + std::atomic can_write_locally = true; + // Holds the lock of every map in a collection for its lifetime, releasing // them on every exit path. The collection must not change while held. class ScopedMapLocks @@ -1015,6 +1030,34 @@ namespace ccf::kv } } + LocalWritePermit acquire_local_write_permit() override + { + std::shared_lock guard(role_rwlock); + const auto writable = can_write_locally.load(); + return {std::move(guard), writable}; + } + + // Stops accepting local writes, waiting for any local writer currently + // holding a permit to finish publishing. Returns true if local writes were + // accepted until now, in which case the caller must discard any + // speculative local state, which no further local writer can add to. + bool disable_local_writes() + { + std::unique_lock guard(role_rwlock); + return can_write_locally.exchange(false); + } + + void enable_local_writes() + { + std::unique_lock guard(role_rwlock); + can_write_locally.store(true); + } + + [[nodiscard]] bool local_writes_enabled() const + { + return can_write_locally.load(); + } + void initialise_term(Term t) override { // Note: This should only be called once, when the store is first @@ -1184,6 +1227,19 @@ namespace ccf::kv txid.seqno, (globally_committable ? " globally_committable" : "")); + // Held from admission until the batch is published to the history and + // chunker, so that consensus cannot discard local state between this + // check and publication. It is released before calling consensus. + auto permit = acquire_local_write_permit(); + if (!permit.allows_writes()) + { + LOG_DEBUG_FMT( + "Refusing to commit {} because this node does not accept local " + "writes", + txid.seqno); + return CommitResult::FAIL_NO_REPLICATE; + } + BatchVector batch; Version previous_last_replicated = 0; Version next_last_replicated = 0; @@ -1283,25 +1339,40 @@ namespace ccf::kv txid.seqno); } - if (h) - { - h->append_entry( - ccf::entry_leaf( - *data_shared, commit_evidence_digest_, claims_digest_), - replication_view); - } + auto leaf = h ? + std::optional(ccf::entry_leaf( + *data_shared, commit_evidence_digest_, claims_digest_)) : + std::nullopt; - if (chunker) { std::lock_guard vguard(version_lock); // A rollback can only discard this batch's writes by truncating, // which requires its target to be below `version` and therefore // increments rollback_count. A rollback that does not truncate // leaves the writes intact, but may still move the term on, which - // consensus will reject - so both are checked here. + // consensus will reject - so both are checked here. Consensus does + // not roll back while local writes are accepted, so this only + // happens when the Store is rolled back directly. if ( - previous_rollback_count == rollback_count && - replication_view == term_of_next_version) + previous_rollback_count != rollback_count || + replication_view != term_of_next_version) + { + LOG_DEBUG_FMT( + "Batch for commit of {}.{} was rolled back at {}", + txid.view, + txid.seqno, + previous_last_replicated + offset); + return CommitResult::FAIL_NO_REPLICATE; + } + + // Published under version_lock, so that a rollback either discards + // these or prevents them from being published. + if (leaf.has_value()) + { + h->append_entry(leaf.value(), replication_view); + } + + if (chunker) { chunker->append_entry_size(data_shared->size()); } @@ -1323,6 +1394,11 @@ namespace ccf::kv offset++; } + // Consensus takes the role lock exclusively under its own lock, so this + // must not be held while calling into it. If this node stops being + // primary from here on, consensus refuses the batch and discards it. + permit.release(); + if (c->replicate(batch, replication_view)) { std::lock_guard vguard(version_lock); @@ -1420,8 +1496,17 @@ namespace ccf::kv } std::optional> next_version( - Term expected_commit_term) override + Term expected_commit_term, const LocalWritePermit& permit) override { + if (!permit.allows_writes()) + { + KV_TRACE(trace::local_result("no_replicate", 0)); + LOG_DEBUG_FMT( + "Refusing to assign a version to a transaction because this node " + "does not accept local writes"); + return std::nullopt; + } + std::lock_guard vguard(version_lock); // If rollback updates the term before this lock is acquired, reject the // transaction before map writes are applied. If version allocation wins @@ -1443,13 +1528,19 @@ namespace ccf::kv return std::make_tuple(v, rollback_count); } - TxID next_txid() override + std::optional next_txid() override { KV_TRACE(trace::unsupported(this, "reserved transaction ID")); + auto permit = acquire_local_write_permit(); + if (!permit.allows_writes()) + { + return std::nullopt; + } + std::lock_guard vguard(version_lock); next_version_unsafe(); - return {term_of_next_version, version}; + return TxID{term_of_next_version, version}; } size_t committable_gap() override diff --git a/src/kv/test/kv_serialisation.cpp b/src/kv/test/kv_serialisation.cpp index e3009c082ca5..89d787371de3 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -720,7 +720,7 @@ TEST_CASE( kv_store.set_max_transaction_size(1); MapTypes::StringString map("public:signature"); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); tx.rw(map)->put("signature", std::string(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = @@ -1264,7 +1264,7 @@ TEST_CASE_TEMPLATE( MapType map2("public:map"); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); auto handle = tx.rw(map); handle->put(k1, v1); handle->put(k2, v2); diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index b808e3a721b3..e5fcb47fad26 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -2595,7 +2595,7 @@ TEST_CASE("Deserialising from other Store") MapTypes::NumString public_map("public:public"); MapTypes::NumString private_map("private"); - auto tx1 = store.create_reserved_tx(store.next_txid()); + auto tx1 = store.create_reserved_tx(store.next_txid().value()); auto handle1 = tx1.rw(public_map); auto handle2 = tx1.rw(private_map); handle1->put(42, "aardvark"); @@ -2799,7 +2799,7 @@ TEST_CASE("Deserialise return status") store.set_history(history); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto data_handle = tx.rw(data); data_handle->put(42, 42); auto [success_, data_, claims_digest, commit_evidence_digest, hooks] = @@ -2814,7 +2814,7 @@ TEST_CASE("Deserialise return status") } { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto sig_handle = tx.rw(signatures); auto tree_handle = tx.rw(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); @@ -2833,7 +2833,7 @@ TEST_CASE("Deserialise return status") INFO("Signature transactions with additional contents should fail"); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto sig_handle = tx.rw(signatures); auto data_handle = tx.rw(data); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); @@ -3882,7 +3882,7 @@ TEST_CASE("CommittableTx guards") const auto baseline_txid = kv_store.current_txid(); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); reserved.rw(map)->put("k", "from_reserved"); // Roll the store back, invalidating the rollback_count that `reserved` @@ -3905,7 +3905,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); REQUIRE_THROWS_WITH_AS( reserved.commit_reserved(), "Reserved transaction cannot be empty", @@ -3917,7 +3917,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); reserved.rw(map)->put("k", "v"); REQUIRE( reserved.commit_reserved().success == ccf::kv::CommitResult::SUCCESS); @@ -3967,7 +3967,7 @@ TEST_CASE("CommittableTx guards") // Such a transaction would otherwise succeed with an empty ledger entry, // leaving nothing at its reserved version - auto reserved = kv_store.create_reserved_tx(kv_store.next_txid()); + auto reserved = kv_store.create_reserved_tx(kv_store.next_txid().value()); REQUIRE(reserved.rw(map)->get("k") == "v"); REQUIRE_THROWS_WITH_AS( reserved.commit_reserved(), @@ -4171,8 +4171,8 @@ TEST_CASE("Stale-view writes which took their version early are rejected") if (reuse_versions) { // New reservations must not make the old-view transaction valid. - REQUIRE(store.next_txid() == ccf::TxID(new_term, 3)); - REQUIRE(store.next_txid() == ccf::TxID(new_term, 4)); + REQUIRE(store.next_txid().value() == ccf::TxID(new_term, 3)); + REQUIRE(store.next_txid().value() == ccf::TxID(new_term, 4)); } }; @@ -4639,7 +4639,7 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") // committing it adds to the Store's map set. Nothing else here may take // maps_lock, or it would order the write against the readers and hide the // race being reproduced. - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); tx.rw(std::format("public:reserved_{}", i)) ->put("k", "v"); const auto [result, data, claims, commit_evidence, hooks] = @@ -4744,7 +4744,7 @@ TEST_CASE("Chunk metadata is not restored by a batch a rollback discarded") "A batch whose writes are discarded by a rollback must not leave chunk " "metadata behind"); { - const auto reserved = store.next_txid(); + const auto reserved = store.next_txid().value(); REQUIRE(reserved.seqno == baseline_txid.seqno + 1); // The rollback target is below the reserved version, so it truncates and @@ -5246,7 +5246,7 @@ TEST_CASE("Ledger entry chunk request") INFO( "Add a signature transaction which triggers chunk via entry header flag"); { - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); auto sig_handle = tx.rw(signatures); auto tree_handle = tx.rw(serialised_tree); @@ -5317,7 +5317,7 @@ TEST_CASE("Ledger entry chunk request") INFO("Add a signature that triggers a snapshot"); { - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); // The store must know that we need a new ledger chunk at this version @@ -5368,12 +5368,12 @@ TEST_CASE("Store version wraps to 0 past INT64_MAX") ccf::kv::ApplyResult::PASS); REQUIRE(kv_store.current_version() == max_signed_version); - const auto wrapped_txid = kv_store.next_txid(); + const auto wrapped_txid = kv_store.next_txid().value(); REQUIRE(wrapped_txid.view == 2); REQUIRE(wrapped_txid.seqno == 0); REQUIRE(kv_store.current_version() == 0); - const auto next_txid = kv_store.next_txid(); + const auto next_txid = kv_store.next_txid().value(); REQUIRE(next_txid.view == 2); REQUIRE(next_txid.seqno == 1); REQUIRE(kv_store.current_version() == 1); @@ -5404,8 +5404,8 @@ TEST_CASE("Store::commit edge cases") store.set_consensus(consensus); store.initialise_term(1); - const auto txid1 = store.next_txid(); - const auto txid2 = store.next_txid(); + const auto txid1 = store.next_txid().value(); + const auto txid2 = store.next_txid().value(); REQUIRE(txid1.seqno == 1); REQUIRE(txid2.seqno == 2); @@ -5438,7 +5438,7 @@ TEST_CASE("Store::commit edge cases") store.set_consensus(consensus); store.initialise_term(1); - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( store.commit( txid, diff --git a/src/kv/test/null_tx_history.h b/src/kv/test/null_tx_history.h index 5d8ee93551e4..d50ebc329351 100644 --- a/src/kv/test/null_tx_history.h +++ b/src/kv/test/null_tx_history.h @@ -116,7 +116,12 @@ namespace ccf void emit_signature() override { - auto txid = store.next_txid(); + auto next_txid = store.next_txid(); + if (!next_txid.has_value()) + { + return; + } + const auto txid = next_txid.value(); LOG_DEBUG_FMT("Issuing signature at {}.{}", txid.view, txid.seqno); store.commit( txid, std::make_unique(txid, store, id), true); diff --git a/src/node/history.h b/src/node/history.h index 2117b61d6820..1306150c609d 100644 --- a/src/node/history.h +++ b/src/node/history.h @@ -807,7 +807,15 @@ namespace ccf std::format("No endorsed certificate set to emit signature")); } - auto txid = store.next_txid(); + // Refused if this node has stopped being primary since the caller + // checked, in which case there is nothing to sign. + auto next_txid = store.next_txid(); + if (!next_txid.has_value()) + { + LOG_DEBUG_FMT("Not signing because local writes are disabled"); + return; + } + const auto txid = next_txid.value(); LOG_DEBUG_FMT("Signed at {} in view: {}", txid.seqno, txid.view); diff --git a/src/node/test/historical_queries.cpp b/src/node/test/historical_queries.cpp index 82b17916c8a5..9b3d32791265 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -1790,7 +1790,7 @@ TEST_CASE("Historical receipts preserve the transaction view across signatures") auto state = create_and_init_state(); auto& store = *state.kv_store; const auto emit_signature = [&]() { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto history = store.get_history(); auto cert = std::make_shared( state.node_kp->self_sign("CN=Test node", valid_from, valid_to)); diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index c80a7d04709f..067d5cfd6043 100644 --- a/src/node/test/history.cpp +++ b/src/node/test/history.cpp @@ -227,7 +227,7 @@ struct SigningFixture std::optional emit_signature( CustomSignaturePendingTx::WriteSignatures write_signatures) { - const auto txid = primary_store.next_txid(); + const auto txid = primary_store.next_txid().value(); primary_store.commit( txid, std::make_unique( @@ -929,7 +929,7 @@ TEST_CASE("Pending signatures retain their endorsed certificate") store.initialise_term(store_term); MapT table("public:table"); - const auto gap_txid = store.next_txid(); + const auto gap_txid = store.next_txid().value(); history->emit_signature(); REQUIRE(consensus->number_of_replicas() == 0); @@ -1109,7 +1109,7 @@ TEST_CASE( INFO("Batch of two, starting with a commitable"); { - auto rv = store.next_txid(); + auto rv = store.next_txid().value(); auto tx = store.create_tx(); auto txv = tx.rw(table); @@ -1262,7 +1262,7 @@ TEST_CASE( REQUIRE(store.current_version() == 2); - auto txid = store.next_txid(); + auto txid = store.next_txid().value(); REQUIRE(txid == ccf::TxID(store_term, 3)); PausedSignatureCommit paused; From aeb9812be9f96149e130892715656d9fd3f15473 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 13:57:33 +0000 Subject: [PATCH 02/10] Discard snapshot receipt material from rolled back signatures A pending snapshot's COSE signatures and serialised tree are now tagged with their source signature index, cleared when rollback truncates past it, and only persisted once that signature is committed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/node/snapshotter.h | 36 ++++++++++++++++++++-- src/node/test/snapshotter.cpp | 56 +++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/src/node/snapshotter.h b/src/node/snapshotter.h index 4d7590d0255e..14bb782ea47a 100644 --- a/src/node/snapshotter.h +++ b/src/node/snapshotter.h @@ -76,6 +76,10 @@ namespace ccf std::optional cose_sigs = std::nullopt; std::optional> tree = std::nullopt; + // Index of the signature that cose_sigs and tree were recorded from. + // They are only valid while that signature is not rolled back, and are + // only used once it is committed. + std::optional<::consensus::Index> receipt_sig_idx = std::nullopt; // Outputs of the serialise action, handed to the persist action. std::shared_ptr serialised; @@ -404,7 +408,10 @@ namespace ccf if ( snapshot_info.evidence_idx.has_value() && idx > snapshot_info.evidence_idx.value() && - snapshot_info.cose_sigs.has_value() && snapshot_info.tree.has_value()) + snapshot_info.cose_sigs.has_value() && + snapshot_info.tree.has_value() && + snapshot_info.receipt_sig_idx.has_value() && + idx >= snapshot_info.receipt_sig_idx.value()) { // Commit evidence is durable. Enqueue the persist action on this // generation's ordered task collection. OrderedTasks guarantees it @@ -569,7 +576,8 @@ namespace ccf if ( pending_snapshot.evidence_idx.has_value() && idx > pending_snapshot.evidence_idx.value() && - !pending_snapshot.cose_sigs.has_value()) + !pending_snapshot.cose_sigs.has_value() && + pending_snapshot.receipt_sig_idx.value_or(idx) == idx) { LOG_TRACE_FMT( "Recording {} COSE signature(s) at {} for snapshot {} with " @@ -580,6 +588,7 @@ namespace ccf pending_snapshot.evidence_idx.value()); pending_snapshot.cose_sigs = cose_sigs; + pending_snapshot.receipt_sig_idx = idx; } } } @@ -594,7 +603,8 @@ namespace ccf if ( pending_snapshot.evidence_idx.has_value() && idx > pending_snapshot.evidence_idx.value() && - !pending_snapshot.tree.has_value()) + !pending_snapshot.tree.has_value() && + pending_snapshot.receipt_sig_idx.value_or(idx) == idx) { LOG_TRACE_FMT( "Recording serialised tree at {} for snapshot {} with evidence at " @@ -604,6 +614,7 @@ namespace ccf pending_snapshot.evidence_idx.value()); pending_snapshot.tree = tree; + pending_snapshot.receipt_sig_idx = idx; } } } @@ -774,6 +785,25 @@ namespace ccf pending_snapshots.erase(last_snapshot); } + + // A remaining snapshot's evidence survives, but the signature its + // receipt was taken from may not. Discard that receipt material, so + // that it is recorded again from the next signature. + for (auto& [_, pending_snapshot] : pending_snapshots) + { + if ( + pending_snapshot.receipt_sig_idx.has_value() && + pending_snapshot.receipt_sig_idx.value() > idx) + { + LOG_TRACE_FMT( + "Discarding receipt from signature at {} for snapshot {}", + pending_snapshot.receipt_sig_idx.value(), + pending_snapshot.version); + pending_snapshot.cose_sigs.reset(); + pending_snapshot.tree.reset(); + pending_snapshot.receipt_sig_idx.reset(); + } + } } }; } diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index 8f22d0088b25..677f540fe458 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -1274,6 +1274,62 @@ TEST_CASE("Rollback before snapshot is committed") } } +TEST_CASE("Rollback discards a snapshot receipt from a rolled back signature") +{ + ccf::NetworkState network; + auto consensus = std::make_shared(); + auto history = std::make_shared( + *network.tables.get(), ccf::kv::test::PrimaryNodeId, *node_kp); + network.tables->set_history(history); + network.tables->initialise_term(2); + network.tables->set_consensus(consensus); + auto encryptor = std::make_shared(); + network.tables->set_encryptor(encryptor); + + ScopedSnapshotDir snapshot_dir; + + size_t snapshot_tx_interval = 10; + issue_transactions(network, snapshot_tx_interval); + + auto snapshotter = std::make_shared( + snapshot_dir.path.string(), network.tables, snapshot_tx_interval); + + const size_t snapshot_idx = snapshot_tx_interval; + const size_t evidence_idx = snapshot_idx + 1; + const size_t receipt_sig_idx = snapshot_idx + 2; + + INFO("Generate snapshot, its evidence, and a signature after it"); + { + REQUIRE(record_signature(history, snapshotter, snapshot_idx)); + snapshotter->commit(snapshot_idx, true); + run_one_task(); + REQUIRE(read_latest_snapshot_evidence(network.tables) == snapshot_idx); + + issue_transactions(network, 1); + record_snapshot_evidence(snapshotter, snapshot_idx, evidence_idx); + REQUIRE_FALSE(record_signature(history, snapshotter, receipt_sig_idx)); + } + + INFO("Roll back the signature, but not the evidence"); + snapshotter->rollback(evidence_idx); + + INFO("The snapshot is not released without a receipt from a new signature"); + { + issue_transactions(network, 1); + snapshotter->commit(receipt_sig_idx + 1, true); + run_one_task(); + REQUIRE_FALSE(latest_committed_snapshot_idx(snapshot_dir.path).has_value()); + } + + INFO("The snapshot is released with a receipt from the new signature"); + { + REQUIRE_FALSE(record_signature(history, snapshotter, receipt_sig_idx + 1)); + snapshotter->commit(receipt_sig_idx + 1, true); + run_one_task(); + REQUIRE(latest_committed_snapshot_idx(snapshot_dir.path) == snapshot_idx); + } +} + TEST_CASE("Failed snapshot evidence commits do not block later snapshots") { ccf::NetworkState network; From 63d7789e35bafa4ed670496cfea527fc71149ae1 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 14:09:38 +0000 Subject: [PATCH 03/10] Discard snapshots whose evidence was rolled back out of generation order Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/node/snapshotter.h | 8 +++++ src/node/test/snapshotter.cpp | 66 +++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/src/node/snapshotter.h b/src/node/snapshotter.h index 14bb782ea47a..536e24a4eab7 100644 --- a/src/node/snapshotter.h +++ b/src/node/snapshotter.h @@ -786,6 +786,14 @@ namespace ccf pending_snapshots.erase(last_snapshot); } + // Evidence transactions from different generations may commit out of + // generation order, so an older snapshot may still have rolled back + // evidence. + std::erase_if(pending_snapshots, [idx](const auto& entry) { + const auto& evidence_idx = entry.second.evidence_idx; + return evidence_idx.has_value() && evidence_idx.value() > idx; + }); + // A remaining snapshot's evidence survives, but the signature its // receipt was taken from may not. Discard that receipt material, so // that it is recorded again from the next signature. diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index 677f540fe458..c63ce592599a 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -1330,6 +1330,72 @@ TEST_CASE("Rollback discards a snapshot receipt from a rolled back signature") } } +TEST_CASE("Rollback discards evidence recorded out of generation order") +{ + ccf::NetworkState network; + auto consensus = std::make_shared(); + auto history = std::make_shared( + *network.tables.get(), ccf::kv::test::PrimaryNodeId, *node_kp); + network.tables->set_history(history); + network.tables->initialise_term(2); + network.tables->set_consensus(consensus); + auto encryptor = std::make_shared(); + network.tables->set_encryptor(encryptor); + + ScopedSnapshotDir snapshot_dir; + + size_t snapshot_tx_interval = 10; + issue_transactions(network, snapshot_tx_interval); + + auto snapshotter = std::make_shared( + snapshot_dir.path.string(), network.tables, snapshot_tx_interval); + + const size_t older_snapshot_idx = snapshot_tx_interval; + const size_t newer_snapshot_idx = 2 * snapshot_tx_interval; + + INFO("Generate two snapshots, neither of which has evidence yet"); + { + REQUIRE(record_signature(history, snapshotter, older_snapshot_idx)); + snapshotter->commit(older_snapshot_idx, true); + run_one_task(); + + issue_transactions(network, newer_snapshot_idx - 1 - older_snapshot_idx); + REQUIRE(record_signature(history, snapshotter, newer_snapshot_idx)); + snapshotter->commit(newer_snapshot_idx, true); + run_one_task(); + } + + INFO("The newer snapshot's evidence is recorded before the older one's"); + const size_t kept_evidence_idx = newer_snapshot_idx + 1; + const size_t rolled_back_evidence_idx = newer_snapshot_idx + 2; + record_snapshot_evidence(snapshotter, newer_snapshot_idx, kept_evidence_idx); + record_snapshot_evidence( + snapshotter, older_snapshot_idx, rolled_back_evidence_idx); + + INFO("Roll back the older snapshot's evidence, but not the newer one's"); + snapshotter->rollback(kept_evidence_idx); + + INFO("Only the snapshot with surviving evidence is released"); + { + issue_transactions(network, 2); + const size_t sig_idx = rolled_back_evidence_idx + 1; + REQUIRE(network.tables->current_version() == sig_idx); + REQUIRE_FALSE(record_signature(history, snapshotter, sig_idx)); + snapshotter->commit(sig_idx, true); + run_one_task(); + run_one_task(); + + REQUIRE( + latest_committed_snapshot_idx(snapshot_dir.path) == newer_snapshot_idx); + for (const auto& entry : fs::directory_iterator(snapshot_dir.path)) + { + CHECK( + ccf::snapshots::get_snapshot_idx_from_file_name( + entry.path().filename()) != older_snapshot_idx); + } + } +} + TEST_CASE("Failed snapshot evidence commits do not block later snapshots") { ccf::NetworkState network; From 2ce8524756ed8204b515146dae74fc1fe7377d22 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 14:09:38 +0000 Subject: [PATCH 04/10] Close remaining gaps in the local write fence commit_reserved refuses once local writes are disabled, a snapshot request without handles is no longer silently dropped, and a turnstile stops local writers starving a demotion waiting for the role lock. The in-flight demotion test now holds the consensus lock before releasing the writer. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- .../aft/test/view_straddling_history.cpp | 30 +++++++++++++++++-- src/kv/committable_tx.h | 16 +++++++++- src/kv/kv_types.h | 2 ++ src/kv/store.h | 13 +++++++- 4 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index 45e8a2d5a8ae..5d596a4614ef 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -134,12 +134,22 @@ TEST_CASE( }); REQUIRE(publish_pause.wait_until_paused()); - INFO("Stepping down cannot complete while A is publishing"); + INFO( + "Consensus starts stepping down, under its lock, but cannot complete " + "while A is publishing"); + const auto view = fixture.cft->get_view(); + std::atomic holds_consensus_lock = false; std::atomic stepped_down = false; std::thread demoter([&]() { - fixture.step_down(); + std::lock_guard guard(fixture.state->lock); + holds_consensus_lock.store(true); + fixture.cft->become_aware_of_new_term(view + 1); stepped_down.store(true); }); + while (!holds_consensus_lock.load()) + { + std::this_thread::yield(); + } std::this_thread::sleep_for(std::chrono::milliseconds(100)); CHECK_FALSE(stepped_down.load()); @@ -169,9 +179,11 @@ TEST_CASE( ccf::ds::to_x509_time_string( std::chrono::system_clock::now() + std::chrono::hours(24)))); - INFO("A transaction starts while the node is primary"); + INFO("A transaction starts, and a TxID is reserved, while primary"); auto stale_tx = fixture.store->create_tx(); stale_tx.rw(fixture.table)->put(1, 1); + const auto reserved_txid = fixture.store->next_txid(); + REQUIRE(reserved_txid.has_value()); fixture.step_down(); const auto baseline_root = fixture.root(); @@ -183,6 +195,14 @@ TEST_CASE( CHECK(fixture.store->current_txid() == baseline_txid); CHECK(fixture.root() == baseline_root); + INFO("A transaction reserved before stepping down cannot write"); + auto reserved_tx = fixture.store->create_reserved_tx(reserved_txid.value()); + reserved_tx.rw(fixture.table)->put(4, 4); + CHECK( + reserved_tx.commit_reserved().success == + ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK_FALSE(read_value(*fixture.store, fixture.table, 4).has_value()); + INFO("Writes are refused, whether started before or after stepping down"); CHECK(stale_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); auto tx = fixture.store->create_tx(); @@ -204,6 +224,10 @@ TEST_CASE( CHECK(snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); CHECK_FALSE(fixture.store->flag_enabled( ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE)); + auto empty_snapshot_tx = fixture.store->create_tx(); + empty_snapshot_tx.set_tx_flag( + ccf::kv::CommittableTx::TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); + CHECK(empty_snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); INFO("Writes are accepted again once the node is re-elected"); fixture.cft->force_become_primary(); diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 2bf358e936f4..8cf89cd3e85c 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -205,7 +205,11 @@ namespace ccf::kv #ifdef CCF_KV_TRACING trace::Commit trace_commit(pimpl->trace_attempt.id); #endif - if (all_changes.empty()) + // A snapshot request without any handle still needs a permit, so it is + // refused rather than silently dropped on a node that will not sign. + if ( + all_changes.empty() && + !tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE)) { committed = true; success = true; @@ -578,6 +582,16 @@ namespace ccf::kv throw std::logic_error("Reserved transaction cannot be empty"); } + // A reserved transaction is committed from inside Store::commit, whose + // permit keeps this stable. Its TxID may have been reserved before a + // step-down, so it must not write the follower's maps. + if (!pimpl->store->local_writes_enabled()) + { + committed = true; + return { + CommitResult::FAIL_NO_REPLICATE, {}, ccf::empty_claims(), {}, {}}; + } + std::vector hooks; bool track_deletes_on_missing_keys = false; diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index 5277d43cee10..ec111ea23e73 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -900,6 +900,8 @@ namespace ccf::kv // Reserves the next TxID, or returns nullopt if this Store does not // currently accept local writes. virtual std::optional next_txid() = 0; + // Only stable while the caller holds a permit. + [[nodiscard]] virtual bool local_writes_enabled() const = 0; virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; diff --git a/src/kv/store.h b/src/kv/store.h index 82786fdef8fd..07f963f00848 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -131,6 +131,12 @@ namespace ccf::kv // version_lock -> history lock. It must never be held across a call into // consensus, nor acquired recursively. ccf::ds::SharedMutex role_rwlock; + // std::shared_mutex may prefer readers, so a steady stream of local + // writers could starve consensus, which waits for role_rwlock while + // holding its own lock. Consensus holds this turnstile while it waits, and + // local writers pass through it, without holding it, before taking + // role_rwlock shared, so they queue behind consensus. + ccf::ds::Mutex role_turnstile; // Only modified under role_rwlock held exclusively. A Store without // consensus accepts local writes; consensus disables them when it binds to // the Store, until it becomes primary. @@ -1032,6 +1038,9 @@ namespace ccf::kv LocalWritePermit acquire_local_write_permit() override { + { + std::lock_guard turnstile(role_turnstile); + } std::shared_lock guard(role_rwlock); const auto writable = can_write_locally.load(); return {std::move(guard), writable}; @@ -1043,17 +1052,19 @@ namespace ccf::kv // speculative local state, which no further local writer can add to. bool disable_local_writes() { + std::lock_guard turnstile(role_turnstile); std::unique_lock guard(role_rwlock); return can_write_locally.exchange(false); } void enable_local_writes() { + std::lock_guard turnstile(role_turnstile); std::unique_lock guard(role_rwlock); can_write_locally.store(true); } - [[nodiscard]] bool local_writes_enabled() const + [[nodiscard]] bool local_writes_enabled() const override { return can_write_locally.load(); } From 456714ce0106b6f9ba7809185b9a53af04d6982e Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 14:18:00 +0000 Subject: [PATCH 05/10] Refuse a snapshot request on a follower before applying the transaction Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/kv/committable_tx.h | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 8cf89cd3e85c..762dfd2b6acc 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -278,6 +278,18 @@ namespace ccf::kv permit = pimpl->store->acquire_local_write_permit(); } + if (snapshot_at_next_signature && !permit.allows_writes()) + { + // A snapshot can only be requested on a node that will emit the next + // signature. A transaction which writes is refused anyway, when it is + // allocated a version. + LOG_TRACE_FMT( + "Could not request a snapshot because this node does not accept " + "local writes"); + KV_TRACE(trace_commit.result("no_replicate", 0)); + return CommitResult::FAIL_NO_REPLICATE; + } + { MapSetLockGuard map_set_guard(*pimpl->store, maps_created); #ifdef CCF_KV_TRACING @@ -324,19 +336,6 @@ namespace ccf::kv return CommitResult::FAIL_CONFLICT; } - if ( - c.value() == NoVersion && snapshot_at_next_signature && - !permit.allows_writes()) - { - // A snapshot can only be requested on a node that will emit the next - // signature. - LOG_TRACE_FMT( - "Could not request a snapshot because this node does not accept " - "local writes"); - KV_TRACE(trace_commit.result("no_replicate", 0)); - return CommitResult::FAIL_NO_REPLICATE; - } - committed = true; version = c.value(); @@ -582,9 +581,11 @@ namespace ccf::kv throw std::logic_error("Reserved transaction cannot be empty"); } - // A reserved transaction is committed from inside Store::commit, whose - // permit keeps this stable. Its TxID may have been reserved before a - // step-down, so it must not write the follower's maps. + // A reserved transaction must be committed from inside Store::commit, + // whose permit keeps this stable and whose view check rejects a TxID + // reserved in an earlier term before this is called. Its TxID may have + // been reserved before a step-down, so it must not write the follower's + // maps. if (!pimpl->store->local_writes_enabled()) { committed = true; From a34dc9302bed0ac7dacf0ebd1f37fa8197ecad08 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 15:28:42 +0000 Subject: [PATCH 06/10] Restore the empty transaction fast path A snapshot request with no handles is never made in practice, and changing how it behaves is unrelated to fencing local writes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/consensus/aft/test/view_straddling_history.cpp | 4 ---- src/kv/committable_tx.h | 6 +----- 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index 5d596a4614ef..fc615c41a7f5 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -224,10 +224,6 @@ TEST_CASE( CHECK(snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); CHECK_FALSE(fixture.store->flag_enabled( ccf::kv::AbstractStore::StoreFlag::SNAPSHOT_AT_NEXT_SIGNATURE)); - auto empty_snapshot_tx = fixture.store->create_tx(); - empty_snapshot_tx.set_tx_flag( - ccf::kv::CommittableTx::TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE); - CHECK(empty_snapshot_tx.commit() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); INFO("Writes are accepted again once the node is re-elected"); fixture.cft->force_become_primary(); diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 762dfd2b6acc..99ecff04c712 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -205,11 +205,7 @@ namespace ccf::kv #ifdef CCF_KV_TRACING trace::Commit trace_commit(pimpl->trace_attempt.id); #endif - // A snapshot request without any handle still needs a permit, so it is - // refused rather than silently dropped on a node that will not sign. - if ( - all_changes.empty() && - !tx_flag_enabled(TxFlag::SNAPSHOT_AT_NEXT_SIGNATURE)) + if (all_changes.empty()) { committed = true; success = true; From 3e149e6710424c09fe244a622939650ddc88b005 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 15:28:42 +0000 Subject: [PATCH 07/10] Replace the role turnstile with an atomic pending flag Local writers now check one atomic, rather than locking a global mutex, on every write. A writer which sees a pending role change is refused without taking role_rwlock, so consensus still only waits for writers already in flight. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/kv/store.h | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/kv/store.h b/src/kv/store.h index 07f963f00848..994a3f1ce572 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -132,11 +132,12 @@ namespace ccf::kv // consensus, nor acquired recursively. ccf::ds::SharedMutex role_rwlock; // std::shared_mutex may prefer readers, so a steady stream of local - // writers could starve consensus, which waits for role_rwlock while - // holding its own lock. Consensus holds this turnstile while it waits, and - // local writers pass through it, without holding it, before taking - // role_rwlock shared, so they queue behind consensus. - ccf::ds::Mutex role_turnstile; + // writers could starve consensus, which waits for role_rwlock exclusively + // while holding its own lock. Consensus sets this before it waits, and + // local writers which see it are refused without taking role_rwlock, so + // consensus only waits for writers already in flight. Only set by + // consensus, under its own lock. + std::atomic role_change_pending = false; // Only modified under role_rwlock held exclusively. A Store without // consensus accepts local writes; consensus disables them when it binds to // the Store, until it becomes primary. @@ -1038,8 +1039,9 @@ namespace ccf::kv LocalWritePermit acquire_local_write_permit() override { + if (role_change_pending.load()) { - std::lock_guard turnstile(role_turnstile); + return {}; } std::shared_lock guard(role_rwlock); const auto writable = can_write_locally.load(); @@ -1052,15 +1054,17 @@ namespace ccf::kv // speculative local state, which no further local writer can add to. bool disable_local_writes() { - std::lock_guard turnstile(role_turnstile); + role_change_pending.store(true); std::unique_lock guard(role_rwlock); + role_change_pending.store(false); return can_write_locally.exchange(false); } void enable_local_writes() { - std::lock_guard turnstile(role_turnstile); + role_change_pending.store(true); std::unique_lock guard(role_rwlock); + role_change_pending.store(false); can_write_locally.store(true); } From 651730a899206db2d10864fb19ee7c9cdc959420 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 15:49:42 +0000 Subject: [PATCH 08/10] Move the role lock into consensus Aft now owns the role lock and whether local writes are accepted, and derives the latter from its leadership state through a single helper, instead of enabling and disabling the Store's writes ad hoc. The Store forwards permit requests to its consensus, and accepts local writes without one. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/consensus/aft/cft.h | 105 +++++++++++++++++++------- src/consensus/aft/cft_types.h | 24 ------ src/consensus/aft/test/logging_stub.h | 12 --- src/kv/kv_types.h | 103 ++++++++++++++----------- src/kv/store.h | 58 ++------------ 5 files changed, 145 insertions(+), 157 deletions(-) diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 3f457ef9df9a..5512f7ad24a4 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -20,11 +20,13 @@ #include "tasks/periodic_task_owner.h" #include +#include #include #include #include #include #include +#include #include #include #include @@ -174,6 +176,24 @@ namespace aft // once, and must later be updated by rollback. bool store_term_initialised = false; + // Fences local writers (CommittableTx::commit(), Store::next_txid() and + // Store::commit()) against this node's role changing. Local writers hold + // it shared, through a permit, while they apply and publish writes to the + // KV and the history. update_local_writes() takes it exclusively, under + // state->lock. Lock order: commit_lock -> state->lock -> role_rwlock -> + // maps_lock -> version_lock -> history lock. It must never be held across + // a call into consensus, nor acquired recursively. + ccf::ds::SharedMutex role_rwlock; + // std::shared_mutex may prefer readers, so a steady stream of local + // writers could starve update_local_writes(), which waits for role_rwlock + // while holding state->lock. It sets this before it waits, and local + // writers which see it are refused without taking role_rwlock, so it only + // waits for writers already in flight. + std::atomic role_change_pending = false; + // Whether local writes are accepted. Only modified by + // update_local_writes(), with role_rwlock held exclusively. + std::atomic local_writes_open = false; + // Randomness std::uniform_int_distribution distrib; std::default_random_engine rand; @@ -217,12 +237,7 @@ namespace aft ledger(std::move(ledger_)), channels(std::move(channels_)) - { - // Only a primary accepts local writes. The Store may already hold - // state, from a snapshot or a recovered ledger, which must not be - // rolled back here. - store->disable_local_writes(); - } + {} ~Aft() override = default; @@ -332,6 +347,22 @@ namespace aft } } + ccf::kv::LocalWritePermit acquire_local_write_permit() override + { + if (role_change_pending.load()) + { + return {}; + } + std::shared_lock guard(role_rwlock); + const auto writable = local_writes_open.load(); + return {std::move(guard), writable}; + } + + bool local_writes_enabled() override + { + return local_writes_open.load(); + } + void set_retired_committed( ccf::SeqNo seqno, const std::vector& node_ids) override { @@ -2081,19 +2112,43 @@ namespace aft } } - // Stops the Store accepting local writes, once local writers that may - // still publish have finished. If it was accepting them, discards the - // speculative local state they wrote beyond last_idx, which no further - // local writer can add to. Must be called with state->lock held, and not - // under any Store lock. - void close_local_writes() + // Only a primary whose retirement is not complete accepts local writes. + // Brings local_writes_open in line with that, waiting for local writers + // in flight to finish. When local writes stop, discards the speculative + // local state they wrote beyond last_idx, which no further local writer + // can add to. Must be called with state->lock held, and not under any + // Store lock. + void update_local_writes() { - if (store->disable_local_writes()) + const auto writable = + state->leadership_state.load() == ccf::kv::LeadershipState::Leader && + !is_retired_committed(); + if (writable == local_writes_open.load()) + { + return; + } + + role_change_pending.store(true); + { + std::unique_lock guard(role_rwlock); + local_writes_open.store(writable); + } + role_change_pending.store(false); + + if (!writable) { rollback(state->last_idx); } } + // Every change of leadership state, except completing retirement (see + // commit()), goes through here, so that local writes follow it. + void set_leadership_state(ccf::kv::LeadershipState leadership_state) + { + state->leadership_state.store(leadership_state); + update_local_writes(); + } + void become_pre_vote_candidate() { if (configurations.empty()) @@ -2106,9 +2161,8 @@ namespace aft trace::tick(*state); - state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate); + set_leadership_state(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); - close_local_writes(); reset_votes_for_me(); restart_election_timeout(); @@ -2145,13 +2199,14 @@ namespace aft return; } - state->leadership_state.store(ccf::kv::LeadershipState::Candidate); + // The view moves on first, so that discarding local state on the way + // moves the Store to the new view too. + state->current_view++; + set_leadership_state(ccf::kv::LeadershipState::Candidate); leader_id.reset(); voted_for = state->node_id; reset_votes_for_me(); - state->current_view++; - close_local_writes(); restart_election_timeout(); reset_last_ack_timeouts(); @@ -2204,13 +2259,11 @@ namespace aft rollback(state->last_idx); } - state->leadership_state.store(ccf::kv::LeadershipState::Leader); leader_id = state->node_id; should_sign = true; - // The KV is now in this term, and holds no speculative state from an // earlier one, so local writes can start. - store->enable_local_writes(); + set_leadership_state(ccf::kv::LeadershipState::Leader); using namespace std::chrono_literals; timeout_elapsed = 0ms; @@ -2252,8 +2305,7 @@ namespace aft restart_election_timeout(); reset_last_ack_timeouts(); - state->leadership_state.store(ccf::kv::LeadershipState::Follower); - close_local_writes(); + set_leadership_state(ccf::kv::LeadershipState::Follower); CFT_INFO_FMT( "Becoming follower {}: {}.{}", state->node_id, @@ -2372,6 +2424,8 @@ namespace aft nominate_successor_unsafe(); leader_id.reset(); + // This runs under the Store's locks, from compaction, so it must not + // wait for local writers. commit() stops them once compaction is done. state->leadership_state.store(ccf::kv::LeadershipState::None); } @@ -2647,10 +2701,7 @@ namespace aft // Compaction may have run the hook that completes this node's // retirement, which cannot itself stop local writes because it runs // under the Store's locks. - if (is_retired_committed()) - { - close_local_writes(); - } + update_local_writes(); ledger->commit(idx); if (commit_observer != nullptr) diff --git a/src/consensus/aft/cft_types.h b/src/consensus/aft/cft_types.h index 602d02416d17..f55092a3be27 100644 --- a/src/consensus/aft/cft_types.h +++ b/src/consensus/aft/cft_types.h @@ -29,11 +29,6 @@ namespace aft virtual void rollback( const ccf::TxID& tx_id, Term term_of_next_version) = 0; virtual void initialise_term(Term t) = 0; - // Stops accepting local writes, waiting for local writers that may still - // publish to finish. Returns true if local writes were accepted until now, - // in which case the caller must discard any speculative local state. - virtual bool disable_local_writes() = 0; - virtual void enable_local_writes() = 0; virtual std::unique_ptr deserialize( std::vector data, bool public_only = false, @@ -76,25 +71,6 @@ namespace aft } } - bool disable_local_writes() override - { - auto p = x.lock(); - if (p) - { - return p->disable_local_writes(); - } - return false; - } - - void enable_local_writes() override - { - auto p = x.lock(); - if (p) - { - p->enable_local_writes(); - } - } - std::unique_ptr deserialize( const std::vector data, bool public_only = false, diff --git a/src/consensus/aft/test/logging_stub.h b/src/consensus/aft/test/logging_stub.h index 96d23a367460..a47b42f92f73 100644 --- a/src/consensus/aft/test/logging_stub.h +++ b/src/consensus/aft/test/logging_stub.h @@ -370,18 +370,6 @@ namespace aft virtual void initialise_term(Term t) {} - bool local_writes_enabled = true; - - virtual bool disable_local_writes() - { - return std::exchange(local_writes_enabled, false); - } - - virtual void enable_local_writes() - { - local_writes_enabled = true; - } - ccf::kv::Version current_version() { return ccf::kv::NoVersion; diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index ec111ea23e73..d341161226b4 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -463,6 +463,47 @@ namespace ccf::kv virtual const ccf::COSESignaturesConfig& get_cose_signatures_config() = 0; }; + // A shared hold on consensus's role lock. While it is held, consensus cannot + // switch between accepting and refusing local writes, so a local writer can + // apply and publish its writes without a concurrent demotion discarding them + // underneath it. A permit from consensus which does not fence local writes + // allows them without holding any lock. + class LocalWritePermit + { + private: + std::shared_lock guard; + bool writable = false; + + public: + LocalWritePermit() = default; + + LocalWritePermit( + std::shared_lock&& guard_, bool writable_) : + guard(std::move(guard_)), + writable(writable_) + {} + + LocalWritePermit(LocalWritePermit&&) = default; + LocalWritePermit& operator=(LocalWritePermit&&) = default; + LocalWritePermit(const LocalWritePermit&) = delete; + LocalWritePermit& operator=(const LocalWritePermit&) = delete; + ~LocalWritePermit() = default; + + [[nodiscard]] bool allows_writes() const + { + return writable; + } + + void release() + { + writable = false; + if (guard.owns_lock()) + { + guard.unlock(); + } + } + }; + class Consensus : public ConfigurableConsensus { public: @@ -530,6 +571,21 @@ namespace ccf::kv virtual void nominate_successor() {} + // Acquires the role lock shared, if this fences local writes against + // changes of role. A local writer holds the returned permit from before it + // applies its writes until it has published them to the history, and must + // neither acquire another permit nor call into consensus while holding it. + virtual LocalWritePermit acquire_local_write_permit() + { + return {std::shared_lock{}, true}; + } + + // Only stable while the caller holds a permit. + virtual bool local_writes_enabled() + { + return true; + } + ccf::TxStatus evaluate_tx_status( ccf::View target_view, ccf::SeqNo target_seqno) { @@ -832,46 +888,6 @@ namespace ccf::kv consume_commit_evidence_digest() = 0; }; - // A shared hold on a Store's role lock. While it is held, the Store cannot - // switch between accepting and refusing local writes, so a local writer can - // apply and publish its writes without a concurrent demotion discarding them - // underneath it. - class LocalWritePermit - { - private: - std::shared_lock guard; - bool writable = false; - - public: - LocalWritePermit() = default; - - LocalWritePermit( - std::shared_lock&& guard_, bool writable_) : - guard(std::move(guard_)), - writable(writable_) - {} - - LocalWritePermit(LocalWritePermit&&) = default; - LocalWritePermit& operator=(LocalWritePermit&&) = default; - LocalWritePermit(const LocalWritePermit&) = delete; - LocalWritePermit& operator=(const LocalWritePermit&) = delete; - ~LocalWritePermit() = default; - - [[nodiscard]] bool allows_writes() const - { - return guard.owns_lock() && writable; - } - - void release() - { - writable = false; - if (guard.owns_lock()) - { - guard.unlock(); - } - } - }; - class AbstractStore { public: @@ -889,9 +905,8 @@ namespace ccf::kv virtual void lock_map_set() = 0; virtual void unlock_map_set() = 0; - // Acquires the role lock shared. A local writer holds the returned permit - // from before it applies its writes until it has applied any Store flags, - // and must not acquire another permit while holding it. + // Acquires a permit from consensus, see Consensus. A Store without + // consensus accepts local writes. virtual LocalWritePermit acquire_local_write_permit() = 0; // Returns nullopt if the permit does not allow local writes, or if the // commit term has moved on from expected_commit_term. @@ -901,7 +916,7 @@ namespace ccf::kv // currently accept local writes. virtual std::optional next_txid() = 0; // Only stable while the caller holds a permit. - [[nodiscard]] virtual bool local_writes_enabled() const = 0; + [[nodiscard]] virtual bool local_writes_enabled() = 0; virtual Version current_version() = 0; virtual ccf::TxID current_txid() = 0; diff --git a/src/kv/store.h b/src/kv/store.h index 994a3f1ce572..eb000d1cffd8 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -121,28 +121,6 @@ namespace ccf::kv std::atomic readiness = StoreReadiness::Ready; - // Fences local writers (CommittableTx::commit(), next_txid() and - // Store::commit()) against consensus changing this node's role. Local - // writers hold it shared while they apply and publish writes, to the KV - // and the ledger history. Consensus takes it exclusively, under its own - // lock, to stop accepting local writes when this node stops being primary, - // and to start accepting them again when it becomes primary. Lock order: - // commit_lock -> consensus lock -> role_rwlock -> maps_lock -> - // version_lock -> history lock. It must never be held across a call into - // consensus, nor acquired recursively. - ccf::ds::SharedMutex role_rwlock; - // std::shared_mutex may prefer readers, so a steady stream of local - // writers could starve consensus, which waits for role_rwlock exclusively - // while holding its own lock. Consensus sets this before it waits, and - // local writers which see it are refused without taking role_rwlock, so - // consensus only waits for writers already in flight. Only set by - // consensus, under its own lock. - std::atomic role_change_pending = false; - // Only modified under role_rwlock held exclusively. A Store without - // consensus accepts local writes; consensus disables them when it binds to - // the Store, until it becomes primary. - std::atomic can_write_locally = true; - // Holds the lock of every map in a collection for its lifetime, releasing // them on every exit path. The collection must not change while held. class ScopedMapLocks @@ -1039,38 +1017,18 @@ namespace ccf::kv LocalWritePermit acquire_local_write_permit() override { - if (role_change_pending.load()) + auto c = get_consensus(); + if (c == nullptr) { - return {}; + return {std::shared_lock{}, true}; } - std::shared_lock guard(role_rwlock); - const auto writable = can_write_locally.load(); - return {std::move(guard), writable}; - } - - // Stops accepting local writes, waiting for any local writer currently - // holding a permit to finish publishing. Returns true if local writes were - // accepted until now, in which case the caller must discard any - // speculative local state, which no further local writer can add to. - bool disable_local_writes() - { - role_change_pending.store(true); - std::unique_lock guard(role_rwlock); - role_change_pending.store(false); - return can_write_locally.exchange(false); + return c->acquire_local_write_permit(); } - void enable_local_writes() + [[nodiscard]] bool local_writes_enabled() override { - role_change_pending.store(true); - std::unique_lock guard(role_rwlock); - role_change_pending.store(false); - can_write_locally.store(true); - } - - [[nodiscard]] bool local_writes_enabled() const override - { - return can_write_locally.load(); + auto c = get_consensus(); + return c == nullptr || c->local_writes_enabled(); } void initialise_term(Term t) override @@ -1245,7 +1203,7 @@ namespace ccf::kv // Held from admission until the batch is published to the history and // chunker, so that consensus cannot discard local state between this // check and publication. It is released before calling consensus. - auto permit = acquire_local_write_permit(); + auto permit = c->acquire_local_write_permit(); if (!permit.allows_writes()) { LOG_DEBUG_FMT( From 3e0ca3e211d214927be6afd0e097e7daa900f214 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 15:56:36 +0000 Subject: [PATCH 09/10] Make a local write permit own its lock safely A moved-from permit no longer allows writes, and a permit keeps the consensus whose lock it holds alive until it releases it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/kv/kv_types.h | 28 ++++++++++++++++++++++++++-- src/kv/store.h | 4 +++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index d341161226b4..a214cafeb8dd 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -44,6 +44,7 @@ #include #include #include +#include #include namespace ccf @@ -471,6 +472,8 @@ namespace ccf::kv class LocalWritePermit { private: + // Keeps the owner of the lock alive until the guard has released it. + std::shared_ptr owner; std::shared_lock guard; bool writable = false; @@ -483,12 +486,33 @@ namespace ccf::kv writable(writable_) {} - LocalWritePermit(LocalWritePermit&&) = default; - LocalWritePermit& operator=(LocalWritePermit&&) = default; + LocalWritePermit(LocalWritePermit&& other) noexcept : + owner(std::move(other.owner)), + guard(std::move(other.guard)), + writable(std::exchange(other.writable, false)) + {} + + LocalWritePermit& operator=(LocalWritePermit&& other) noexcept + { + if (this != &other) + { + release(); + guard = std::move(other.guard); + owner = std::move(other.owner); + writable = std::exchange(other.writable, false); + } + return *this; + } + LocalWritePermit(const LocalWritePermit&) = delete; LocalWritePermit& operator=(const LocalWritePermit&) = delete; ~LocalWritePermit() = default; + void set_owner(std::shared_ptr owner_) + { + owner = std::move(owner_); + } + [[nodiscard]] bool allows_writes() const { return writable; diff --git a/src/kv/store.h b/src/kv/store.h index eb000d1cffd8..f92508aa6bae 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1022,7 +1022,9 @@ namespace ccf::kv { return {std::shared_lock{}, true}; } - return c->acquire_local_write_permit(); + auto permit = c->acquire_local_write_permit(); + permit.set_owner(c); + return permit; } [[nodiscard]] bool local_writes_enabled() override From 7a85e5f1841a0504af41d78c090eef29812473b4 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 2 Dec 2026 16:32:37 +0000 Subject: [PATCH 10/10] Clarify the local write fence comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 70f21073859b499a96d2c66cab082118 --- src/consensus/aft/cft.h | 42 +++++++++++-------- .../aft/test/view_straddling_common.h | 8 ++-- .../aft/test/view_straddling_history.cpp | 14 ++++--- src/kv/committable_tx.h | 4 +- src/kv/kv_types.h | 19 +++++---- src/kv/store.h | 6 ++- src/node/history.h | 4 +- 7 files changed, 57 insertions(+), 40 deletions(-) diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 5512f7ad24a4..586ffd0b9e6e 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -178,17 +178,18 @@ namespace aft // Fences local writers (CommittableTx::commit(), Store::next_txid() and // Store::commit()) against this node's role changing. Local writers hold - // it shared, through a permit, while they apply and publish writes to the - // KV and the history. update_local_writes() takes it exclusively, under - // state->lock. Lock order: commit_lock -> state->lock -> role_rwlock -> - // maps_lock -> version_lock -> history lock. It must never be held across - // a call into consensus, nor acquired recursively. + // it shared, through a permit, while they apply writes to the KV, and + // again, through a separate permit, while they publish them to the history. + // update_local_writes() takes it exclusively, under state->lock. Lock + // order: commit_lock -> state->lock -> role_rwlock -> maps_lock -> + // version_lock -> history lock. It must never be held across a call that + // takes state->lock, such as replicate(), nor acquired recursively. ccf::ds::SharedMutex role_rwlock; // std::shared_mutex may prefer readers, so a steady stream of local // writers could starve update_local_writes(), which waits for role_rwlock // while holding state->lock. It sets this before it waits, and local // writers which see it are refused without taking role_rwlock, so it only - // waits for writers already in flight. + // waits for writers which checked the flag before it was set. std::atomic role_change_pending = false; // Whether local writes are accepted. Only modified by // update_local_writes(), with role_rwlock held exclusively. @@ -704,8 +705,10 @@ namespace aft if (state->leadership_state.load() != ccf::kv::LeadershipState::Leader) { - // Local writes were disabled, and the speculative local state these + // Local writes were closed, and the speculative local state these // entries belong to discarded, when this node stopped being leader. + // Entries from before a later re-election are refused by the term + // check below, as every candidacy increments the view. CFT_DEBUG_FMT( "Failed to replicate {} items: not leader", entries.size()); return false; @@ -2114,10 +2117,11 @@ namespace aft // Only a primary whose retirement is not complete accepts local writes. // Brings local_writes_open in line with that, waiting for local writers - // in flight to finish. When local writes stop, discards the speculative - // local state they wrote beyond last_idx, which no further local writer - // can add to. Must be called with state->lock held, and not under any - // Store lock. + // holding a permit to release it. When local writes stop, discards the + // speculative local state they wrote beyond last_idx (the end of Aft's + // log, committed or not), which no further + // local writer can add to. Must be called with state->lock held, and not + // under any Store lock other than commit_lock. void update_local_writes() { const auto writable = @@ -2141,8 +2145,11 @@ namespace aft } } - // Every change of leadership state, except completing retirement (see - // commit()), goes through here, so that local writes follow it. + // Every change of leadership state goes through here, so that local + // writes follow it. The one exception is completing retirement, which + // runs under the Store's locks, and so is followed up by Aft's commit(). + // Any other transition made under the Store's locks must likewise leave + // calling update_local_writes() until those locks are released. void set_leadership_state(ccf::kv::LeadershipState leadership_state) { state->leadership_state.store(leadership_state); @@ -2199,8 +2206,8 @@ namespace aft return; } - // The view moves on first, so that discarding local state on the way - // moves the Store to the new view too. + // The view moves on first, so that if this closes local writes, + // discarding local state moves the Store to the new view too. state->current_view++; set_leadership_state(ccf::kv::LeadershipState::Candidate); leader_id.reset(); @@ -2255,7 +2262,7 @@ namespace aft else { // The KV's term was already set, by an earlier election or rollback, - // so update it without discarding anything. + // so this only updates its term; nothing is past last_idx to discard. rollback(state->last_idx); } @@ -2700,7 +2707,8 @@ namespace aft store->compact(idx); // Compaction may have run the hook that completes this node's // retirement, which cannot itself stop local writes because it runs - // under the Store's locks. + // under the Store's locks. state->lock is still held, so nothing + // published since can have been replicated, and this discards it. update_local_writes(); ledger->commit(idx); diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index 3d9ef69d3acd..33c7473cb754 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -130,8 +130,8 @@ namespace straddling // Behaves like ccf::kv::MovePendingTx, the PendingTx of every normal // transaction: hands over an already-serialised entry and cannot fail. If - // given a pause, it pauses first, while Store::commit() holds the Store's - // role lock shared, modelling the committing thread being descheduled + // given a pause, it pauses first, while Store::commit() holds the role lock + // shared, modelling the committing thread being descheduled // while it publishes the entry. class ReadyPendingTx : public ccf::kv::PendingTx { @@ -157,8 +157,8 @@ namespace straddling // Pauses the next call to replicate() once armed, before it takes CFT's // lock. This models the committing thread being descheduled after - // Store::commit() has published the entry locally and released the - // Store's locks, but before it reaches CFT. In production this is the + // Store::commit() has published the entry locally and released the role + // lock, but before it reaches CFT. In production this is the // thread blocking on aft::State::lock while an election holds it. class PausingCft : public aft::Aft { diff --git a/src/consensus/aft/test/view_straddling_history.cpp b/src/consensus/aft/test/view_straddling_history.cpp index fc615c41a7f5..381c6e68558d 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -9,15 +9,17 @@ // matching, and the follower would reject valid entries. // // Store::commit() publishes a local transaction to the history while it -// holds the Store's role lock shared, and CFT discards everything published -// after its last index once it has taken that lock exclusively, when the -// node stops being primary. A local writer therefore either finishes -// publishing before the node steps down, and is discarded, or is refused. +// holds the role lock shared, and CFT discards everything published after +// its last index once it has taken that lock exclusively, when the node +// stops being primary. A local writer which CFT has not yet accepted +// therefore either finishes publishing before CFT takes the lock, and is +// discarded and then refused by replicate(), or is refused before it +// publishes. // // Interleaving, from PR #8223: // -// - Tx A is published locally by Store::commit(), which then releases its -// locks before calling CFT. +// - Tx A is published locally by Store::commit(), which then releases the +// role lock before calling CFT. // - An election rolls the Store and the ledger history back to seqno 1. // - CFT rejects A, which must not reappear in the history. diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 99ecff04c712..a5b34e9c9319 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -266,8 +266,8 @@ namespace ccf::kv // Held from before any write is applied until the Store flags have been // applied, so that consensus cannot discard local state in between. - // Read-only transactions that set no Store flag do not need it, and can - // commit on any node. + // Read-only transactions that do not request a snapshot do not need it, + // and can commit on any node. LocalWritePermit permit; if (has_writes() || snapshot_at_next_signature) { diff --git a/src/kv/kv_types.h b/src/kv/kv_types.h index a214cafeb8dd..4f08ed763cb0 100644 --- a/src/kv/kv_types.h +++ b/src/kv/kv_types.h @@ -466,9 +466,11 @@ namespace ccf::kv // A shared hold on consensus's role lock. While it is held, consensus cannot // switch between accepting and refusing local writes, so a local writer can - // apply and publish its writes without a concurrent demotion discarding them - // underneath it. A permit from consensus which does not fence local writes - // allows them without holding any lock. + // apply, or publish, its writes without a concurrent demotion discarding them + // underneath it. Writers must check allows_writes(); a refused commit returns + // CommitResult::FAIL_NO_REPLICATE. A permit from + // consensus which does not fence local writes allows them without holding + // any lock. class LocalWritePermit { private: @@ -596,9 +598,12 @@ namespace ccf::kv virtual void nominate_successor() {} // Acquires the role lock shared, if this fences local writes against - // changes of role. A local writer holds the returned permit from before it - // applies its writes until it has published them to the history, and must - // neither acquire another permit nor call into consensus while holding it. + // changes of role. A local writer holds a permit while it applies its + // writes, and Store::commit() holds another while it publishes them to the + // history, so the writer must release its own first. A holder must neither + // acquire another permit, including through next_txid() or + // Store::commit(), nor call into consensus in a way that takes its + // lock, such as replicate(), or it may deadlock with a role change. virtual LocalWritePermit acquire_local_write_permit() { return {std::shared_lock{}, true}; @@ -930,7 +935,7 @@ namespace ccf::kv virtual void unlock_map_set() = 0; // Acquires a permit from consensus, see Consensus. A Store without - // consensus accepts local writes. + // consensus returns one which allows local writes without holding a lock. virtual LocalWritePermit acquire_local_write_permit() = 0; // Returns nullopt if the permit does not allow local writes, or if the // commit term has moved on from expected_commit_term. diff --git a/src/kv/store.h b/src/kv/store.h index f92508aa6bae..6dd9a53839ec 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1370,8 +1370,10 @@ namespace ccf::kv } // Consensus takes the role lock exclusively under its own lock, so this - // must not be held while calling into it. If this node stops being - // primary from here on, consensus refuses the batch and discards it. + // must not be held across a call which takes that lock. If this node + // stops being primary before replicate() runs, consensus discards the + // batch as it does so, and refuses it here, or by its old term if it has + // since been re-elected. permit.release(); if (c->replicate(batch, replication_view)) diff --git a/src/node/history.h b/src/node/history.h index 1306150c609d..52124d9d6f66 100644 --- a/src/node/history.h +++ b/src/node/history.h @@ -807,8 +807,8 @@ namespace ccf std::format("No endorsed certificate set to emit signature")); } - // Refused if this node has stopped being primary since the caller - // checked, in which case there is nothing to sign. + // Refused if this node has stopped being primary, or completed + // retirement, since the caller checked, so do not sign. auto next_txid = store.next_txid(); if (!next_txid.has_value()) {