Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/local-writes-fenced-on-step-down.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
119 changes: 111 additions & 8 deletions src/consensus/aft/cft.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
#include "tasks/periodic_task_owner.h"

#include <algorithm>
#include <atomic>
#include <functional>
#include <list>
#include <map>
#include <random>
#include <shared_mutex>
#include <unordered_map>
#include <vector>

Expand Down Expand Up @@ -168,6 +170,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<bool> role_change_pending = false;
// Whether local writes are accepted. Only modified by
// update_local_writes(), with role_rwlock held exclusively.
std::atomic<bool> local_writes_open = false;

// Randomness
std::uniform_int_distribution<int> distrib;
std::default_random_engine rand;
Expand Down Expand Up @@ -321,6 +346,22 @@ namespace aft
}
}

ccf::kv::LocalWritePermit acquire_local_write_permit() override
{
if (role_change_pending.load())
{
return {};
}
std::shared_lock<ccf::ds::SharedMutex> 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<ccf::kv::NodeId>& node_ids) override
{
Expand Down Expand Up @@ -646,9 +687,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;
}

Expand All @@ -667,7 +711,6 @@ namespace aft
CFT_DEBUG_FMT(
"Failed to replicate {} items: node retirement is complete",
entries.size());
rollback(state->last_idx);
return false;
}

Expand Down Expand Up @@ -2013,6 +2056,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<ccf::ds::SharedMutex> 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())
Expand All @@ -2023,7 +2107,7 @@ namespace aft
return;
}

state->leadership_state.store(ccf::kv::LeadershipState::PreVoteCandidate);
set_leadership_state(ccf::kv::LeadershipState::PreVoteCandidate);
leader_id.reset();

reset_votes_for_me();
Expand Down Expand Up @@ -2061,12 +2145,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();
Expand Down Expand Up @@ -2106,15 +2192,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;
Expand Down Expand Up @@ -2156,7 +2251,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,
Expand Down Expand Up @@ -2275,6 +2370,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);
}

Expand Down Expand Up @@ -2547,6 +2644,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)
Expand Down Expand Up @@ -2629,6 +2731,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);
Expand Down
89 changes: 68 additions & 21 deletions src/consensus/aft/test/view_straddling_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include "kv/store.h"
#include "test_common.h"

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <doctest/doctest.h>
Expand All @@ -21,7 +22,6 @@
namespace straddling
{
using TestMap = ccf::kv::Map<size_t, size_t>;
using Cft = aft::Aft<aft::LedgerStubProxy>;

class BaselinePendingTx : public ccf::kv::PendingTx
{
Expand Down Expand Up @@ -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 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<aft::LedgerStubProxy>
{
std::atomic<CommitPause*> next_pause = nullptr;

public:
using aft::Aft<aft::LedgerStubProxy>::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<aft::LedgerStubProxy>::replicate(entries, term);
}
};

using Cft = PausingCft;

static std::optional<size_t> read_value(
ccf::kv::Store& store, TestMap& table, size_t key)
{
Expand All @@ -164,6 +197,7 @@ namespace straddling
const ccf::NodeId node_id = ccf::kv::test::PrimaryNodeId;
std::shared_ptr<ccf::kv::Store> store = std::make_shared<ccf::kv::Store>();
TestMap table{"public:table"};
std::shared_ptr<aft::State> state = std::make_shared<aft::State>(node_id);
std::shared_ptr<Cft> cft;
ccf::View initial_view = 0;

Expand All @@ -175,13 +209,29 @@ 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<BaselinePendingTx>(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>(
cft_settings,
std::make_unique<aft::Adaptor<ccf::kv::Store>>(store),
std::make_unique<aft::LedgerStubProxy>(node_id),
std::make_shared<aft::ChannelStubProxy>(),
std::make_shared<aft::State>(node_id),
state,
nullptr);
store->set_consensus(cft);

Expand All @@ -190,23 +240,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<BaselinePendingTx>(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();
}
Expand Down
Loading