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 00000000000..c16c9fd4b9b --- /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 2f141212cc5..586ffd0b9e6 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 @@ -170,6 +172,29 @@ 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; + + // 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 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 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. + std::atomic local_writes_open = false; + // Randomness std::uniform_int_distribution distrib; std::default_random_engine rand; @@ -323,6 +348,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 { @@ -664,9 +705,12 @@ namespace aft if (state->leadership_state.load() != ccf::kv::LeadershipState::Leader) { + // 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()); - rollback(state->last_idx); return false; } @@ -685,7 +729,6 @@ namespace aft CFT_DEBUG_FMT( "Failed to replicate {} items: node retirement is complete", entries.size()); - rollback(state->last_idx); return false; } @@ -2072,6 +2115,47 @@ 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 + // 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 = + 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 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); + update_local_writes(); + } + void become_pre_vote_candidate() { if (configurations.empty()) @@ -2084,7 +2168,7 @@ namespace aft trace::tick(*state); - state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate); + set_leadership_state(ccf::kv::LeadershipState::PreVoteCandidate); leader_id.reset(); reset_votes_for_me(); @@ -2122,12 +2206,14 @@ namespace aft return; } - state->leadership_state.store(ccf::kv::LeadershipState::Candidate); + // 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(); voted_for = state->node_id; reset_votes_for_me(); - state->current_view++; restart_election_timeout(); reset_last_ack_timeouts(); @@ -2167,15 +2253,24 @@ 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 this only updates its term; nothing is past last_idx to discard. + 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. + set_leadership_state(ccf::kv::LeadershipState::Leader); using namespace std::chrono_literals; timeout_elapsed = 0ms; @@ -2217,7 +2312,7 @@ namespace aft restart_election_timeout(); reset_last_ack_timeouts(); - state->leadership_state.store(ccf::kv::LeadershipState::Follower); + set_leadership_state(ccf::kv::LeadershipState::Follower); CFT_INFO_FMT( "Becoming follower {}: {}.{}", state->node_id, @@ -2336,6 +2431,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); } @@ -2608,6 +2705,11 @@ 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. state->lock is still held, so nothing + // published since can have been replicated, and this discards it. + update_local_writes(); ledger->commit(idx); if (commit_observer != nullptr) @@ -2690,6 +2792,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/test/main.cpp b/src/consensus/aft/test/main.cpp index 7ad54e2dfaa..d38be3e6437 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -3496,7 +3496,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.wo(signatures)->put(ccf::PrimarySignature(primary_id, txid.seqno)); tx.wo(serialised_tree)->put({}); diff --git a/src/consensus/aft/test/view_straddling_common.h b/src/consensus/aft/test/view_straddling_common.h index 8b4e647a4dd..00f4ff2ab4e 100644 --- a/src/consensus/aft/test/view_straddling_common.h +++ b/src/consensus/aft/test/view_straddling_common.h @@ -11,6 +11,7 @@ #include "service/tables/signatures.h" #include "test_common.h" +#include #include #include #include @@ -22,7 +23,6 @@ namespace straddling { using TestMap = ccf::kv::Map; - using Cft = aft::Aft; class SignaturePendingTx : public ccf::kv::PendingTx { @@ -135,29 +135,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 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 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 + { + 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) { @@ -182,6 +215,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; @@ -194,27 +228,14 @@ namespace straddling // history before CFT is created and the baseline is committed. void start() { - cft = std::make_shared( - cft_settings, - std::make_unique>(store), - std::make_unique(node_id), - std::make_shared(), - std::make_shared(node_id), - nullptr); - store->set_consensus(cft); - - ccf::kv::Configuration::Nodes configuration; - configuration.try_emplace(node_id); - cft->add_configuration(0, configuration); - cft->force_become_primary(); - initial_view = cft->get_view(); + start_consensus(); { auto tx = store->create_tx(); tx.rw(table)->put(0, 1); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto baseline_txid = store->next_txid(); + const auto baseline_txid = store->next_txid().value(); REQUIRE( store->commit( baseline_txid, @@ -225,11 +246,37 @@ namespace straddling REQUIRE(cft->ledger->ledger.size() == 2); } + // 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(), + state, + nullptr); + store->set_consensus(cft); + + ccf::kv::Configuration::Nodes configuration; + configuration.try_emplace(node_id); + cft->add_configuration(0, configuration); + cft->force_become_primary(); + initial_view = cft->get_view(); + } + + // 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 (2) 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 60c35474bb9..9de314bea26 100644 --- a/src/consensus/aft/test/view_straddling_history.cpp +++ b/src/consensus/aft/test/view_straddling_history.cpp @@ -1,23 +1,27 @@ // 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 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 passes Store::commit()'s view check under version_lock, which is -// then released. +// - 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 2. -// - 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 +32,39 @@ 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 signature at the next TxID, without committing it to the + // Store. + std::pair prepare(uint8_t marker) { - history = std::make_shared(*store, node_id, *node_kp); - store->set_history(history); - start(); + const auto txid = store->next_txid().value(); + return {txid, SignaturePendingTx(txid, *store, marker).call()}; } }; } @@ -80,64 +75,248 @@ TEST_CASE( { HistoryFixture fixture; - const auto [baseline_txid, baseline_root, _] = - fixture.history->get_replicated_state_txid_and_root(); - REQUIRE(baseline_txid.seqno == 2); - REQUIRE(read_value(*fixture.store, fixture.table, 0) == 1); - REQUIRE(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + const auto baseline_root = fixture.root(); + REQUIRE(fixture.history_seqno() == 2); INFO("Apply and serialise A at seqno 3 in the initial view"); - const auto stale_txid = fixture.store->next_txid(); + auto [stale_txid, stale_info] = fixture.prepare(2); REQUIRE(stale_txid == ccf::TxID(fixture.initial_view, 3)); - auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); 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() == 3); INFO("Lose leadership and win a later election, rolling back to seqno 2"); 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 == 2); - REQUIRE(rolled_back_root == baseline_root); - } + REQUIRE(fixture.history_seqno() == 2); + REQUIRE(fixture.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 == 2); - CHECK(observed_root == baseline_root); - } - fixture.history->pause.release(); + INFO("Resume A: cft rejects it, and history, KV and ledger agree"); + replicate_pause.release(); stale_worker.join(); - - INFO("cft rejects A, and history, KV and ledger agree"); REQUIRE(stale_result.has_value()); CHECK(stale_result.value() == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(fixture.history_seqno() == 2); + CHECK(fixture.root() == baseline_root); + CHECK(fixture.store->current_txid().seqno == 2); + CHECK(fixture.cft->get_last_idx() == 2); + CHECK(fixture.cft->ledger->ledger.size() == 2); +} + +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(2); + 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( + "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([&]() { + 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()) { - const auto [final_txid, final_root, final_term] = - fixture.history->get_replicated_state_txid_and_root(); - CHECK(final_txid.seqno == 2); - CHECK(final_root == baseline_root); + std::this_thread::yield(); } + 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() == 2); + CHECK(fixture.root() == baseline_root); CHECK(fixture.store->current_txid().seqno == 2); - CHECK(read_value(*fixture.store, fixture.table, 0) == 1); - CHECK(read_signature_seqno(*fixture.store) == baseline_txid.seqno); + CHECK(read_signature_seqno(*fixture.store) == 2); CHECK(fixture.cft->get_last_idx() == 2); CHECK(fixture.cft->ledger->ledger.size() == 2); } + +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, 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(); + 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("A transaction reserved before stepping down cannot write"); + CHECK( + SignaturePendingTx(reserved_txid.value(), *fixture.store, 2) + .call() + .success == ccf::kv::CommitResult::FAIL_NO_REPLICATE); + CHECK(read_signature_seqno(*fixture.store) == 2); + + 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 = 2; + fixture.state->retirement_committable_idx = 2; + + INFO("Committing the retirement completes it, without deadlocking"); + auto tx = fixture.store->create_tx(); + tx.rw(retired)->put(0, 0); + REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); + const auto txid = fixture.store->next_txid().value(); + REQUIRE( + fixture.store->commit( + txid, + std::make_unique(txid, *fixture.store, 2), + true) == ccf::kv::CommitResult::SUCCESS); + REQUIRE(fixture.cft->get_committed_seqno() == 4); + 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 85a1c0fd30b..b5da38874f6 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.3. 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 2. +// - An election happens. Stepping down rolls the Store back past A, to seqno +// 2, and the node then wins in view W > V. // - Tx B is applied locally in view W and given TxID W.3. It has not yet // entered Store::commit(). // - A continues. CFT rejects it. If that rejection rolls the Store @@ -58,20 +58,22 @@ TEST_CASE( fixture.start(); INFO("Apply and serialise A at seqno 3 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, 3)); auto stale_info = SignaturePendingTx(stale_txid, *fixture.store, 2).call(); REQUIRE(stale_info.success == ccf::kv::CommitResult::SUCCESS); REQUIRE(read_signature_seqno(*fixture.store) == 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/js/test/js.cpp b/src/js/test/js.cpp index 84fec46b340..28741e8d88c 100644 --- a/src/js/test/js.cpp +++ b/src/js/test/js.cpp @@ -3127,7 +3127,7 @@ namespace std::vector make_test_signature_transaction(ccf::kv::Store& store) { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); tx.wo(ccf::Tables::SIGNATURES) ->put(ccf::PrimarySignature(ccf::NodeId("test-node"), txid.seqno)); diff --git a/src/kv/committable_tx.h b/src/kv/committable_tx.h index 6f3ac59aecb..ae43aa9901f 100644 --- a/src/kv/committable_tx.h +++ b/src/kv/committable_tx.h @@ -266,6 +266,33 @@ 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 do not request a snapshot 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(); + } + + 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 @@ -275,7 +302,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()) { @@ -314,11 +342,6 @@ namespace ccf::kv 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 @@ -356,6 +379,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. @@ -573,6 +600,18 @@ namespace ccf::kv throw std::logic_error("Reserved transaction cannot be empty"); } + // 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; + 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 1e2accbebb0..d26cdf1f563 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,12 +37,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include #include namespace ccf @@ -461,6 +464,72 @@ 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, 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: + // Keeps the owner of the lock alive until the guard has released it. + std::shared_ptr owner; + 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&& 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; + } + + void release() + { + writable = false; + if (guard.owns_lock()) + { + guard.unlock(); + } + } + }; + class Consensus : public ConfigurableConsensus { public: @@ -528,6 +597,24 @@ 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 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}; + } + + // 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) { @@ -847,9 +934,18 @@ namespace ccf::kv virtual void lock_map_set() = 0; virtual void unlock_map_set() = 0; + // Acquires a permit from consensus, see Consensus. A Store without + // 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. 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; + // Only stable while the caller holds a permit. + [[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 c7f17211a71..41399ce409a 100644 --- a/src/kv/store.h +++ b/src/kv/store.h @@ -1017,6 +1017,24 @@ namespace ccf::kv } } + LocalWritePermit acquire_local_write_permit() override + { + auto c = get_consensus(); + if (c == nullptr) + { + return {std::shared_lock{}, true}; + } + auto permit = c->acquire_local_write_permit(); + permit.set_owner(c); + return permit; + } + + [[nodiscard]] bool local_writes_enabled() override + { + auto c = get_consensus(); + return c == nullptr || c->local_writes_enabled(); + } + void initialise_term(Term t) override { // Note: This should only be called once, when the store is first @@ -1186,6 +1204,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 = c->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; @@ -1285,25 +1316,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()); } @@ -1325,6 +1371,13 @@ namespace ccf::kv offset++; } + // Consensus takes the role lock exclusively under its own lock, so this + // 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)) { std::lock_guard vguard(version_lock); @@ -1421,8 +1474,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 @@ -1444,13 +1506,19 @@ namespace ccf::kv return std::make_tuple(v, rollback_count.load()); } - 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 bfe0b9f6194..cbbfb287a56 100644 --- a/src/kv/test/kv_serialisation.cpp +++ b/src/kv/test/kv_serialisation.cpp @@ -722,7 +722,7 @@ TEST_CASE( ccf::kv::RawCopySerialisedValue> tree( ccf::Tables::SERIALISED_MERKLE_TREE); - auto tx = kv_store.create_reserved_tx(kv_store.next_txid()); + auto tx = kv_store.create_reserved_tx(kv_store.next_txid().value()); tx.wo(tree)->put(std::vector(512, 'A')); const auto [result, data, claims, commit_evidence, hooks] = diff --git a/src/kv/test/kv_test.cpp b/src/kv/test/kv_test.cpp index 2e5ed52e9ec..d7df96818af 100644 --- a/src/kv/test/kv_test.cpp +++ b/src/kv/test/kv_test.cpp @@ -160,7 +160,7 @@ TEST_CASE("Live transactions cannot acquire signature table handles") CHECK(store.current_version() == 0); INFO("Denied while a signature reservation is pending and after it commits"); - const auto signature_txid = store.next_txid(); + const auto signature_txid = store.next_txid().value(); check_denied(); MapTypes::StringString ordinary("public:ordinary"); { @@ -200,7 +200,7 @@ TEST_CASE("Historical signature entries remain readable") { ccf::kv::Store source; source.set_encryptor(std::make_shared()); - const auto txid = source.next_txid(); + const auto txid = source.next_txid().value(); auto info = make_signature_entry(source, txid, 42); REQUIRE(info.success == ccf::kv::CommitResult::SUCCESS); @@ -248,7 +248,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") INFO("Cannot access non-signature maps or upgrade signature handles"); { - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); CHECK_THROWS_AS( reserved.wo("public:ordinary"), ccf::kv::MapAccessDenied); @@ -277,7 +277,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") INFO("Clear on an empty signature table records a read and is rejected"); { - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); auto* tree = reserved.wo( ccf::Tables::SERIALISED_MERKLE_TREE); tree->clear(); @@ -286,7 +286,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") } INFO("Recorded read dependencies on populated signature tables are rejected"); - const auto baseline = store.next_txid(); + const auto baseline = store.next_txid().value(); REQUIRE( publish_signature_entry(store, baseline, 1) == ccf::kv::CommitResult::SUCCESS); @@ -299,7 +299,7 @@ TEST_CASE("Reserved transactions are write-only on signature tables") "has_globally_committed"}) { INFO("Reserved observation: ", observation); - auto reserved = store.create_reserved_tx(store.next_txid()); + auto reserved = store.create_reserved_tx(store.next_txid().value()); auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); const auto key = ccf::SerialisedMerkleTree::create_unit(); @@ -342,11 +342,11 @@ TEST_CASE("Materialised reads exclude gaps and cannot tear signature state") tx.rw(raw)->put("key", "old"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto old_signature = store.next_txid(); + const auto old_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, old_signature, 1) == ccf::kv::CommitResult::SUCCESS); - const auto pending_signature = store.next_txid(); + const auto pending_signature = store.next_txid().value(); { auto tx = store.create_tx(); tx.rw(raw)->put("key", "new"); @@ -415,7 +415,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") tx.rw(raw)->put("key", "old"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto initial_signature = store.next_txid(); + const auto initial_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, initial_signature, 1) == ccf::kv::CommitResult::SUCCESS); @@ -436,7 +436,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") tx.rw(raw)->put("key", "replacement"); REQUIRE(tx.commit() == ccf::kv::CommitResult::SUCCESS); } - const auto replacement_signature = store.next_txid(); + const auto replacement_signature = store.next_txid().value(); REQUIRE(replacement_signature.seqno == initial_signature.seqno); REQUIRE( publish_signature_entry(store, replacement_signature, 2) == @@ -487,7 +487,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") store.set_consensus(consensus); store.initialise_term(2); ccf::CoseSignatures cose_signatures(ccf::Tables::COSE_SIGNATURES); - const auto initial_signature = store.next_txid(); + const auto initial_signature = store.next_txid().value(); REQUIRE( publish_signature_entry(store, initial_signature, 1) == ccf::kv::CommitResult::SUCCESS); @@ -498,7 +498,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") consensus->view_history.rollback(0); consensus->flush(); REQUIRE( - publish_signature_entry(store, store.next_txid(), 2) == + publish_signature_entry(store, store.next_txid().value(), 2) == ccf::kv::CommitResult::SUCCESS); }; @@ -535,7 +535,7 @@ TEST_CASE("Materialised reads reject rollback and see replication compaction") store.set_encryptor(std::make_shared()); auto consensus = std::make_shared(store); store.set_consensus(consensus); - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( publish_signature_entry(store, txid, 1) == ccf::kv::CommitResult::SUCCESS); @@ -3289,7 +3289,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.wo(signatures); auto tree_handle = tx.wo(serialised_tree); ccf::PrimarySignature sigv(ccf::kv::test::PrimaryNodeId, 2); @@ -4375,7 +4375,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.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); @@ -4399,7 +4399,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", @@ -4411,7 +4411,7 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - const auto reserved_txid = kv_store.next_txid(); + const auto reserved_txid = kv_store.next_txid().value(); auto reserved = kv_store.create_reserved_tx(reserved_txid); reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); @@ -4441,7 +4441,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.wo(ccf::Tables::SERIALISED_MERKLE_TREE) ->put({42}); REQUIRE( @@ -4482,14 +4482,14 @@ TEST_CASE("CommittableTx guards") ccf::kv::Store kv_store; kv_store.set_encryptor(std::make_shared()); - const auto baseline = kv_store.next_txid(); + const auto baseline = kv_store.next_txid().value(); REQUIRE( make_signature_entry(kv_store, baseline, 42).success == ccf::kv::CommitResult::SUCCESS); // 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()); auto* handle = reserved.wo(ccf::Tables::SERIALISED_MERKLE_TREE); REQUIRE(handle->get(ccf::SerialisedMerkleTree::create_unit()).has_value()); @@ -4705,8 +4705,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)); } }; @@ -5171,7 +5171,7 @@ TEST_CASE("Reserved transaction map creation is serialised with lookups") { // Rollback removes the signature tables so the next reservation creates // them again, exercising add_dynamic_map on every iteration. - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); REQUIRE( make_signature_entry(store, txid, 42).success == ccf::kv::CommitResult::SUCCESS); @@ -5271,7 +5271,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 @@ -5773,7 +5773,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.wo(signatures); auto tree_handle = tx.wo(serialised_tree); @@ -5844,7 +5844,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 @@ -5895,12 +5895,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); @@ -5931,8 +5931,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); @@ -5965,7 +5965,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 cd0994896c8..f2505ad46c4 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 39f30641cf7..c458e8b9085 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, or completed + // retirement, since the caller checked, so do not 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/rpc/test/node_frontend_test.cpp b/src/node/rpc/test/node_frontend_test.cpp index dff08340915..b0150dce63d 100644 --- a/src/node/rpc/test/node_frontend_test.cpp +++ b/src/node/rpc/test/node_frontend_test.cpp @@ -834,7 +834,7 @@ TEST_CASE("Node state is explicitly nontransactional metadata") network.tables->initialise_term(2); auto publish_signature = [&](ccf::kv::Version reported_seqno) { - const auto txid = network.tables->next_txid(); + const auto txid = network.tables->next_txid().value(); auto tx = network.tables->create_reserved_tx(txid); tx.wo(Tables::SIGNATURES) ->put( diff --git a/src/node/snapshotter.h b/src/node/snapshotter.h index 4d7590d0255..536e24a4eab 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,33 @@ 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. + 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/historical_queries.cpp b/src/node/test/historical_queries.cpp index f7e65ec2311..554b69bb1ef 100644 --- a/src/node/test/historical_queries.cpp +++ b/src/node/test/historical_queries.cpp @@ -1792,7 +1792,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)); @@ -1965,7 +1965,7 @@ TEST_CASE("Historical cache rejects signatures which misreport their TxID") // Write a signature transaction by hand, which declares a TxID in a later // view than the one it is actually committed in - const auto signature_txid = store.next_txid(); + const auto signature_txid = store.next_txid().value(); const auto signature_seqno = signature_txid.seqno; const ccf::TxID declared_id{signature_txid.view + 1, signature_seqno}; { @@ -4126,7 +4126,7 @@ TEST_CASE( for (const auto& written_signatures : signature_transactions) { - const auto txid = store.next_txid(); + const auto txid = store.next_txid().value(); auto tx = store.create_reserved_tx(txid); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); for (const auto& [identity_type, signature] : written_signatures) diff --git a/src/node/test/history.cpp b/src/node/test/history.cpp index 94170d50c75..7b260361afc 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( @@ -317,7 +317,7 @@ TEST_CASE("Check signature verification") INFO("Issue a bogus signature, rejected by verification on the backup"); { - const auto txid = primary_store.next_txid(); + const auto txid = primary_store.next_txid().value(); auto txs = primary_store.create_reserved_tx(txid); auto sigs = txs.wo(signatures); ccf::PrimarySignature bogus(ccf::kv::test::PrimaryNodeId, txid.seqno); @@ -941,7 +941,7 @@ TEST_CASE("Pending signatures retain their endorsed certificate") constexpr auto store_term = 2; store.initialise_term(store_term); - const auto gap_txid = store.next_txid(); + const auto gap_txid = store.next_txid().value(); history->emit_signature(); REQUIRE(consensus->number_of_replicas() == 0); @@ -1119,7 +1119,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); @@ -1271,7 +1271,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; @@ -1384,7 +1384,7 @@ TEST_CASE("COSE signature table holds one entry per identity") INFO("A table carrying two identities round-trips both"); { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto* handle = tx.wo(ccf::Tables::COSE_SIGNATURES); handle->put(ccf::IdentityType::CLASSICAL, ec384_sig); handle->put(ccf::IdentityType::PQ, mldsa65_sig); @@ -1421,7 +1421,7 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") const ccf::CoseSignature keyed_signature{4, 5, 6}; { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); tx.wo(ccf::Tables::COSE_SIGNATURES) ->put(legacy_signature); tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) @@ -1437,7 +1437,7 @@ TEST_CASE("CLASSICAL COSE signatures interoperate with the legacy singleton") } { - auto tx = store.create_reserved_tx(store.next_txid()); + auto tx = store.create_reserved_tx(store.next_txid().value()); auto* signatures = tx.wo(ccf::Tables::COSE_SIGNATURES); signatures->put(ccf::IdentityType::CLASSICAL, keyed_signature); tx.wo(ccf::Tables::SERIALISED_MERKLE_TREE) diff --git a/src/node/test/snapshotter.cpp b/src/node/test/snapshotter.cpp index a73e341e34e..7895b968d45 100644 --- a/src/node/test/snapshotter.cpp +++ b/src/node/test/snapshotter.cpp @@ -1274,6 +1274,128 @@ 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("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; @@ -1448,7 +1570,7 @@ TEST_CASE("Rekey ledger while snapshot is in progress") { // It is necessary to record a signature for the snapshot to be // deserialisable by the backup store - const auto txid = network.tables->next_txid(); + const auto txid = network.tables->next_txid().value(); auto tx = network.tables->create_reserved_tx(txid); auto sigs = tx.wo(ccf::Tables::SIGNATURES); auto trees =