From a345706690a1736bac4b8a94f5b069bf825d5a0f Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Mon, 16 Nov 2026 17:47:56 +0000 Subject: [PATCH 01/25] Commit a signature batched before a configuration adding the first peer A batch from a leader alone in its configuration which held a signature followed by a configuration adding a node left the signature uncommitted until the new node acknowledged: replicate() decided whether to commit after the batch's hooks had added the node. Decide before them, as the Lean model commits the signature within the batch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/consensus/aft/cft.h | 8 +++-- src/consensus/aft/test/driver.cpp | 11 ++++++ src/consensus/aft/test/driver.h | 36 ++++++++++++++++++- tests/cft_scenarios/CftDriver.lean | 8 +++++ tests/cft_scenarios/Scenarios.lean | 1 + ...ommit_before_reconfiguration_in_batch.lean | 20 +++++++++++ 6 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 tests/cft_scenarios/Scenarios/commit_before_reconfiguration_in_batch.lean diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index c6e79fe92910..9eb0eac8c66e 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -677,6 +677,10 @@ namespace aft // entries to the model as one batch trace::replicate(*state); + // A configuration in this batch may add a node, but an earlier signature + // in the batch is still committable without it + const bool no_other_nodes = other_nodes_in_active_configs().empty(); + for (const auto& [index, data, is_globally_committable, hooks] : entries) { bool globally_committable = is_globally_committable; @@ -741,8 +745,8 @@ namespace aft } } - // Try to advance commit at once if there are no other nodes. - if (other_nodes_in_active_configs().size() == 0) + // Try to advance commit at once if there were no other nodes. + if (no_other_nodes) { update_commit(); } diff --git a/src/consensus/aft/test/driver.cpp b/src/consensus/aft/test/driver.cpp index a559c7c2dc9b..9577632b0b3d 100644 --- a/src/consensus/aft/test/driver.cpp +++ b/src/consensus/aft/test/driver.cpp @@ -276,6 +276,17 @@ extern "C" command("replicate", t, batch), [&]() { driver->replicate(t, batch); }); } + lean_obj_res cft_replicate_and_trust_node( + b_lean_obj_arg term, b_lean_obj_arg entries, b_lean_obj_arg node) + { + const auto t = text(term); + const auto batch = texts(entries); + const auto id = text(node); + return step(command("replicate_and_trust_node", t, batch, id), [&]() { + driver->replicate_and_trust_node(t, batch, id); + }); + } + lean_obj_res cft_periodic_one(b_lean_obj_arg node, uint64_t milliseconds) { const auto id = text(node); diff --git a/src/consensus/aft/test/driver.h b/src/consensus/aft/test/driver.h index 93084099370f..4b06184cc136 100644 --- a/src/consensus/aft/test/driver.h +++ b/src/consensus/aft/test/driver.h @@ -977,7 +977,10 @@ class CftDriver // Replicates the entries in one batch: "$" is a signature, anything else a // transaction with that data void replicate( - const std::string& term_s, const std::vector& entries) + const std::string& term_s, + const std::vector& entries, + const std::optional& configuration = + std::nullopt) { const auto opt = find_primary_in_term(term_s); if (!opt.has_value()) @@ -1002,9 +1005,40 @@ class CftDriver {data_s.begin(), data_s.end()}, signature)); } + if (configuration.has_value()) + { + batch.push_back(make_entry( + node_id, + cft->get_last_idx() + 1 + batch.size(), + term_s, + {}, + false, + configuration)); + } cft->replicate(batch, term); } + // Replicates entries then a configuration adding new_node, in one batch + void replicate_and_trust_node( + const std::string& term_s, + const std::vector& entries, + const std::string& new_node) + { + add_node(new_node); + CFT_DRIVER_PRINT( + "Note over {}: Node {} trusted", ccf::NodeId(new_node), new_node); + ccf::kv::Configuration::Nodes configuration; + for (const auto& [id, node] : _nodes) + { + configuration.try_emplace(id); + if (id != ccf::NodeId(new_node)) + { + connect(id, new_node); + } + } + replicate(term_s, entries, configuration); + } + void disconnect(ccf::NodeId left, ccf::NodeId right) { bool noop = true; diff --git a/tests/cft_scenarios/CftDriver.lean b/tests/cft_scenarios/CftDriver.lean index 88bee4eeeb6a..e2c2eb82f921 100644 --- a/tests/cft_scenarios/CftDriver.lean +++ b/tests/cft_scenarios/CftDriver.lean @@ -87,6 +87,14 @@ Each entry is `signature`, or the data of a transaction. @[extern "cft_replicate"] opaque replicate (term : @& Term) (entries : @& List Text) : IO Unit +/-- +Create `node`, and replicate `entries` then a configuration adding it, in one batch on the +primary in `term`. +-/ +@[extern "cft_replicate_and_trust_node"] +opaque replicateAndTrustNode (term : @& Term) (entries : @& List Text) (node : @& NodeId) + : IO Unit + /-! ## Time -/ /-- Advance the clock of `node` by `ms` milliseconds. -/ diff --git a/tests/cft_scenarios/Scenarios.lean b/tests/cft_scenarios/Scenarios.lean index 5b179f276665..6836bbaebb85 100644 --- a/tests/cft_scenarios/Scenarios.lean +++ b/tests/cft_scenarios/Scenarios.lean @@ -9,6 +9,7 @@ import Scenarios.check_quorum import Scenarios.check_quorum_012_0 import Scenarios.check_quorum_0_012 import Scenarios.commit_before_pending_reconfiguration +import Scenarios.commit_before_reconfiguration_in_batch import Scenarios.commit_stepwise_through_reconfiguration import Scenarios.delayed_vote_requests import Scenarios.election diff --git a/tests/cft_scenarios/Scenarios/commit_before_reconfiguration_in_batch.lean b/tests/cft_scenarios/Scenarios/commit_before_reconfiguration_in_batch.lean new file mode 100644 index 000000000000..12cc7429ed71 --- /dev/null +++ b/tests/cft_scenarios/Scenarios/commit_before_reconfiguration_in_batch.lean @@ -0,0 +1,20 @@ +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. +import CftDriver + +open CftDriver + +-- A signature commits without the node added by a later configuration of the same batch +initialize scenario "commit_before_reconfiguration_in_batch" do + startNode 0 + replicate 2 [signature] + assertCommitIdx 0 2 + + -- 3: transaction, 4: signature, 5: [0] -> [0, 1] + replicateAndTrustNode 2 ["hello", signature] 1 + assertConfig 0 5 [0, 1] + assertCommitIdx 0 4 + + -- 6 also needs 1 + replicate 2 [signature] + assertCommitIdx 0 4 From 541b825aab72e4f300bd2364522f8da087ef6909 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Mon, 16 Nov 2026 18:31:33 +0000 Subject: [PATCH 02/25] Add trace encoders for Aft vote state Move Aft's nested Votes struct to aft::Votes in cft_types.h so the trace serialisation can name it, and add msgpack encoders for votes_for_me (array ordered by configuration index of {idx, quorum, sorted votes}) and for optional node IDs (nil when absent). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/consensus/aft/cft.h | 6 ---- src/consensus/aft/cft_trace_msgpack.h | 49 +++++++++++++++++++++++++++ src/consensus/aft/cft_types.h | 8 +++++ src/consensus/aft/test/main.cpp | 23 +++++++++++++ 4 files changed, 80 insertions(+), 6 deletions(-) diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 9eb0eac8c66e..9dbbc4c51d16 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -103,12 +103,6 @@ namespace aft std::optional leader_id = std::nullopt; // Keep track of votes in each active configuration - struct Votes - { - std::unordered_set votes; - size_t quorum = 0; - }; - std::map votes_for_me; std::chrono::milliseconds timeout_elapsed; diff --git a/src/consensus/aft/cft_trace_msgpack.h b/src/consensus/aft/cft_trace_msgpack.h index 04c9863a5138..c374c07eb6a3 100644 --- a/src/consensus/aft/cft_trace_msgpack.h +++ b/src/consensus/aft/cft_trace_msgpack.h @@ -10,6 +10,10 @@ #include #include +#include +#include +#include +#include namespace aft { @@ -105,6 +109,51 @@ namespace aft write_msgpack(out, state.committable_indices.back()); } } + + inline void write_msgpack( + std::vector& out, const std::map& votes_for_me) + { + using namespace ccf::msgpack; + using ccf::msgpack::write_msgpack; + write_array_header(out, container_size(votes_for_me.size())); + for (const auto& [idx, votes] : votes_for_me) + { + write_map_header(out, 3); + write_str(out, "idx"); + write_msgpack(out, idx); + write_str(out, "quorum"); + write_msgpack(out, votes.quorum); + write_str(out, "votes"); + std::vector voters; + voters.reserve(votes.votes.size()); + for (const auto& voter : votes.votes) + { + voters.emplace_back(voter.value()); + } + std::sort(voters.begin(), voters.end()); + write_array_header(out, container_size(voters.size())); + for (const auto& voter : voters) + { + write_str(out, voter); + } + } + } +} + +namespace ccf +{ + inline void write_msgpack( + std::vector& out, const std::optional& node_id) + { + if (node_id.has_value()) + { + msgpack::write_str(out, node_id->value()); + } + else + { + msgpack::write_nil(out); + } + } } namespace ccf::kv diff --git a/src/consensus/aft/cft_types.h b/src/consensus/aft/cft_types.h index 87c2cf3cdcb4..db318888d2f5 100644 --- a/src/consensus/aft/cft_types.h +++ b/src/consensus/aft/cft_types.h @@ -11,6 +11,7 @@ #include #include #include +#include namespace aft { @@ -20,6 +21,13 @@ namespace aft static constexpr size_t starting_view_change = 2; + // Votes received by a candidate in one active configuration + struct Votes + { + std::unordered_set votes; + size_t quorum = 0; + }; + class Store { public: diff --git a/src/consensus/aft/test/main.cpp b/src/consensus/aft/test/main.cpp index e49147a0b396..76ab4169d9cd 100644 --- a/src/consensus/aft/test/main.cpp +++ b/src/consensus/aft/test/main.cpp @@ -57,6 +57,29 @@ DOCTEST_TEST_CASE( DOCTEST_CHECK(calls.size() == 3); } +DOCTEST_TEST_CASE("Vote state trace encoding" * doctest::test_suite("trace")) +{ + std::map votes_for_me; + votes_for_me[7] = {{ccf::NodeId("c"), ccf::NodeId("a"), ccf::NodeId("b")}, 2}; + votes_for_me[3] = {{}, 1}; + std::vector bytes; + write_msgpack(bytes, votes_for_me); + DOCTEST_CHECK( + nlohmann::json::from_msgpack(bytes) == + nlohmann::json::array( + {{{"idx", 3}, {"quorum", 1}, {"votes", nlohmann::json::array()}}, + {{"idx", 7}, {"quorum", 2}, {"votes", {"a", "b", "c"}}}})); + + std::optional leader_id = std::nullopt; + bytes.clear(); + write_msgpack(bytes, leader_id); + DOCTEST_CHECK(nlohmann::json::from_msgpack(bytes).is_null()); + leader_id = ccf::NodeId("a"); + bytes.clear(); + write_msgpack(bytes, leader_id); + DOCTEST_CHECK(nlohmann::json::from_msgpack(bytes) == "a"); +} + DOCTEST_TEST_CASE("cft owns its periodic timer" * doctest::test_suite("single")) { const auto self = ccf::kv::test::PrimaryNodeId; From ae5646e014e1a4cdc10894082a24ec4402400f70 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Mon, 16 Nov 2026 18:31:38 +0000 Subject: [PATCH 03/25] Trace Aft protocol variables on the events that use them ccf.cft events now carry voted_for, votes_for_me, leader_id, is_new_follower and ticking as top-level fields next to state, each only on the trace points whose lock hold reads or writes it, with its value when the trace point executes. Plain tick records gain only ticking, which the election-timeout check reads. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../cft-trace-protocol-variables.added.md | 2 + lean/consensus/replay/README.md | 4 + src/consensus/aft/cft.h | 36 +++++--- src/consensus/aft/cft_trace_msgpack.h | 86 ++++++++++++++++--- 4 files changed, 103 insertions(+), 25 deletions(-) create mode 100644 .changes/cft-trace-protocol-variables.added.md diff --git a/.changes/cft-trace-protocol-variables.added.md b/.changes/cft-trace-protocol-variables.added.md new file mode 100644 index 000000000000..50a591835b73 --- /dev/null +++ b/.changes/cft-trace-protocol-variables.added.md @@ -0,0 +1,2 @@ +`ccf.cft` consensus trace events now also carry the protocol variables `voted_for`, `votes_for_me`, `leader_id`, `is_new_follower` and `ticking` as top-level fields, on the events whose code reads or writes them. +See the [consensus trace replay README](lean/consensus/replay/README.md#run-replay) for the encoding. diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 90c7ac670199..3a6c9bf28184 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -31,6 +31,10 @@ done The scenario runner writes the raw records to `consensus/raw/`. The Fluentd tag is `ccf.cft`; packet message names are unprefixed, for example `append_entries` and `request_vote`. +Each event's `state` field is a snapshot of `aft::State`. +Events whose code reads or writes the `aft::Aft` variables `voted_for`, `votes_for_me`, `leader_id`, `is_new_follower` or `ticking` also carry those variables as top-level fields next to `state`, with their values when the event is traced; [`cft_trace_msgpack.h`](../../../src/consensus/aft/cft_trace_msgpack.h) lists the fields of each event. +`voted_for` and `leader_id` are a node ID or nil, and `votes_for_me` is an array, ordered by configuration index, of `{"idx", "quorum", "votes"}` maps whose `votes` lists the sorted IDs of the nodes that voted for this node in that configuration. +Replay currently ignores these fields. ## Replay contract diff --git a/src/consensus/aft/cft.h b/src/consensus/aft/cft.h index 9dbbc4c51d16..426e3fd90534 100644 --- a/src/consensus/aft/cft.h +++ b/src/consensus/aft/cft.h @@ -691,7 +691,8 @@ namespace aft (globally_committable ? " committable" : ""), hooks->size()); - trace::replicate_entry(*state, term, index, globally_committable); + trace::replicate_entry( + *state, term, index, globally_committable, ticking); for (auto& hook : *hooks) { @@ -848,7 +849,7 @@ namespace aft void periodic(std::chrono::milliseconds elapsed) override { std::unique_lock guard(state->lock); - trace::tick(*state); + trace::tick(*state, ticking); timeout_elapsed += elapsed; if (state->leadership_state.load() == ccf::kv::LeadershipState::Leader) @@ -1118,7 +1119,8 @@ namespace aft r.idx, r.term); - trace::recv_append_entries(*state, r, from.value()); + trace::recv_append_entries( + *state, r, from.value(), leader_id, is_new_follower); // Don't check that the sender node ID is valid. Accept anything that // passes the integrity check. This way, entries containing dynamic @@ -1372,7 +1374,7 @@ namespace aft auto& [ds, i] = ae; CFT_DEBUG_FMT("Replicating on follower {}: {}", state->node_id, i); - trace::execute_append_entries_sync(*state, from.value()); + trace::execute_append_entries_sync(*state, from.value(), ticking); bool track_deletes_on_missing_keys = false; ccf::kv::ApplyResult apply_success = @@ -1791,7 +1793,7 @@ namespace aft { std::lock_guard guard(state->lock); - trace::recv_request_vote(*state, r, from.value()); + trace::recv_request_vote(*state, r, from.value(), voted_for, leader_id); recv_request_vote_unsafe(from, r, ElectionType::RegularVote); } @@ -1857,7 +1859,7 @@ namespace aft { std::lock_guard guard(state->lock); - trace::recv_request_vote_response(*state, r, from.value()); + trace::recv_request_vote_response(*state, r, from.value(), votes_for_me); // Ignore if we don't recognise the node. auto node = all_other_nodes.find(from); @@ -1980,7 +1982,7 @@ namespace aft { std::lock_guard guard(state->lock); - trace::recv_propose_request_vote(*state, r, from.value()); + trace::recv_propose_request_vote(*state, r, from.value(), ticking); if (!is_retired_committed() && ticking && r.term == state->current_view) { @@ -2032,7 +2034,8 @@ namespace aft state->node_id, state->current_view); - trace::become_pre_vote_candidate(*state, configurations); + trace::become_pre_vote_candidate( + *state, configurations, votes_for_me, leader_id); add_vote_for_me(state->node_id); @@ -2072,7 +2075,8 @@ namespace aft CFT_INFO_FMT( "Becoming candidate {}: {}", state->node_id, state->current_view); - trace::become_candidate(*state, configurations); + trace::become_candidate( + *state, configurations, voted_for, votes_for_me, leader_id); add_vote_for_me(state->node_id); @@ -2122,7 +2126,7 @@ namespace aft CFT_INFO_FMT( "Becoming leader {}: {}", state->node_id, state->current_view); - trace::become_leader(*state, configurations); + trace::become_leader(*state, configurations, votes_for_me, leader_id); // Try to advance commit at once if there are no other nodes. if (other_nodes_in_active_configs().size() == 0) @@ -2161,7 +2165,13 @@ namespace aft state->current_view, state->commit_idx); - trace::become_follower(*state, configurations); + trace::become_follower( + *state, + configurations, + voted_for, + votes_for_me, + leader_id, + is_new_follower); } // Called when a replica becomes aware of the existence of a new term @@ -2523,7 +2533,7 @@ namespace aft return; } - trace::commit(*state, idx, configurations); + trace::commit(*state, idx, configurations, leader_id); compact_committable_indices(idx); @@ -2719,7 +2729,7 @@ namespace aft if (successor.has_value()) { trace::step_down_and_nominate_successor( - *state, configurations, successor.value().value()); + *state, configurations, successor.value().value(), leader_id); send_propose_request_vote(successor.value()); } diff --git a/src/consensus/aft/cft_trace_msgpack.h b/src/consensus/aft/cft_trace_msgpack.h index c374c07eb6a3..4075587faef2 100644 --- a/src/consensus/aft/cft_trace_msgpack.h +++ b/src/consensus/aft/cft_trace_msgpack.h @@ -191,6 +191,9 @@ namespace aft::trace { constexpr std::string_view cft_trace_tag = "ccf.cft"; + // Besides state, an event carries the members of Aft (voted_for, + // votes_for_me, leader_id, is_new_follower, ticking) that its handling + // reads or writes, as they are when the event is traced. DECLARE_TRACE_EVENT( send_append_entries, cft_trace_tag, @@ -208,36 +211,94 @@ namespace aft::trace match_idx, sent_idx); DECLARE_TRACE_EVENT( - recv_append_entries, cft_trace_tag, state, packet, from_node_id); + recv_append_entries, + cft_trace_tag, + state, + packet, + from_node_id, + leader_id, + is_new_follower); DECLARE_TRACE_EVENT( - execute_append_entries_sync, cft_trace_tag, state, from_node_id); + execute_append_entries_sync, cft_trace_tag, state, from_node_id, ticking); DECLARE_TRACE_EVENT( send_append_entries_response, cft_trace_tag, state, packet, to_node_id); DECLARE_TRACE_EVENT( send_request_vote, cft_trace_tag, state, packet, to_node_id); DECLARE_TRACE_EVENT( send_request_vote_response, cft_trace_tag, state, packet, to_node_id); + // Only a regular vote request reads voted_for and leader_id DECLARE_TRACE_EVENT( recv_request_vote, cft_trace_tag, state, packet, from_node_id); DECLARE_TRACE_EVENT( - recv_request_vote_response, cft_trace_tag, state, packet, from_node_id); + recv_request_vote, + cft_trace_tag, + state, + packet, + from_node_id, + voted_for, + leader_id); + DECLARE_TRACE_EVENT( + recv_request_vote_response, + cft_trace_tag, + state, + packet, + from_node_id, + votes_for_me); + DECLARE_TRACE_EVENT( + recv_propose_request_vote, + cft_trace_tag, + state, + packet, + from_node_id, + ticking); + DECLARE_TRACE_EVENT(tick, cft_trace_tag, state, ticking); + DECLARE_TRACE_EVENT( + become_pre_vote_candidate, + cft_trace_tag, + state, + configurations, + votes_for_me, + leader_id); DECLARE_TRACE_EVENT( - recv_propose_request_vote, cft_trace_tag, state, packet, from_node_id); - DECLARE_TRACE_EVENT(tick, cft_trace_tag, state); + become_candidate, + cft_trace_tag, + state, + configurations, + voted_for, + votes_for_me, + leader_id); + DECLARE_TRACE_EVENT( + become_leader, + cft_trace_tag, + state, + configurations, + votes_for_me, + leader_id); DECLARE_TRACE_EVENT( - become_pre_vote_candidate, cft_trace_tag, state, configurations); - DECLARE_TRACE_EVENT(become_candidate, cft_trace_tag, state, configurations); - DECLARE_TRACE_EVENT(become_leader, cft_trace_tag, state, configurations); - DECLARE_TRACE_EVENT(become_follower, cft_trace_tag, state, configurations); + become_follower, + cft_trace_tag, + state, + configurations, + voted_for, + votes_for_me, + leader_id, + is_new_follower); DECLARE_TRACE_EVENT(nomination, cft_trace_tag, state); DECLARE_TRACE_EVENT( step_down_and_nominate_successor, cft_trace_tag, state, configurations, - to_node_id); + to_node_id, + leader_id); DECLARE_TRACE_EVENT( - replicate_entry, cft_trace_tag, state, view, seqno, globally_committable); + replicate_entry, + cft_trace_tag, + state, + view, + seqno, + globally_committable, + ticking); DECLARE_TRACE_EVENT( retired_committed_tx, cft_trace_tag, node_id, seqno, retired_node_id); DECLARE_TRACE_EVENT(init_as_backup, cft_trace_tag, state, seqno, view); @@ -245,7 +306,8 @@ namespace aft::trace DECLARE_TRACE_EVENT(replicate, cft_trace_tag, state); DECLARE_TRACE_EVENT( add_configuration, cft_trace_tag, state, configurations, idx, nodes, rid); - DECLARE_TRACE_EVENT(commit, cft_trace_tag, state, idx, configurations); + DECLARE_TRACE_EVENT( + commit, cft_trace_tag, state, idx, configurations, leader_id); DECLARE_TRACE_EVENT( drop_pending_to, cft_trace_tag, state, from_node_id, to_node_id, packet); } From 2357f640d2d67220d6b6fe37d35a66350b435747 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:06:46 +0000 Subject: [PATCH 04/25] Add observation refinement and lock-hold sections to ccf_common Trace validation needs a protocol-independent statement of what an accepted trace means, and a framework that turns per-hold simulation into that statement. CCF.Observation states refinement of a specification at observed trace events; CCF.Sections models event-granular nodes whose lock holds are checked at release, and CCF.Proofs.Sections/SectionsObservation prove that accepted section runs refine the clean network at those events. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/common/CCF.lean | 4 + lean/common/CCF/Observation.lean | 53 ++ lean/common/CCF/Proofs/Sections.lean | 751 ++++++++++++++++++ .../CCF/Proofs/SectionsObservation.lean | 275 +++++++ lean/common/CCF/Sections.lean | 341 ++++++++ lean/common/README.md | 34 +- 6 files changed, 1443 insertions(+), 15 deletions(-) create mode 100644 lean/common/CCF/Observation.lean create mode 100644 lean/common/CCF/Proofs/Sections.lean create mode 100644 lean/common/CCF/Proofs/SectionsObservation.lean create mode 100644 lean/common/CCF/Sections.lean diff --git a/lean/common/CCF.lean b/lean/common/CCF.lean index 910ee08e5ce8..f283997049b4 100644 --- a/lean/common/CCF.lean +++ b/lean/common/CCF.lean @@ -6,11 +6,15 @@ public import CCF.Execution public import CCF.Finset public import CCF.Function public import CCF.MultiNodeTransitionSystem +public import CCF.Observation public import CCF.Parsec public import CCF.Proofs.Execution public import CCF.Proofs.Finset public import CCF.Proofs.Function +public import CCF.Proofs.Sections +public import CCF.Proofs.SectionsObservation public import CCF.Proofs.Seq +public import CCF.Sections public import CCF.Seq public import CCF.TransitionSystem public import CCF.TxID diff --git a/lean/common/CCF/Observation.lean b/lean/common/CCF/Observation.lean new file mode 100644 index 000000000000..2f012414ec9b --- /dev/null +++ b/lean/common/CCF/Observation.lean @@ -0,0 +1,53 @@ +module + +public import CCF.Execution + +@[expose] public section + +namespace CCF.ObservationRefinement + +/-! +Observation-point refinement: the reviewed statement relating a traced +implementation to a specification. + +An implementation is observed through a list of `Observation`s, one per traced event, +each carrying the node's declared state as snapshotted at that event. `Refines` says +that one specification execution, read at nondecreasing positions, explains every +observed point: the observed node's state in the specification at the corresponding +position is related by `rel` to the observed declared state. Only declared states, +`rel`, the event predicate and the specification appear here; how the implementation +model is built, and how it is proved to satisfy this, is not part of the statement. +-/ + +/-- One traced event: the node, the event, and the node's declared state at the event. -/ +structure Observation (Node Event Declared : Type) where + /-- The node that traced the event. -/ + node : Node + /-- The traced event, with every label it carries. -/ + event : Event + /-- The node's declared state, as snapshotted when the event was traced. -/ + declared : Declared + +/-- +`Refines spec nodeOf rel observed observations`: there is a specification trace and a +nondecreasing map `index` from observation positions to trace positions such that, at +every observation whose event satisfies `observed`, the trace's state at `index` +position has the observed node in a state related by `rel` (for that node) to the +observed declared state. +-/ +def Refines {Node Event Declared SpecLocal : Type} (spec : TransitionSystem) + (nodeOf : spec.State -> Node -> Option SpecLocal) + (rel : Node -> SpecLocal -> Declared -> Prop) + (observed : Event -> Bool) (observations : List (Observation Node Event Declared)) + : Prop := + exists (trace : Execution.Trace spec) (index : Nat -> Nat), + (forall i j, i <= j -> index i <= index j) + /\ forall (i : Nat) (observation : Observation Node Event Declared), + observations[i]? = some observation + -> observed observation.event = true + -> exists state local_, + trace.stateAt (index i) = some state + /\ nodeOf state observation.node = some local_ + /\ rel observation.node local_ observation.declared + +end CCF.ObservationRefinement diff --git a/lean/common/CCF/Proofs/Sections.lean b/lean/common/CCF/Proofs/Sections.lean new file mode 100644 index 000000000000..be663bba5468 --- /dev/null +++ b/lean/common/CCF/Proofs/Sections.lean @@ -0,0 +1,751 @@ +module + +public import CCF.Sections +public import CCF.Proofs.Execution + +@[expose] public section + +namespace CCF.Sections + +/-! +The lifting step: a `Refinement` makes every step of the event-granular network a +(possibly empty) run of the guarded clean network, preserving a simulation relation. +Event and delivery steps are matched by no clean step; a release is matched by the +section's clean local run. +-/ + +open MultiNodeTransitionSystem (nodeState removeOne) +open Execution (Run) + +/-- `guard` in `Option`, as a conditional. -/ +theorem option_guard_bind {α : Type} (p : Prop) [Decidable p] (f : Unit -> Option α) + : (guard p : Option Unit).bind f = if p then f () else none := by + by_cases h : p <;> simp [h, guard, pure, failure] + +section TableLemmas + +variable {Node LocalState Message : Type} [BEq Node] [LawfulBEq Node] + +/-- A found entry is a member of the node table, under its own key. -/ +theorem mem_of_nodeState {state : MultiNodeTransitionSystem.State Node LocalState Message} + {node : Node} {value : LocalState} (found : nodeState state node = some value) + : (node, value) ∈ state.nodes := by + unfold nodeState at found + obtain ⟨entry, hfind, rfl⟩ := Option.map_eq_some_iff.mp found + have hkey := List.find?_some hfind + have hmem := List.mem_of_find?_eq_some hfind + simp only [beq_iff_eq] at hkey + subst hkey + exact hmem + +/-- Overwriting preserves the key list. -/ +theorem keys_setNode (state : MultiNodeTransitionSystem.State Node LocalState Message) + (node : Node) (value : LocalState) + : (setNode state node value).nodes.map Prod.fst = state.nodes.map Prod.fst := by + simp only [setNode, List.map_map] + apply List.map_congr_left + intro entry _ + by_cases h : entry.1 = node <;> simp [h] + +/-- Members of an overwritten table are the new entry or old members. -/ +theorem mem_setNode {state : MultiNodeTransitionSystem.State Node LocalState Message} + {node : Node} {value : LocalState} {entry : Node × LocalState} + (member : entry ∈ (setNode state node value).nodes) + : entry = (node, value) \/ entry ∈ state.nodes := by + simp only [setNode, List.mem_map] at member + obtain ⟨old, hold, rfl⟩ := member + by_cases h : old.1 = node <;> simp [h, hold] + +/-- Overwriting a present node makes the lookup return the new value. -/ +theorem nodeState_setNode + {state : MultiNodeTransitionSystem.State Node LocalState Message} {node : Node} + {old value : LocalState} (found : nodeState state node = some old) + : nodeState (setNode state node value) node = some value := by + unfold nodeState at found ⊢ + simp only [setNode, List.find?_map] + have hcomp : ((fun entry : Node × LocalState => entry.1 == node) + ∘ fun entry => if entry.1 == node then (node, value) else entry) + = fun entry => entry.1 == node := by + funext entry + by_cases h : entry.1 = node <;> simp [h] + rw [hcomp] + obtain ⟨entry, hfind, _⟩ := Option.map_eq_some_iff.mp found + rw [hfind] + have hkey := List.find?_some hfind + simp [hkey] + +/-- Two overwrites of the same node keep the last value. -/ +theorem setNode_setNode (state : MultiNodeTransitionSystem.State Node LocalState Message) + (node : Node) (first second : LocalState) + : setNode (setNode state node first) node second = setNode state node second := by + simp only [setNode, List.map_map] + congr 2 + funext entry + by_cases h : entry.1 = node <;> simp [h] + +private theorem map_set_absent (entries : List (Node × LocalState)) (node : Node) + (value : LocalState) (absent : forall entry, entry ∈ entries -> entry.1 ≠ node) + : entries.map (fun entry => if entry.1 == node then (node, value) else entry) + = entries := by + induction entries with + | nil => rfl + | cons head tail ih => + have hhead := absent head (by simp) + simp only [List.map_cons, beq_iff_eq, hhead, ite_false] + rw [ih fun entry member => absent entry (by simp [member])] + +private theorem map_set_self (entries : List (Node × LocalState)) (node : Node) + (value : LocalState) (distinct : (entries.map Prod.fst).Nodup) + (found : (entries.find? fun entry => entry.1 == node).map Prod.snd = some value) + : entries.map (fun entry => if entry.1 == node then (node, value) else entry) + = entries := by + induction entries with + | nil => simp at found + | cons head tail ih => + simp only [List.map_cons, List.nodup_cons, List.mem_map] at distinct + obtain ⟨fresh, distinct⟩ := distinct + by_cases h : head.1 = node + · simp only [List.find?_cons, h, beq_self_eq_true, Option.map_some, + Option.some.injEq] at found + simp only [List.map_cons, h, beq_self_eq_true, ite_true] + rw [map_set_absent tail node value] + · rw [← h, ← found] + · intro entry member same + exact fresh ⟨entry, member, by rw [same, h]⟩ + · have hne : (head.1 == node) = false := by simp [h] + simp only [List.find?_cons, hne] at found + simp only [List.map_cons, hne] + rw [ih distinct found] + rfl + +/-- Overwriting a node with its current value changes nothing, given distinct keys. -/ +theorem setNode_self {state : MultiNodeTransitionSystem.State Node LocalState Message} + {node : Node} {value : LocalState} (distinct : (state.nodes.map Prod.fst).Nodup) + (found : nodeState state node = some value) + : setNode state node value = state := by + cases state with + | mk nodes network => + simp only [setNode, MultiNodeTransitionSystem.State.mk.injEq, and_true] + exact map_set_self nodes node value distinct found + +/-- Overwriting a node twice keeps the last value, whatever the network in between. -/ +theorem setNode_network_setNode + (state : MultiNodeTransitionSystem.State Node LocalState Message) (node : Node) + (first second : LocalState) (network : List (Envelope Node Message)) + : setNode { setNode state node first with network } node second + = { setNode state node second with network } := by + simp only [setNode, List.map_map, MultiNodeTransitionSystem.State.mk.injEq, and_true] + apply List.map_congr_left + intro entry _ + by_cases h : entry.1 = node <;> simp [h] + +end TableLemmas + +section KeyedLists + +variable {Node A B : Type} + +theorem Keyed.keys {related : Node -> A -> B -> Prop} + : forall {lefts : List (Node × A)} {rights : List (Node × B)}, + Keyed related lefts rights -> lefts.map Prod.fst = rights.map Prod.fst + | [], [], _ => rfl + | _ :: _, _ :: _, .cons _ rest => by simp [Keyed.keys rest] + +variable [BEq Node] [LawfulBEq Node] in +theorem Keyed.find {related : Node -> A -> B -> Prop} {node : Node} + : forall {lefts : List (Node × A)} {rights : List (Node × B)} {right : B}, + Keyed related lefts rights + -> (rights.find? fun entry => entry.1 == node).map Prod.snd = some right + -> exists left, + (lefts.find? fun entry => entry.1 == node).map Prod.snd = some left + /\ related node left right + | [], [], _, _, found => by simp at found + | (key, left) :: _, (_, _) :: _, right, .cons holds rest, found => by + by_cases hkey : key = node + · subst hkey + simp only [List.find?_cons, beq_self_eq_true, Option.map_some, Option.some.injEq] + at found ⊢ + subst found + exact ⟨left, rfl, holds⟩ + · have hne : (key == node) = false := by simp [hkey] + simp only [List.find?_cons, hne] at found ⊢ + exact Keyed.find rest found + +variable [BEq Node] [LawfulBEq Node] in +theorem Keyed.set {related : Node -> A -> B -> Prop} {node : Node} {left : A} {right : B} + (holds : related node left right) + : forall {lefts : List (Node × A)} {rights : List (Node × B)}, + Keyed related lefts rights + -> Keyed related + (lefts.map fun entry => if entry.1 == node then (node, left) else entry) + (rights.map fun entry => if entry.1 == node then (node, right) else entry) + | [], [], _ => .nil + | (key, _) :: _, (_, _) :: _, .cons holds' rest => by + by_cases hkey : key = node + · subst hkey + simp only [List.map_cons, beq_self_eq_true, ite_true] + exact .cons holds (Keyed.set holds rest) + · have hne : (key == node) = false := by simp [hkey] + simp only [List.map_cons, hne] + exact .cons holds' (Keyed.set holds rest) + +variable [BEq Node] [LawfulBEq Node] in +theorem Keyed.without {related : Node -> A -> B -> Prop} {node : Node} + : forall {lefts : List (Node × A)} {rights : List (Node × B)}, + Keyed related lefts rights + -> Keyed related (Sections.without lefts node) (Sections.without rights node) + | [], [], _ => .nil + | (key, _) :: _, (_, _) :: _, .cons holds rest => by + by_cases hkey : key = node + · subst hkey + simpa [Sections.without] using Keyed.without (node := key) rest + · have hne : (key == node) = false := by simp [hkey] + have := Keyed.without (node := node) rest + simp only [Sections.without, List.filter_cons, hne, Bool.not_false, ite_true] at this ⊢ + exact .cons holds this + +theorem Keyed.map_flip {related : Node -> A -> B -> Prop} {C : Type} + {other : Node -> C -> A -> Prop} {f : B -> C} + (implies + : forall node left right, related node left right -> other node (f right) left) + : forall {lefts : List (Node × A)} {rights : List (Node × B)}, + Keyed related lefts rights + -> Keyed other (rights.map fun entry => (entry.1, f entry.2)) lefts + | [], [], _ => .nil + | _ :: _, _ :: _, .cons holds rest => + .cons (implies _ _ _ holds) (Keyed.map_flip implies rest) + +end KeyedLists + +/-- Overwriting a node does not change the table without it. -/ +theorem without_setNode {Node LocalState Message : Type} [BEq Node] [LawfulBEq Node] + (state : MultiNodeTransitionSystem.State Node LocalState Message) (node : Node) + (value : LocalState) + : without (setNode state node value).nodes node = without state.nodes node := by + simp only [without, setNode] + induction state.nodes with + | nil => rfl + | cons head tail ih => + by_cases h : head.1 = node + · simp [h, ih] + · have hne : (head.1 == node) = false := by simp [h] + simp only [List.map_cons, hne, Bool.false_eq_true, ite_false, List.filter_cons, ih] + +section Machine + +variable {Node Message LocalState Event : Type} + {machine : Machine Node Message LocalState Event} + {node : Node} + +theorem Steps.snoc {start finish last : LocalState} {events : List Event} {event : Event} + (steps : Steps machine node start events finish) + (step : machine.step node finish none event = some last) + : Steps machine node start (events ++ [event]) last := by + induction steps with + | nil => exact .cons step (.nil _) + | cons first _ ih => exact .cons first (ih step) + +theorem SectionRun.snoc {start finish last : LocalState} + {received : Option (Node × Message)} {events : List Event} {event : Event} + (run : SectionRun machine node start received events finish) + (step : machine.step node finish none event = some last) + : SectionRun machine node start received (events ++ [event]) last := by + obtain ⟨first, rest, middle, rfl, hfirst, hsteps⟩ := run + exact ⟨first, rest ++ [event], middle, by simp, hfirst, hsteps.snoc step⟩ + +theorem SectionRun.single {start finish : LocalState} {received : Option (Node × Message)} + {event : Event} (step : machine.step node start received event = some finish) + : SectionRun machine node start received [event] finish := + ⟨event, [], finish, rfl, step, .nil _⟩ + +end Machine + +section Inversion + +variable {Node Message LocalState Event : Type} [BEq Node] [BEq Message] + {machine : Machine Node Message LocalState Event} + {state after : State Node Message LocalState} + +theorem next_event_inv {node : Node} {event : Event} + (step : next machine state (.event node event) = some after) + : exists slot current, + nodeState state node = some slot + /\ (!machine.opens event || slot.entry.isNone) = true + /\ machine.step node slot.current none event = some current + /\ after + = setNode state node + { + slot with + current, entry := slot.entry.orElse fun _ => some slot.current + } := by + simp only [next] at step + cases found : nodeState state node with + | none => simp [found] at step + | some slot => + cases allowed : (!machine.opens event || slot.entry.isNone) with + | false => + simp only [found, option_guard_bind, Option.bind_eq_bind, Option.bind_some] at step + rw [allowed] at step + simp at step + | true => + cases ran : machine.step node slot.current none event with + | none => simp [found, ran, option_guard_bind] at step + | some current => + simp only [found, allowed, ran, option_guard_bind, Option.bind_eq_bind, + Option.bind_some, ite_true, Option.pure_def, Option.some.injEq] at step + exact ⟨slot, current, rfl, allowed, ran, step.symm⟩ + +theorem next_deliver_inv {envelope : Envelope Node Message} {event : Event} + (step : next machine state (.deliver envelope event) = some after) + : state.network.contains envelope = true + /\ exists slot current, + nodeState state envelope.target = some slot + /\ slot.entry = none + /\ machine.step envelope.target slot.current + (some (envelope.source, envelope.payload)) event + = some current + /\ after + = setNode state envelope.target + { current, entry := some slot.current, inbox := some envelope } := by + simp only [next] at step + cases queued : state.network.contains envelope with + | false => simp [queued, option_guard_bind] at step + | true => + cases found : nodeState state envelope.target with + | none => simp [queued, found, option_guard_bind] at step + | some slot => + cases free : slot.entry with + | some _ => simp [queued, found, free, option_guard_bind] at step + | none => + cases ran + : machine.step envelope.target slot.current + (some (envelope.source, envelope.payload)) event with + | none => simp [queued, found, free, ran, option_guard_bind] at step + | some current => + simp only [queued, found, free, ran, option_guard_bind, Option.bind_eq_bind, + Option.bind_some, ite_true, Option.isNone_none, Option.pure_def, + Option.some.injEq] at step + exact ⟨rfl, slot, current, rfl, free, ran, step.symm⟩ + +theorem next_release_inv {node : Node} + (step : next machine state (.release node) = some after) + : exists slot start finish sends pending, + nodeState state node = some slot + /\ slot.entry = some start + /\ machine.close + ((without state.nodes node).map fun entry => (entry.1, entry.2.base)) node + slot.current + = some (finish, sends) + /\ machine.idle finish = true + /\ ((slot.inbox = none /\ pending = state.network) + \/ exists envelope, + slot.inbox = some envelope + /\ state.network.contains envelope = true + /\ pending = removeOne envelope state.network) + /\ after + = { + setNode state node { current := finish } with + network := pending ++ sends + } := by + simp only [next] at step + cases found : nodeState state node with + | none => simp [found] at step + | some slot => + cases held : slot.entry with + | none => simp [found, held, option_guard_bind] at step + | some start => + cases closed + : machine.close + ((without state.nodes node).map fun entry => (entry.1, entry.2.base)) + node slot.current with + | none => simp [found, held, closed, option_guard_bind] at step + | some result => + obtain ⟨finish, sends⟩ := result + cases hidle : machine.idle finish with + | false => simp [found, held, closed, hidle, option_guard_bind] at step + | true => + cases hinbox : slot.inbox with + | none => + simp only [found, held, closed, hidle, hinbox, + option_guard_bind, Option.bind_eq_bind, Option.bind_some, + Option.isSome_some, ite_true, Option.pure_def, + Option.some.injEq] at step + exact ⟨slot, start, finish, sends, state.network, rfl, held, closed, hidle, + .inl ⟨hinbox, rfl⟩, step.symm⟩ + | some envelope => + cases queued : state.network.contains envelope with + | false => + simp [found, held, closed, hinbox, queued, option_guard_bind] at step + | true => + simp only [found, held, closed, hidle, hinbox, queued, + option_guard_bind, Option.bind_eq_bind, Option.bind_some, + Option.isSome_some, ite_true, Option.pure_def, + Option.some.injEq] at step + exact ⟨slot, start, finish, sends, removeOne envelope state.network, + rfl, held, closed, hidle, + .inr ⟨envelope, hinbox, queued, rfl⟩, step.symm⟩ + +end Inversion + +section Lift + +variable {Node Message CleanState LocalAction Notification Input : Type} + [BEq Node] [BEq Message] + +/-- One clean internal step through the network composition. -/ +theorem next_local + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + {state : MultiNodeTransitionSystem.State Node CleanState Message} {node : Node} + {before after : CleanState} {input : Input} + {effects : Outputs Node Message Notification} + (found : nodeState state node = some before) + (step + : (protocol.step (Capabilities.record node) node before + (protocol.internal input)).run + {} + = some (after, effects)) + : MultiNodeTransitionSystem.next protocol state (.local node input) + = some + { + setNode state node after with + network := state.network ++ effects.outgoing + } := by + simp [MultiNodeTransitionSystem.next, found, step, setNode] + +/-- One clean delivery through the network composition. -/ +theorem next_deliver + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + {state : MultiNodeTransitionSystem.State Node CleanState Message} + {envelope : Envelope Node Message} {before after : CleanState} + {effects : Outputs Node Message Notification} + (queued : state.network.contains envelope = true) + (found : nodeState state envelope.target = some before) + (step + : (protocol.step (Capabilities.record envelope.target) envelope.target before + (protocol.receive envelope.source envelope.payload)).run + {} + = some (after, effects)) + : MultiNodeTransitionSystem.next protocol state (.deliver envelope) + = some + { + setNode state envelope.target after with + network := removeOne envelope state.network ++ effects.outgoing + } := by + simp [MultiNodeTransitionSystem.next, queued, found, step, setNode, option_guard_bind] + +variable [LawfulBEq Node] + +/-- Admitted clean internal local steps lift to a guarded network run touching one node. -/ +theorem localRun_lift + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + (admit : List (Node × CleanState) -> Node -> Input -> Bool) + {node : Node} {others : List (Node × CleanState)} + : forall {start finish : CleanState} {inputs : List Input} + {sends : List (Envelope Node Message)}, + LocalRun protocol node start (inputs.map protocol.internal) finish sends + -> (forall input, input ∈ inputs -> admit others node input = true) + -> forall (state : MultiNodeTransitionSystem.State Node CleanState Message), + (state.nodes.map Prod.fst).Nodup + -> nodeState state node = some start + -> without state.nodes node = others + -> Run (guarded protocol admit) state (inputs.map (.local node)) + { setNode state node finish with network := state.network ++ sends } + | _, _, [], _, run, _, state, distinct, found, _ => by + cases run + rw [setNode_self distinct found] + have : ({ state with network := state.network ++ [] } + : MultiNodeTransitionSystem.State Node CleanState Message) = state := by + cases state; simp + rw [this] + exact .nil _ + | _, _, input :: inputs, _, run, admitted, state, distinct, found, rest => by + cases run with + | cons step tail => + rename_i middle effects sends + have first + : (guarded protocol admit).step state (.local node input) + = some { setNode state node middle with + network := state.network ++ effects.outgoing } := by + show guardedNext protocol admit state (.local node input) = _ + simp only [guardedNext, rest, admitted input (by simp), ite_true] + exact next_local protocol found step + refine .cons first ?_ + have := localRun_lift protocol admit tail + (fun input' member => admitted input' (by simp [member])) + { setNode state node middle with network := state.network ++ effects.outgoing } + (by rw [keys_setNode]; exact distinct) + (nodeState_setNode found) + (by rw [← rest]; exact without_setNode state node middle) + simp only [setNode_network_setNode, List.append_assoc] at this + exact this + +end Lift + +section Simulation + +variable {Node Message LocalState Event CleanState LocalAction Notification Input : Type} + {machine : Machine Node Message LocalState Event} + +/-- The section bookkeeping invariant of one node's slot. -/ +def SlotInv (machine : Machine Node Message LocalState Event) (node : Node) + (slot : Slot Node Message LocalState) + : Prop := + match slot.entry with + | none => slot.inbox = none /\ machine.idle slot.current = true + | some start => + machine.idle start = true + /\ (forall envelope, slot.inbox = some envelope -> envelope.target = node) + /\ exists events, + SectionRun machine node start + (slot.inbox.map fun envelope => (envelope.source, envelope.payload)) + events slot.current + +/-- +A clean state simulates an event-granular state: equal networks whose messages satisfy +`msgInv`, distinct nodes, and +each node's clean state related to its slot's abstracted local state. +-/ +def Sim (machine : Machine Node Message LocalState Event) + (rel : Node -> CleanState -> LocalState -> Prop) + (msgInv : Envelope Node Message -> Prop) + (clean : MultiNodeTransitionSystem.State Node CleanState Message) + (state : State Node Message LocalState) + : Prop := + (clean.network = state.network + /\ forall envelope, envelope ∈ state.network -> msgInv envelope) + /\ (state.nodes.map Prod.fst).Nodup + /\ Keyed + (fun node cleanLocal slot => + rel node cleanLocal slot.base /\ SlotInv machine node slot) + clean.nodes state.nodes + +variable {rel : Node -> CleanState -> LocalState -> Prop} + {msgInv : Envelope Node Message -> Prop} + +theorem Sim.lookup [BEq Node] [LawfulBEq Node] + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state : State Node Message LocalState} {node : Node} + {slot : Slot Node Message LocalState} (sim : Sim machine rel msgInv clean state) + (found : nodeState state node = some slot) + : exists cleanLocal, + nodeState clean node = some cleanLocal + /\ rel node cleanLocal slot.base + /\ SlotInv machine node slot := + let ⟨cleanLocal, cleanFound, holds⟩ := sim.2.2.find found + ⟨cleanLocal, cleanFound, holds⟩ + +theorem Sim.cleanDistinct + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state : State Node Message LocalState} (sim : Sim machine rel msgInv clean state) + : (clean.nodes.map Prod.fst).Nodup := by + rw [sim.2.2.keys]; exact sim.2.1 + +theorem Sim.set [BEq Node] [LawfulBEq Node] + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state : State Node Message LocalState} {node : Node} {cleanLocal : CleanState} + {slot : Slot Node Message LocalState} (sim : Sim machine rel msgInv clean state) + (found : nodeState clean node = some cleanLocal) + (related : rel node cleanLocal slot.base) (holds : SlotInv machine node slot) + : Sim machine rel msgInv clean (setNode state node slot) := by + refine ⟨sim.1, by rw [keys_setNode]; exact sim.2.1, ?_⟩ + have := sim.2.2.set (node := node) (left := cleanLocal) (right := slot) ⟨related, holds⟩ + have same := setNode_self sim.cleanDistinct found + rw [← same] + exact this + +/-- Event steps keep the simulation with the same clean state. -/ +theorem event_sim [BEq Node] [BEq Message] [LawfulBEq Node] + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state after : State Node Message LocalState} {node : Node} {event : Event} + (sim : Sim machine rel msgInv clean state) + (step : next machine state (.event node event) = some after) + : Sim machine rel msgInv clean after := by + obtain ⟨slot, current, found, _, ran, rfl⟩ := next_event_inv step + obtain ⟨cleanLocal, cleanFound, related, holds⟩ := sim.lookup found + obtain ⟨current0, entry0, inbox0⟩ := slot + refine sim.set cleanFound ?_ ?_ + · cases entry0 <;> simpa [Slot.base] using related + · cases entry0 with + | none => + obtain ⟨hinbox, hidle⟩ := holds + simp only at hinbox + subst hinbox + exact ⟨hidle, by simp, [event], by simpa using SectionRun.single ran⟩ + | some start => + obtain ⟨hidle, htarget, events, hrun⟩ := holds + exact ⟨hidle, htarget, events ++ [event], hrun.snoc ran⟩ + +/-- Delivery steps keep the simulation with the same clean state. -/ +theorem deliver_sim [BEq Node] [BEq Message] [LawfulBEq Node] + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state after : State Node Message LocalState} {envelope : Envelope Node Message} + {event : Event} (sim : Sim machine rel msgInv clean state) + (step : next machine state (.deliver envelope event) = some after) + : Sim machine rel msgInv clean after := by + obtain ⟨_, slot, current, found, free, ran, rfl⟩ := next_deliver_inv step + obtain ⟨cleanLocal, cleanFound, related, holds⟩ := sim.lookup found + obtain ⟨current0, entry0, inbox0⟩ := slot + simp only at free + subst free + obtain ⟨_, hidle⟩ := holds + refine sim.set cleanFound (by simpa [Slot.base] using related) ?_ + exact ⟨hidle, by simp, [event], by simpa using SectionRun.single ran⟩ + +/-- Initial event-granular states are simulated by initial clean states over the same nodes. -/ +theorem init_sim + {protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input} + {admit : List (Node × CleanState) -> Node -> Input -> Bool} + (refinement : Refinement machine protocol admit) + : forall (nodes : List (Node × Slot Node Message LocalState)), + (forall entry, + entry ∈ nodes + -> entry.2.entry = none + /\ entry.2.inbox = none + /\ machine.init entry.1 entry.2.current) + -> exists cleanNodes : List (Node × CleanState), + Keyed + (fun node cleanLocal slot => + refinement.rel node cleanLocal slot.base /\ SlotInv machine node slot) + cleanNodes nodes + /\ forall entry, entry ∈ cleanNodes -> protocol.init entry.1 entry.2 + | [], _ => ⟨[], .nil, by simp⟩ + | (node, slot) :: rest, initial => by + obtain ⟨cleanRest, keyed, inits⟩ := + init_sim refinement rest fun entry member => initial entry (by simp [member]) + obtain ⟨free, empty, hinit⟩ := initial (node, slot) (by simp) + obtain ⟨hidle, cleanLocal, cleanInit, related⟩ := refinement.init_sound node _ hinit + refine ⟨(node, cleanLocal) :: cleanRest, .cons ⟨?_, ?_⟩ keyed, ?_⟩ + · have free' : slot.entry = none := free + simp only [Slot.base, free', Option.getD_none]; exact related + · have free' : slot.entry = none := free + unfold SlotInv; rw [free']; exact ⟨empty, hidle⟩ + · intro entry member + simp only [List.mem_cons] at member + rcases member with rfl | member + · exact cleanInit + · exact inits entry member + +theorem Sim.release [BEq Node] [LawfulBEq Node] + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state : State Node Message LocalState} {node : Node} {cleanFinish : CleanState} + {finish : LocalState} (pending sends : List (Envelope Node Message)) + (sim : Sim machine rel msgInv clean state) (related : rel node cleanFinish finish) + (idle : machine.idle finish = true) + (valid : forall envelope, envelope ∈ pending ++ sends -> msgInv envelope) + : Sim machine rel msgInv + { setNode clean node cleanFinish with network := pending ++ sends } + { + setNode state node { current := finish } with + network := pending ++ sends + } := by + refine ⟨⟨rfl, valid⟩, ?_, ?_⟩ + · show ((setNode state node { current := finish }).nodes.map Prod.fst).Nodup + rw [keys_setNode]; exact sim.2.1 + · show Keyed _ (setNode clean node cleanFinish).nodes (setNode state node { current := finish }).nodes + exact sim.2.2.set (left := cleanFinish) (right := { current := finish }) + ⟨related, ⟨rfl, idle⟩⟩ + +theorem mem_of_mem_removeOne {α : Type _} [BEq α] {value item : α} + : forall {items : List α}, item ∈ removeOne value items -> item ∈ items + | [], member => member + | head :: tail, member => by + unfold removeOne at member + split at member + · exact List.mem_cons_of_mem _ member + · simp only [List.mem_cons] at member ⊢ + rcases member with rfl | member + · exact Or.inl rfl + · exact Or.inr (mem_of_mem_removeOne member) + +/-- A release is matched by the section's clean local run, keeping the simulation. -/ +theorem release_sim [BEq Node] [BEq Message] [LawfulBEq Node] [LawfulBEq Message] + {protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input} + {admit : List (Node × CleanState) -> Node -> Input -> Bool} + (refinement : Refinement machine protocol admit) + {clean : MultiNodeTransitionSystem.State Node CleanState Message} + {state after : State Node Message LocalState} {node : Node} + (sim : Sim machine refinement.rel refinement.msgInv clean state) + (step : next machine state (.release node) = some after) + : exists chunk clean', + Run (guarded protocol admit) clean chunk clean' + /\ Sim machine refinement.rel refinement.msgInv clean' after := by + obtain ⟨slot, start, finish, sends, pending, found, held, closed, hidle, hinbox, rfl⟩ := + next_release_inv step + obtain ⟨cleanLocal, cleanFound, related, holds⟩ := sim.lookup found + obtain ⟨current0, entry0, inbox0⟩ := slot + simp only at held + subst held + obtain ⟨hstart, htarget, events, hrun⟩ := holds + have relStart : refinement.rel node cleanLocal start := related + have others := (sim.2.2.without (node := node)).map_flip (f := Slot.base) + (other := fun other local_ cleanOther => refinement.rel other cleanOther local_) + (fun _ _ _ holds => holds.1) + have received : forall source message, + (inbox0.map fun envelope => (envelope.source, envelope.payload)) = some (source, message) + -> refinement.msgInv ⟨source, node, message⟩ := by + intro source message hsome + rcases hinbox with ⟨hnone, _⟩ | ⟨envelope, hin, queued, _⟩ + · simp only at hnone; subst hnone; simp at hsome + · simp only at hin; subst hin + simp only [Option.map_some, Option.some.injEq, Prod.mk.injEq] at hsome + obtain ⟨rfl, rfl⟩ := hsome + have target := htarget envelope rfl + obtain ⟨source, target', payload⟩ := envelope + simp only at target + subst target + exact sim.1.2 _ (List.contains_iff_mem.mp queued) + obtain ⟨inputs, cleanFinish, localRun, relFinish, admitted, sent⟩ := + refinement.section_sound node start _ events current0 finish sends cleanLocal _ _ hstart + relStart received hrun closed hidle others + have distinct := sim.cleanDistinct + have valid : forall pending, (forall envelope, envelope ∈ pending -> envelope ∈ state.network) + -> forall envelope, envelope ∈ pending ++ sends -> refinement.msgInv envelope := by + intro pending sub envelope member + rcases List.mem_append.mp member with member | member + · exact sim.1.2 _ (sub _ member) + · exact sent _ member + rcases hinbox with ⟨hnone, rfl⟩ | ⟨envelope, hsome, queued, rfl⟩ + · simp only at hnone + subst hnone + simp only [Option.map_none, Option.toList_none, List.nil_append] at localRun + refine ⟨inputs.map (.local node), _, ?_, sim.release state.network sends relFinish hidle + (valid _ fun _ member => member)⟩ + have := localRun_lift protocol admit localRun admitted clean distinct cleanFound rfl + rw [sim.1.1] at this + exact this + · simp only at hsome + subst hsome + have htgt : envelope.target = node := htarget envelope rfl + subst htgt + simp only [Option.map_some, Option.toList_some, List.singleton_append] at localRun + cases localRun with + | cons first rest => + rename_i middle effects restSends + refine ⟨.deliver envelope :: inputs.map (.local envelope.target), _, ?_, + sim.release (removeOne envelope state.network) _ relFinish hidle + (valid _ fun _ member => mem_of_mem_removeOne member)⟩ + have hqueued : clean.network.contains envelope = true := by rw [sim.1.1]; exact queued + refine .cons (show guardedNext protocol admit clean (.deliver envelope) = _ from + next_deliver protocol hqueued cleanFound first) ?_ + have := localRun_lift protocol admit rest admitted + { setNode clean envelope.target middle with + network := removeOne envelope clean.network ++ effects.outgoing } + (by show ((setNode clean envelope.target middle).nodes.map Prod.fst).Nodup + rw [keys_setNode]; exact distinct) + (nodeState_setNode cleanFound) + (without_setNode clean envelope.target middle) + simp only [setNode_network_setNode, List.append_assoc] at this + rw [← sim.1.1] + exact this + +end Simulation diff --git a/lean/common/CCF/Proofs/SectionsObservation.lean b/lean/common/CCF/Proofs/SectionsObservation.lean new file mode 100644 index 000000000000..7629f9b9ac88 --- /dev/null +++ b/lean/common/CCF/Proofs/SectionsObservation.lean @@ -0,0 +1,275 @@ +module + +public import CCF.Proofs.Sections +public import CCF.Observation + +@[expose] public section + +namespace CCF.Sections + +/-! +From the lifting step to observation-point refinement: every observation list accepted +by the event-granular network is explained by one trace of the guarded clean network, +and therefore of any specification whose initial states and steps include the guarded +network's. At each lock-taking event, the node's clean state is related by `R` to the +observed declared state. +-/ + +open MultiNodeTransitionSystem (nodeState) +open Execution (Run StepsFrom) +open ObservationRefinement (Observation) + +section Lists + +variable {system : TransitionSystem} + +theorem stepsFrom_append + : forall (start middle : system.State) + (first second : List (system.Action × system.State)), + (start :: first.map Prod.snd)[first.length]? = some middle + -> StepsFrom system start first + -> StepsFrom system middle second + -> StepsFrom system start (first ++ second) + | start, middle, [], second, last, _, valid => by + simp only [List.map_nil, List.length_nil, List.getElem?_cons_zero, + Option.some.injEq] at last + subst last + exact valid + | _, middle, (_, after) :: rest, second, last, ⟨step, valid⟩, tail => + ⟨step, stepsFrom_append after middle rest second (by simpa using last) valid tail⟩ + +theorem run_stepsFrom {start finish : system.State} {actions : List system.Action} + (run : Run system start actions finish) + : exists steps : List (system.Action × system.State), + StepsFrom system start steps + /\ (start :: steps.map Prod.snd)[steps.length]? = some finish := by + induction run with + | nil => exact ⟨[], trivial, by simp⟩ + | @cons _ middle _ action _ step _ ih => + obtain ⟨steps, valid, last⟩ := ih + exact ⟨(action, middle) :: steps, ⟨step, valid⟩, by simpa using last⟩ + +theorem getElem?_shift + : forall (start middle : system.State) + (first second : List (system.Action × system.State)) (position : Nat), + (start :: first.map Prod.snd)[first.length]? = some middle + -> (start :: (first ++ second).map Prod.snd)[first.length + position]? + = (middle :: second.map Prod.snd)[position]? + | start, middle, [], second, position, last => by + simp only [List.map_nil, List.length_nil, List.getElem?_cons_zero, + Option.some.injEq] at last + subst last + simp + | _, middle, (_, after) :: rest, second, position, last => by + simp only [List.cons_append, List.map_cons, List.length_cons, + List.getElem?_cons_succ] at last ⊢ + rw [show rest.length + 1 + position = (rest.length + position) + 1 by omega, + List.getElem?_cons_succ] + exact getElem?_shift after middle rest second position last + +end Lists + +variable + {Node Message LocalState Event CleanState LocalAction Notification Input Declared + : Type} + [BEq Node] [BEq Message] + {machine : Machine Node Message LocalState Event} + {protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message Notification + Input} + {admit : List (Node × CleanState) -> Node -> Input -> Bool} + +/-- Recorded guarded steps are recorded steps of any system that includes them. -/ +theorem stepsFrom_embed + {specInit : MultiNodeTransitionSystem.State Node CleanState Message -> Prop} + {specStep + : MultiNodeTransitionSystem.State Node CleanState Message + -> MultiNodeTransitionSystem.Action Node Message Input + -> Option (MultiNodeTransitionSystem.State Node CleanState Message)} + (embeds + : forall clean action clean', + guardedNext protocol admit clean action = some clean' + -> specStep clean action = some clean') + : forall clean + (steps + : List + ((guarded protocol admit).Action × (guarded protocol admit).State)), + StepsFrom (guarded protocol admit) clean steps + -> StepsFrom ⟨_, _, specInit, specStep⟩ clean steps + | _, [], _ => trivial + | clean, (action, after) :: rest, ⟨step, valid⟩ => + ⟨embeds clean action after step, stepsFrom_embed embeds after rest valid⟩ + +variable [LawfulBEq Node] [LawfulBEq Message] + +/-- The core induction: emitted observations are read off one guarded clean run. -/ +theorem emits_sim (refinement : Refinement machine protocol admit) + (declare : LocalState -> Declared) (R : Node -> CleanState -> Declared -> Prop) + (factors + : forall node clean local_, + refinement.rel node clean local_ + -> machine.idle local_ = true + -> R node clean (declare local_)) + (frame + : forall node local_ received event local', + machine.idle local_ = true + -> machine.step node local_ received event = some local' + -> machine.opens event = true + -> forall clean, R node clean (declare local_) -> R node clean (declare local')) + {start finish : State Node Message LocalState} + {actions : List (Action Node Message Event)} + {observations : List (Observation Node Event Declared)} + (emits : Emits machine declare start actions finish observations) + : forall clean, + Sim machine refinement.rel refinement.msgInv clean start + -> exists (steps + : List + ((guarded protocol admit).Action + × (guarded protocol admit).State)) (index : Nat -> Nat), + StepsFrom (guarded protocol admit) clean steps + /\ (forall i j, i <= j -> index i <= index j) + /\ forall (i : Nat) (observation : Observation Node Event Declared), + observations[i]? = some observation + -> machine.opens observation.event = true + -> exists state cleanLocal, + (clean :: steps.map Prod.snd)[index i]? = some state + /\ nodeState state observation.node = some cleanLocal + /\ R observation.node cleanLocal observation.declared := by + induction emits with + | nil => + intro clean _ + exact ⟨[], fun _ => 0, trivial, fun _ _ _ => Nat.le_refl _, by simp⟩ + | @event before middle _ node event slot _ _ step found _ ih => + intro clean sim + obtain ⟨steps, index, valid, monotone, points⟩ := ih clean (event_sim sim step) + refine ⟨steps, fun i => if i = 0 then 0 else index (i - 1), valid, ?_, ?_⟩ + · intro i j ordered + by_cases zero : i = 0 + · simp [zero] + · have : j ≠ 0 := by omega + simp only [zero, this, ite_false] + exact monotone _ _ (by omega) + · intro i observation found' opens + cases i with + | zero => + simp only [List.getElem?_cons_zero, Option.some.injEq] at found' + subst found' + obtain ⟨slot0, current, found0, allowed, ran, rfl⟩ := next_event_inv step + obtain ⟨cleanLocal, cleanFound, related, holds⟩ := sim.lookup found0 + have free : slot0.entry = none := by + simp only at opens + simpa [opens] using allowed + have same := (nodeState_setNode found0).symm.trans found + simp only [Option.some.injEq] at same + subst same + have hidle : machine.idle slot0.current = true := by + unfold SlotInv at holds; rw [free] at holds; exact holds.2 + refine ⟨clean, cleanLocal, by simp, cleanFound, ?_⟩ + show R node cleanLocal (declare current) + have : slot0.base = slot0.current := by simp [Slot.base, free] + exact frame node _ none event current hidle ran opens _ + (factors _ _ _ (this ▸ related) hidle) + | succ i => + simp only [List.getElem?_cons_succ] at found' + simp only [Nat.add_one_ne_zero, ite_false, Nat.add_sub_cancel] + exact points i observation found' opens + | @deliver before middle _ envelope event slot _ _ step found _ ih => + intro clean sim + obtain ⟨steps, index, valid, monotone, points⟩ := ih clean (deliver_sim sim step) + refine ⟨steps, fun i => if i = 0 then 0 else index (i - 1), valid, ?_, ?_⟩ + · intro i j ordered + by_cases zero : i = 0 + · simp [zero] + · have : j ≠ 0 := by omega + simp only [zero, this, ite_false] + exact monotone _ _ (by omega) + · intro i observation found' opens + cases i with + | zero => + simp only [List.getElem?_cons_zero, Option.some.injEq] at found' + subst found' + obtain ⟨_, slot0, current, found0, free, ran, rfl⟩ := next_deliver_inv step + obtain ⟨cleanLocal, cleanFound, related, holds⟩ := sim.lookup found0 + have same := (nodeState_setNode found0).symm.trans found + simp only [Option.some.injEq] at same + subst same + have hidle : machine.idle slot0.current = true := by + unfold SlotInv at holds; rw [free] at holds; exact holds.2 + refine ⟨clean, cleanLocal, by simp, cleanFound, ?_⟩ + show R envelope.target cleanLocal (declare current) + have : slot0.base = slot0.current := by simp [Slot.base, free] + exact frame _ _ _ event current hidle ran opens _ + (factors _ _ _ (this ▸ related) hidle) + | succ i => + simp only [List.getElem?_cons_succ] at found' + simp only [Nat.add_one_ne_zero, ite_false, Nat.add_sub_cancel] + exact points i observation found' opens + | @release before middle _ node _ _ step _ ih => + intro clean sim + obtain ⟨chunk, clean', run, sim'⟩ := release_sim refinement sim step + obtain ⟨first, valid, last⟩ := run_stepsFrom run + obtain ⟨second, index, valid', monotone, points⟩ := ih clean' sim' + refine ⟨first ++ second, fun i => first.length + index i, + stepsFrom_append _ _ _ _ last valid valid', ?_, ?_⟩ + · intro i j ordered + exact Nat.add_le_add_left (monotone _ _ ordered) _ + · intro i observation found' opens + rw [getElem?_shift (system := guarded protocol admit) _ _ first second _ last] + exact points i observation found' opens + +/-- +Observation-point refinement from the lifting step. Given a `Refinement` whose relation +implies `R` of the declared part at idle states, and whose lock-taking events preserve +`R` of the declared part when they open a section, every observation list accepted over +the nodes `keys` is explained by one trace of any specification over the same states +whose initial states include the clean network's initial states over `keys`, and whose +steps include the guarded clean network's steps. +-/ +theorem observation_refines (refinement : Refinement machine protocol admit) + (declare : LocalState -> Declared) (R : Node -> CleanState -> Declared -> Prop) + (factors + : forall node clean local_, + refinement.rel node clean local_ + -> machine.idle local_ = true + -> R node clean (declare local_)) + (frame + : forall node local_ received event local', + machine.idle local_ = true + -> machine.step node local_ received event = some local' + -> machine.opens event = true + -> forall clean, R node clean (declare local_) -> R node clean (declare local')) + (keys : List Node) + (specInit : MultiNodeTransitionSystem.State Node CleanState Message -> Prop) + (specStep + : MultiNodeTransitionSystem.State Node CleanState Message + -> MultiNodeTransitionSystem.Action Node Message Input + -> Option (MultiNodeTransitionSystem.State Node CleanState Message)) + (initEmbeds + : forall clean, + (MultiNodeTransitionSystem.lift protocol).init clean + -> clean.nodes.map Prod.fst = keys + -> specInit clean) + (stepEmbeds + : forall clean action clean', + guardedNext protocol admit clean action = some clean' + -> specStep clean action = some clean') + (observations : List (Observation Node Event Declared)) + (accepted : Accepts machine declare keys observations) + : ObservationRefinement.Refines ⟨_, _, specInit, specStep⟩ nodeState R machine.opens + observations := by + obtain ⟨start, actions, finish, initial, hkeys, emits, _⟩ := accepted + obtain ⟨distinct, empty, slots⟩ := initial + obtain ⟨cleanNodes, keyed, inits⟩ := init_sim refinement start.nodes slots + have sim : Sim machine refinement.rel refinement.msgInv { nodes := cleanNodes, network := [] } start := + ⟨⟨empty.symm, by simp [empty]⟩, distinct, keyed⟩ + obtain ⟨steps, index, valid, monotone, points⟩ := + emits_sim refinement declare R factors frame emits _ sim + have cleanKeys : cleanNodes.map Prod.fst = keys := keyed.keys.trans hkeys + have initialized : specInit { nodes := cleanNodes, network := [] } := + initEmbeds _ ⟨by rw [cleanKeys, ← hkeys]; exact distinct, rfl, inits⟩ cleanKeys + refine ⟨Execution.ofSteps (system := ⟨_, _, specInit, specStep⟩) _ steps initialized + (stepsFrom_embed stepEmbeds _ steps valid), index, monotone, ?_⟩ + intro i observation found opens + simpa only [Execution.ofSteps_stateAt] using points i observation found opens + +end CCF.Sections diff --git a/lean/common/CCF/Sections.lean b/lean/common/CCF/Sections.lean new file mode 100644 index 000000000000..ac3d6a065ecb --- /dev/null +++ b/lean/common/CCF/Sections.lean @@ -0,0 +1,341 @@ +module + +public import CCF.MultiNodeTransitionSystem +public import CCF.Execution +public import CCF.Observation + +@[expose] public section + +namespace CCF.Sections + +/-! +Event-granular nodes with critical sections, and their refinement obligation +towards a `MultiNodeTransitionSystem.Protocol`. + +A node machine takes one step per implementation event; a step is a partial function +of the node's local state, the delivered message (if any) and the event, and emits +nothing. The first event of a section takes the node's lock and may consume one queued +envelope. A silent `release` step runs the machine's `close` on the node's local state +and the other nodes' abstracted local states (which it may read, for example to find a +committed prefix to install), yielding the state after the section's untraced trailing +code and the section's sends in order; release then removes the consumed envelope from +the network and publishes the sends. + +A clean state simulates an event-granular state when the networks agree and each +node's clean state is related, by the refinement's `rel`, to the node's state at lock +acquisition (`entry`), or to its current state when it holds no lock. `Refinement` +packages the local obligation: every complete section from an idle state corresponds to +clean local steps with the same sends, each admitted by `admit`. The lifting theorems are +in `CCF.Proofs.Sections` and `CCF.Proofs.SectionsObservation`. +-/ + +open MultiNodeTransitionSystem (nodeState removeOne) + +/-- An event-granular node. -/ +structure Machine (Node Message LocalState Event : Type) where + /-- Initial local states. -/ + init : Node -> LocalState -> Prop + /-- Whether no section is open in this state. -/ + idle : LocalState -> Bool + /-- Events that take the lock: they may only occur outside a section. -/ + opens : Event -> Bool + /-- One event, with the message (and its sender) it delivers, if any. -/ + step : Node -> LocalState -> Option (Node × Message) -> Event -> Option LocalState + /-- + The section's untraced trailing code, and every send of the section, in order, given + the other nodes' abstracted local states. + -/ + close + : List (Node × LocalState) -> Node -> LocalState + -> Option (LocalState × List (Envelope Node Message)) + +/-- A node's machine state plus the bookkeeping of its open section. -/ +structure Slot (Node Message LocalState : Type) where + /-- The machine state after the latest event. -/ + current : LocalState + /-- Ghost: the state at lock acquisition; `none` when the lock is free. -/ + entry : Option LocalState := none + /-- The envelope consumed by the section's first event, still in the network. -/ + inbox : Option (Envelope Node Message) := none + +/-- Global states reuse the network composition's node table and network. -/ +abbrev State (Node Message LocalState : Type) := + MultiNodeTransitionSystem.State Node (Slot Node Message LocalState) Message + +/-- A node consumes an event, an event delivers a queued envelope, or a node releases. -/ +inductive Action (Node Message Event : Type) where + /-- The node takes an event without receiving a message. -/ + | event (node : Node) (event : Event) + /-- The envelope's target opens a section by receiving it. -/ + | deliver (envelope : Envelope Node Message) (event : Event) + /-- The node ends its section and publishes its sends. -/ + | release (node : Node) + +/-- Overwrite a node's table entry, like `MultiNodeTransitionSystem.next` does. -/ +def setNode {Node LocalState Message : Type} [BEq Node] + (state : MultiNodeTransitionSystem.State Node LocalState Message) (node : Node) + (value : LocalState) + : MultiNodeTransitionSystem.State Node LocalState Message := + { + state with + nodes := + state.nodes.map fun entry => if entry.1 == node then (node, value) else entry + } + +/-- The table without `node`. -/ +def without {Node LocalState : Type} [BEq Node] (nodes : List (Node × LocalState)) + (node : Node) + : List (Node × LocalState) := + nodes.filter fun entry => !(entry.1 == node) + +/-- Two node tables with the same keys in the same order, related entrywise. -/ +inductive Keyed {Node A B : Type} (related : Node -> A -> B -> Prop) + : List (Node × A) -> List (Node × B) -> Prop where + /-- Empty tables. -/ + | nil : Keyed related [] [] + /-- Related heads under one key, then related tails. -/ + | cons {node : Node} {left : A} {right : B} {lefts : List (Node × A)} + {rights : List (Node × B)} (holds : related node left right) + (rest : Keyed related lefts rights) + : Keyed related ((node, left) :: lefts) ((node, right) :: rights) + +/-- A slot's abstracted local state: its state at lock acquisition while it holds the lock. -/ +def Slot.base {Node Message LocalState : Type} (slot : Slot Node Message LocalState) + : LocalState := + slot.entry.getD slot.current + +/-- One global step of the event-granular network. -/ +def next {Node Message LocalState Event : Type} [BEq Node] [BEq Message] + (machine : Machine Node Message LocalState Event) + (state : State Node Message LocalState) + : Action Node Message Event -> Option (State Node Message LocalState) + | .event node event => do + let slot <- nodeState state node + guard (!machine.opens event || slot.entry.isNone) + let current <- machine.step node slot.current none event + pure + (setNode state node + { slot with current, entry := slot.entry.orElse fun _ => some slot.current }) + | .deliver envelope event => do + guard (state.network.contains envelope) + let node := envelope.target + let slot <- nodeState state node + guard (slot.entry.isNone) + let current <- machine.step node slot.current + (some (envelope.source, envelope.payload)) event + pure + (setNode state node + { current, entry := some slot.current, inbox := some envelope }) + | .release node => do + let slot <- nodeState state node + guard (slot.entry.isSome) + let (current, sends) <- machine.close + ((without state.nodes node).map + fun entry => (entry.1, entry.2.base)) + node slot.current + guard (machine.idle current) + let pending <- match slot.inbox with + | none => pure state.network + | some envelope => do + guard (state.network.contains envelope) + pure (removeOne envelope state.network) + pure { setNode state node { current } with network := pending ++ sends } + +/-- The event-granular network: distinct nodes, idle initial states, empty network. -/ +abbrev lift {Node Message LocalState Event : Type} [BEq Node] [BEq Message] + (machine : Machine Node Message LocalState Event) + : TransitionSystem where + State := State Node Message LocalState + Action := Action Node Message Event + init state := + (state.nodes.map Prod.fst).Nodup + /\ state.network = [] + /\ (forall entry, + entry ∈ state.nodes + -> entry.2.entry = none + /\ entry.2.inbox = none + /\ machine.init entry.1 entry.2.current) + step := next machine + +/-- Non-delivering events of one node. -/ +inductive Steps {Node Message LocalState Event : Type} + (machine : Machine Node Message LocalState Event) (node : Node) + : LocalState -> List Event -> LocalState -> Prop where + /-- No events. -/ + | nil (state : LocalState) : Steps machine node state [] state + /-- One event, then the rest. -/ + | cons {state middle finish : LocalState} {event : Event} {events : List Event} + (step : machine.step node state none event = some middle) + (rest : Steps machine node middle events finish) + : Steps machine node state (event :: events) finish + +/-- A section's events: a first event, possibly delivering `received`, then the rest. -/ +def SectionRun {Node Message LocalState Event : Type} + (machine : Machine Node Message LocalState Event) (node : Node) + (start : LocalState) (received : Option (Node × Message)) (events : List Event) + (finish : LocalState) + : Prop := + exists (first : Event) (rest : List Event) (middle : LocalState), + events = first :: rest + /\ machine.step node start received first = some middle + /\ Steps machine node middle rest finish + +/-- Clean local steps of one node, accumulating its sends. -/ +inductive LocalRun {Node LocalState LocalAction Message Notification Input : Type} + (protocol + : MultiNodeTransitionSystem.Protocol Node LocalState LocalAction Message + Notification Input) + (node : Node) + : LocalState -> List LocalAction -> LocalState -> List (Envelope Node Message) + -> Prop where + /-- No steps. -/ + | nil (state : LocalState) : LocalRun protocol node state [] state [] + /-- One enabled local step, then the rest. -/ + | cons {state middle finish : LocalState} {action : LocalAction} + {actions : List LocalAction} {effects : Outputs Node Message Notification} + {sends : List (Envelope Node Message)} + (step + : (protocol.step (Capabilities.record node) node state action).run {} + = some (middle, effects)) + (rest : LocalRun protocol node middle actions finish sends) + : LocalRun protocol node state (action :: actions) finish (effects.outgoing ++ sends) + +/-- +The clean network where an internal input of a node is enabled only if `admit` accepts +it given the other nodes' states. Specifications that guard internal inputs on global +state (for example, joining from a committed prefix) are reached from this one. +-/ +def guardedNext {Node Message CleanState LocalAction Notification Input : Type} + [BEq Node] [BEq Message] + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + (admit : List (Node × CleanState) -> Node -> Input -> Bool) + (state : MultiNodeTransitionSystem.State Node CleanState Message) + : MultiNodeTransitionSystem.Action Node Message Input + -> Option (MultiNodeTransitionSystem.State Node CleanState Message) + | .local node input => + if admit (without state.nodes node) node input then + MultiNodeTransitionSystem.next protocol state (.local node input) + else + none + | .deliver envelope => MultiNodeTransitionSystem.next protocol state (.deliver envelope) + +/-- `MultiNodeTransitionSystem.lift` with `guardedNext` steps. -/ +abbrev guarded {Node Message CleanState LocalAction Notification Input : Type} + [BEq Node] [BEq Message] + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + (admit : List (Node × CleanState) -> Node -> Input -> Bool) + : TransitionSystem := + { MultiNodeTransitionSystem.lift protocol with step := guardedNext protocol admit } + +/-- +The local obligation, relative to a relation `rel` between clean and machine local +states (which also carries any local invariant) and an invariant `msgInv` of messages in +flight. Initial machine states are idle and related to clean initial states. Every +complete section from an idle state related to `clean`, which received a message +satisfying `msgInv` (if any), closed given other nodes related to `cleanOthers`, +corresponds to: the clean receive of that message, if any, followed by admitted clean +internal inputs, from `clean` to a clean state related to the released state, with +exactly the section's sends; and every send satisfies `msgInv`. +-/ +structure Refinement + {Node Message LocalState Event CleanState LocalAction Notification Input : Type} + (machine : Machine Node Message LocalState Event) + (protocol + : MultiNodeTransitionSystem.Protocol Node CleanState LocalAction Message + Notification Input) + (admit : List (Node × CleanState) -> Node -> Input -> Bool) where + /-- What every machine message in flight satisfies. -/ + msgInv : Envelope Node Message -> Prop + /-- Relates a node's clean state to its machine state. -/ + rel : Node -> CleanState -> LocalState -> Prop + /-- Initial states are idle and related to a clean initial state. -/ + init_sound + : forall node state, + machine.init node state + -> machine.idle state = true + /\ exists clean, protocol.init node clean /\ rel node clean state + /-- Every complete section is an admitted clean local run with the same sends. -/ + section_sound + : forall node start received events middle finish sends clean + (others : List (Node × LocalState)) + (cleanOthers : List (Node × CleanState)), + machine.idle start = true + -> rel node clean start + -> (forall source message, + received = some (source, message) -> msgInv ⟨source, node, message⟩) + -> SectionRun machine node start received events middle + -> machine.close others node middle = some (finish, sends) + -> machine.idle finish = true + -> Keyed (fun other local_ cleanOther => rel other cleanOther local_) others + cleanOthers + -> exists (inputs : List Input) (clean' : CleanState), + LocalRun protocol node clean + ((received.map + fun (source, message) => protocol.receive source message).toList + ++ inputs.map protocol.internal) + clean' sends + /\ rel node clean' finish + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall envelope, envelope ∈ sends -> msgInv envelope + +open ObservationRefinement (Observation) + +/-- +`Emits machine declare start actions finish observations`: the actions run from `start` +to `finish`, and every event action emits one observation carrying the acting node's +declared state after the event. Releases emit nothing. +-/ +inductive Emits {Node Message LocalState Event Declared : Type} [BEq Node] [BEq Message] + (machine : Machine Node Message LocalState Event) (declare : LocalState -> Declared) + : State Node Message LocalState -> List (Action Node Message Event) + -> State Node Message LocalState -> List (Observation Node Event Declared) + -> Prop where + /-- No actions. -/ + | nil (state : State Node Message LocalState) : Emits machine declare state [] state [] + /-- A node takes an event. -/ + | event {before middle after : State Node Message LocalState} {node : Node} + {event : Event} {slot : Slot Node Message LocalState} + {actions : List (Action Node Message Event)} + {observations : List (Observation Node Event Declared)} + (step : next machine before (.event node event) = some middle) + (found : MultiNodeTransitionSystem.nodeState middle node = some slot) + (rest : Emits machine declare middle actions after observations) + : Emits machine declare before (.event node event :: actions) after + (⟨node, event, declare slot.current⟩ :: observations) + /-- A node receives an envelope with an event. -/ + | deliver {before middle after : State Node Message LocalState} + {envelope : Envelope Node Message} {event : Event} + {slot : Slot Node Message LocalState} {actions : List (Action Node Message Event)} + {observations : List (Observation Node Event Declared)} + (step : next machine before (.deliver envelope event) = some middle) + (found : MultiNodeTransitionSystem.nodeState middle envelope.target = some slot) + (rest : Emits machine declare middle actions after observations) + : Emits machine declare before (.deliver envelope event :: actions) after + (⟨envelope.target, event, declare slot.current⟩ :: observations) + /-- A node releases its lock. -/ + | release {before middle after : State Node Message LocalState} {node : Node} + {actions : List (Action Node Message Event)} + {observations : List (Observation Node Event Declared)} + (step : next machine before (.release node) = some middle) + (rest : Emits machine declare middle actions after observations) + : Emits machine declare before (.release node :: actions) after observations + +/-- +Some run of the network, from an initial state over exactly the nodes `keys`, emits +exactly `observations` and ends with every lock released. +-/ +def Accepts {Node Message LocalState Event Declared : Type} [BEq Node] [BEq Message] + (machine : Machine Node Message LocalState Event) (declare : LocalState -> Declared) + (keys : List Node) (observations : List (Observation Node Event Declared)) + : Prop := + exists start actions finish, + (lift machine).init start + /\ start.nodes.map Prod.fst = keys + /\ Emits machine declare start actions finish observations + /\ forall entry, entry ∈ finish.nodes -> entry.2.entry = none + +end CCF.Sections diff --git a/lean/common/README.md b/lean/common/README.md index 8eb87ff37d08..4f6965f64685 100644 --- a/lean/common/README.md +++ b/lean/common/README.md @@ -2,21 +2,25 @@ The `ccf_common` Lake package exposes protocol-independent definitions in the `CCF` namespace. -| Module | Purpose | -| ------------------------------- | ------------------------------------------------------------ | -| `CCF.Capabilities` | Envelopes, ordered outputs, effects, and recording callbacks | -| `CCF.TransitionSystem` | Initial states, enabled transitions, and reachability | -| `CCF.MultiNodeTransitionSystem` | Local protocols composed into a message-passing network | -| `CCF.Execution` | Finite runs and finite or infinite execution traces | -| `CCF.Parsec` | Stateful Parsec combinators over arrays of arbitrary events | -| `CCF.Architecture` | Checks of specification import layering | -| `CCF.Seq` | Possibly infinite sequences (replaces Mathlib `Stream'.Seq`) | -| `CCF.Finset` | Finite sets as strictly sorted lists (replaces `Finset`) | -| `CCF.Function` | Point updates of functions (replaces `Function.update`) | -| `CCF.Proofs.Execution` | Execution constructors and theorems about runs and traces | -| `CCF.Proofs.Finset` | Lemmas about the `CCF.Finset` operations | -| `CCF.Proofs.Function` | Lemmas about point updates | -| `CCF.Proofs.Seq` | Lemmas about sequence access and membership | +| Module | Purpose | +| -------------------------------- | ------------------------------------------------------------ | +| `CCF.Capabilities` | Envelopes, ordered outputs, effects, and recording callbacks | +| `CCF.TransitionSystem` | Initial states, enabled transitions, and reachability | +| `CCF.MultiNodeTransitionSystem` | Local protocols composed into a message-passing network | +| `CCF.Execution` | Finite runs and finite or infinite execution traces | +| `CCF.Observation` | Refinement of a specification at observed trace events | +| `CCF.Sections` | Event-granular nodes whose lock holds refine local steps | +| `CCF.Parsec` | Stateful Parsec combinators over arrays of arbitrary events | +| `CCF.Architecture` | Checks of specification import layering | +| `CCF.Seq` | Possibly infinite sequences (replaces Mathlib `Stream'.Seq`) | +| `CCF.Finset` | Finite sets as strictly sorted lists (replaces `Finset`) | +| `CCF.Function` | Point updates of functions (replaces `Function.update`) | +| `CCF.Proofs.Execution` | Execution constructors and theorems about runs and traces | +| `CCF.Proofs.Finset` | Lemmas about the `CCF.Finset` operations | +| `CCF.Proofs.Function` | Lemmas about point updates | +| `CCF.Proofs.Seq` | Lemmas about sequence access and membership | +| `CCF.Proofs.Sections` | Lock-hold networks simulated by the clean network | +| `CCF.Proofs.SectionsObservation` | Accepted section runs establish `CCF.Observation` refinement | `CCF.Execution.TraceImpl system` records an `init` state and a possibly infinite `steps` sequence pairing each action with its destination state. `CCF.Execution.Trace system` is the subtype whose `TraceImpl.Valid` proof establishes initialization and every recorded transition. From bdd494bd7b7dd833d66cc69dc4d4516d586fdd3d Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:07:14 +0000 Subject: [PATCH 05/25] Add the reviewed trace-validation surface for cft.h This is the part of trace validation a reviewer reads: the declared state (one field per cft.h member, with the ledger the node holds after its snapshot base), the decoded trace points, the actions they map to, what each trace point is compared with, and the state refinement mapping `abs` / `related` from a clean node state to a declared state. Everything later in the series is checked against these definitions. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 1 + .../Consensus/TraceValidation/Abs.lean | 180 +++++++++++++++ .../Consensus/TraceValidation/Action.lean | 30 +++ .../Consensus/TraceValidation/Event.lean | 105 +++++++++ .../Consensus/TraceValidation/Observe.lean | 210 ++++++++++++++++++ .../Consensus/TraceValidation/State.lean | 161 ++++++++++++++ 6 files changed, 687 insertions(+) create mode 100644 lean/consensus/Consensus/TraceValidation/Abs.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Action.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Event.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Observe.lean create mode 100644 lean/consensus/Consensus/TraceValidation/State.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 5d35ffae1b5b..71e46bf72469 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -2,6 +2,7 @@ module public import Consensus.Properties public import Consensus.Replay.Reduction +public import Consensus.TraceValidation.Abs import Consensus.Tests.CanonicalTraces import Consensus.Tests.ReplayDelivery diff --git a/lean/consensus/Consensus/TraceValidation/Abs.lean b/lean/consensus/Consensus/TraceValidation/Abs.lean new file mode 100644 index 000000000000..2e0c1d405ab5 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Abs.lean @@ -0,0 +1,180 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.Model +public import Consensus.TraceValidation.Observe +public import CCF.Observation + +@[expose] public section + +/-! +# State refinement mapping (reviewed) + +The declared state is `Consensus.TraceValidation.Exec.Declared`: one structure of `cft.h` +members per node, each field documented with the member it mirrors. This file maps it to +the clean model's node state; `accepted_refines` says an accepted trace is a behaviour of +the clean model under this mapping. + +`Declared.abs names d` is the clean `NodeState` that the declared state `d` stands for: +each clean field is a projection of declared fields. Node ids are strings in the +implementation and naturals in the clean model; `names` is the sorted table of the +trace's node ids, so the clean id is the rank and the clean order is the +implementation's `std::map` order. + +A node that joined from a snapshot holds only the ledger after the snapshot index +`base`, so `abs`'s log is that suffix, while the clean log is the whole log. Indexes +are absolute in both. + +`related names node c d` is the relation between the clean state `c` of `node` and its +declared state `d`: `d` is `node`'s, and, once `d` has a ledger entry, `c`'s log after +`base` is `abs`'s log, the snapshot's signature commits the node to the entries up to +`base` (`c`'s log has a signature at `base` in the snapshot view, and `c` has committed +it), and every other clean variable equals its `abs` value, except where the +implementation holds no value: + +* send and match indexes are related only on a primary, for the nodes in + `all_other_nodes` (the implementation has no entry for other nodes; the clean model + keeps a total function that it never reads there); +* vote sets are related only in the role that collects them (cft.h resets + `votes_for_me` when it starts collecting; the clean model keeps stale sets). + +Before its first ledger entry, without a snapshot, a node is related to any clean state +that has committed nothing: the clean initial state of the genesis primary (`initialNodeState`) already is +primary at term 2 with the configuration entry, while the implementation starts with no +role, view 0 and an empty ledger and gets there through `force_become_primary` and the +genesis `replicate`. +-/ + +namespace Consensus.TraceValidation + +open CCF (Finset) + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Declared Leadership NodeId Ev) + +/-- The trace's node ids, sorted; a node's clean id is its position. -/ +structure Names where + known : Array NodeId + +/-- The clean id of an implementation node id. Ids outside the table map past its end. -/ +def Names.id (names : Names) (node : NodeId) : NodeID := + (names.known.findIdx? (· == node)).getD (names.known.size + node.length) + +/-- The implementation node id of a clean id. -/ +def Names.name (names : Names) (node : NodeID) : NodeId := + names.known[node]?.getD s!"#{node}" + +def Names.set (names : Names) (nodes : List NodeId) : Finset NodeID := + Finset.ofList (nodes.map names.id) + +/-- `ccf::kv::LeadershipState` to the clean role. -/ +def absRole : Leadership -> Role + | .none => .none + | .follower => .follower + | .preVoteCandidate => .preVoteCandidate + | .candidate => .candidate + | .leader => .primary + +/-- +A ledger entry: a signature, or a transaction with the metadata its hooks reveal. The +clean request id is not observable and is always 0. +-/ +def absEntry (names : Names) (e : Exec.Entry) : Entry := + { + term := e.term + content := + if e.sig then + .signature + else + .transaction 0 + { + configuration := e.config.map fun ns => names.set (ns.map Prod.fst) + retirementConfirmations := names.set e.retired + } + } + +/-- +The clean state a declared state stands for, a field-by-field projection. Its log is the +entries the node holds: indexes `d.base + 1` to `d.lastIdx`. +-/ +def Exec.Declared.abs (names : Names) (d : Declared) : NodeState := + let peer (f : Exec.Peer -> Nat) (n : NodeID) : Nat := + match d.allOtherNodes.find? (fun (id, _) => names.id id == n) with + | some (_, p) => f p + | none => 0 + -- `votes_for_me` only counts the self-vote in configurations the node is in; + -- a (pre-vote) candidate has always voted for itself. + let votes := names.set (d.nodeId :: d.votesForMe.flatMap fun (_, vs, _) => vs) + { + role := absRole d.leadership + currentTerm := d.currentView + log := (d.ledger.toList.take (d.lastIdx - d.base)).map (absEntry names) + commitIndex := d.commitIdx + sentIndex := peer (·.sentIdx) + matchIndex := peer (·.matchIdx) + isNewFollower := d.isNewFollower + votedFor := d.votedFor.map names.id + primaryKnown := d.leaderId.isSome + votesGranted := votes + preVotesGranted := votes + retiredCommittedIndex := d.retiredCommittedIdx + } + +/-- The nodes whose send and match indexes the declared state holds: a primary's peers. -/ +def Exec.Declared.trackedPeers (names : Names) (d : Declared) : List NodeID := + if d.leadership == .leader then d.allOtherNodes.map fun (id, _) => names.id id else [] + +/-- +The clean log has the snapshot's signature at the base, in the base view, and has +committed it; after the base it is the held entries; and every other clean variable +equals its `abs` value, except where the implementation holds none. +-/ +def Exec.Declared.agrees (names : Names) (c : NodeState) (d : Declared) : Bool := + let a := d.abs names + (d.base == 0 + || c.log[d.base - 1]? == some { term := d.baseView, content := .signature }) + && d.base <= d.commitIdx + && c.role == a.role + && c.currentTerm == a.currentTerm + && c.log.drop d.base == a.log + && c.commitIndex == a.commitIndex + && (d.trackedPeers names).all + (fun n => c.sentIndex n == a.sentIndex n && c.matchIndex n == a.matchIndex n) + && c.isNewFollower == a.isNewFollower + && c.votedFor == a.votedFor + && c.primaryKnown == a.primaryKnown + && (a.role != .candidate || c.votesGranted == a.votesGranted) + && (a.role != .preVoteCandidate || c.preVotesGranted == a.preVotesGranted) + && c.retiredCommittedIndex == a.retiredCommittedIndex + +/-- The reviewed relation between a clean state and a declared state (see above). -/ +def related (names : Names) (node : NodeID) (c : NodeState) (d : Declared) : Bool := + names.id d.nodeId == node + && (d.agrees names c || (d.lastIdx == 0 && d.base == 0 && c.commitIndex == 0)) + +/-! ## Trace-wide parameters and observations -/ + +/-- Trace-wide parameters, computed by the decoder. -/ +structure Env where + /-- The trace's node ids, sorted. -/ + names : Names + /-- Every node's address, as in configuration hooks. -/ + addrs : List (Exec.NodeId × String) + /-- The genesis configuration: the node whose first event is `become_leader`. -/ + genesis : Finset NodeID + +/-- Events that take the lock: the observation points. -/ +def opens (e : Ev) : Bool := Exec.heads.contains e.function + +/-- One observation: the node, its event, and its declared state and label at the event. -/ +abbrev Obs := CCF.ObservationRefinement.Observation NodeID Ev (Declared × Exec.Label) + +/-- Every node's observed events are its stream, in order (by trace line). -/ +def streamsMatch (streams : List (NodeID × List Ev)) (obs : List Obs) : Bool := + streams.all + fun (k, evs) => + ((obs.filter (·.node == k)).map (·.event.line)) == evs.map (·.line) + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Action.lean b/lean/consensus/Consensus/TraceValidation/Action.lean new file mode 100644 index 000000000000..f8897011522b --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Action.lean @@ -0,0 +1,30 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Lean.Data.Json + +@[expose] public section + +/-! +# M_tv actions + +One action per trace event: the trace point reached and the event fields the +model consumes as input (see `Observe.inputFields`). The silent lock release is +`none : Option Action`. Each step also returns a `Label`: the values the model +computed at the trace point for the event's remaining non-state fields. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean + +structure Action where + point : String + inputs : List (String × Json) +deriving Inhabited + +abbrev Label := List (String × Json) + +end Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Event.lean b/lean/consensus/Consensus/TraceValidation/Event.lean new file mode 100644 index 000000000000..e37bd01e650a --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Event.lean @@ -0,0 +1,105 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Lean.Data.Json + +@[expose] public section + +/-! +# Trace events for messy-model trace validation + +Decoding only: one record per line, `{process_id, h_ts, msg}`. Command records +(`msg.cmd`) are driver provenance and are kept apart. Every other record is one +trace event of the node named by `msg.state.node_id` (or `msg.node_id` for +`retired_committed_tx`, which carries no snapshot). + +Events are split into one stream per node, ordered by `h_ts` within the node's +process. The global order across processes is never used. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean + +structure Ev where + file : String + line : Nat + process : String + hts : Nat + node : String + function : String + /-- The `msg` object, including `function` and `state`. -/ + msg : Json +deriving Inhabited + +def Ev.loc (e : Ev) : String := s!"{e.file}:{e.line} [{e.function}]" + +def Ev.keys (e : Ev) : List String := + match e.msg.getObj? with + | .ok o => o.toList.map Prod.fst |>.filter (· != "function") + | .error _ => [] + +def natural : Json -> Except String Nat + | .num { mantissa := .ofNat value, exponent := 0 } => pure value + | j => throw s!"expected natural number, got {j.compress}" + +def getNat (j : Json) (k : String) : Except String Nat := do + natural (← (j.getObjVal? k).mapError (fun e => s!"{k}: {e}")) + +def getStr (j : Json) (k : String) : Except String String := do + (← (j.getObjVal? k).mapError (fun e => s!"{k}: {e}")).getStr? + +structure Trace where + events : Array Ev + commands : Nat + records : Nat + +/-- Decode one ndjson capture. -/ +def decode (file input : String) : Except String Trace := do + let mut events := #[] + let mut commands := 0 + let mut records := 0 + let lines := input.splitOn "\n" + for raw in lines, line in [1:lines.length + 1] do + if raw.trimAscii.isEmpty then continue + let loc := s!"{file}:{line}" + let value ← (Json.parse raw).mapError (fun e => s!"{loc}: {e}") + records := records + 1 + let msg ← (value.getObjVal? "msg").mapError (fun e => s!"{loc}: {e}") + if (msg.getObjVal? "cmd").isOk then + commands := commands + 1 + continue + let process ← (getStr value "process_id").mapError (fun e => s!"{loc}: {e}") + let hts ← (getNat value "h_ts").mapError (fun e => s!"{loc}: {e}") + let function ← (getStr msg "function").mapError (fun e => s!"{loc}: {e}") + let node ← + (if function == "retired_committed_tx" then + getStr msg "node_id" + else do + getStr (← msg.getObjVal? "state") "node_id").mapError + (fun e => s!"{loc}: {e}") + events := events.push { file, line, process, hts, node, function, msg } + return { events, commands, records } + +def readTrace (path : System.FilePath) : IO (Except String Trace) := do + let input ← IO.FS.readFile path + return decode path.toString input + +/-- One stream per node, ordered by `h_ts`; a node must live in one process. -/ +def streams (trace : Trace) : Except String (List (String × Array Ev)) := do + let nodes := (trace.events.toList.map (·.node)).mergeSort.eraseDups + nodes.mapM + fun node => do + let evs := trace.events.filter (·.node == node) + let procs := (evs.toList.map (·.process)).eraseDups + unless procs.length == 1 do + throw s!"node {node} spans processes {procs}" + let sorted := evs.qsort (fun a b => a.hts < b.hts) + for i in [1:sorted.size] do + if sorted[i - 1]!.hts == sorted[i]!.hts then + throw s!"{sorted[i]!.loc}: duplicate h_ts {sorted[i]!.hts} in process {procs}" + return (node, sorted) + +end Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Observe.lean b/lean/consensus/Consensus/TraceValidation/Observe.lean new file mode 100644 index 000000000000..99f8b856e6bd --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Observe.lean @@ -0,0 +1,210 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Event +public import Consensus.TraceValidation.State +public import Consensus.TraceValidation.Action + +@[expose] public section + +/-! +# Trace validation surface (reviewed) + +Each trace event maps to exactly one M_tv action (`actionOf`). After the model +steps that action, the event is observed against the declared state (`Declared`) at the +trace point and the model's label (`observe`). Every field of every event is in +exactly one of these classes, or both of the last two: + +* `state`, and the per-point fields in `stateFields`: projections of `Declared`; +* `inputFields`: consumed by the action (message identity, untraced choices, + entry contents that only the hooks reveal); +* the label: values the model computed at the trace point (packets, indices). + +Depends only on the declared state, the action type and event decoding. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean + +/-- Fields an action consumes as input, by trace point. -/ +def inputFields : String -> List String + -- A receive's `from_node_id` and `packet` are labels: the delivered message's. + -- The dropped message is not delivered: it is named by the event. + | "drop_pending_to" => ["to_node_id", "packet"] + -- `packet.idx` is the untraced batch size's choice; `to_node_id` tells a retired + -- node's skipped send apart. Both are also labelled, so compared. + | "send_append_entries" => ["to_node_id", "packet"] + | "replicate_entry" => ["globally_committable"] + -- On the primary the entry content is only visible through its hooks. + | "retired_committed_tx" => ["retired_node_id"] + -- `idx` is input only for the out-of-lock hook, whose snapshot version is untraced. + | "add_configuration" => ["idx", "nodes"] + | "init_as_backup" => ["seqno", "view"] + | _ => [] + +def actionOf (e : Ev) : Except String Action := do + let inputs ← + (inputFields e.function).mapM + fun k => do + return (k, ← (e.msg.getObjVal? k).mapError fun _ => s!"input {k} missing") + return { point := e.function, inputs } + +/-- +An `add_configuration` while the node is uninitialised (no role, view 0) is the +snapshot-install hook, which runs outside the lock: a section of its own. +-/ +def outOfLock (s : Declared) (e : Ev) : Bool := + e.function == "add_configuration" && s.leadership == .none && s.currentView == 0 + +def optNat (k : String) (v : Option Nat) : List (String × Json) := + match v with + | some n => [(k, toJson n)] + | none => [] + +/-- `write_msgpack(aft::State)`: the snapshot every trace point but one carries. -/ +def snapshot (s : Declared) : List (String × Json) := + let ci := + match s.committable with + | [] => [] + | [a] => [a] + | a :: rest => [a, rest.getLast?.getD a] + [ + ("node_id", toJson s.nodeId), + ("current_view", toJson s.currentView), + ("last_idx", toJson s.lastIdx), + ("commit_idx", toJson s.commitIdx), + ("leadership_state", toJson s.leadership.name), + ("membership_state", toJson (if s.retired then "Retired" else "Active")) + ] + ++ (match s.retirementPhase with + | some p => [("retirement_phase", toJson p.name)] + | none => []) + ++ optNat "retirement_idx" s.retirementIdx + ++ optNat "retirement_committable_idx" s.retirementCommittableIdx + ++ optNat "retired_committed_idx" s.retiredCommittedIdx + ++ [("committable_indices", toJson ci)] + +def optId (v : Option NodeId) : Json := + match v with + | some id => toJson id + | none => Json.null + +/-- `write_msgpack(std::map)`: by configuration index, votes sorted. -/ +def votesJson (vs : List (Nat × List NodeId × Nat)) : Json := + toJson + (vs.map + fun (idx, votes, quorum) => + Json.mkObj + [ + ("idx", toJson idx), + ("quorum", toJson quorum), + ("votes", toJson (votes.mergeSort (· <= ·))) + ]) + +/-- +The `aft::Aft` protocol variables a trace point carries (`cft_trace_msgpack.h`), as +projections of `Declared`. A regular vote request carries `voted_for` and `leader_id`; a +pre-vote request carries neither. Every event of these points must carry them. +-/ +def carried (e : Ev) (s : Declared) : List (String × Json) := + let v := ("voted_for", optId s.votedFor) + let w := ("votes_for_me", votesJson s.votesForMe) + let l := ("leader_id", optId s.leaderId) + let n := ("is_new_follower", toJson s.isNewFollower) + let t := ("ticking", toJson s.ticking) + match e.function with + | "tick" + | "replicate_entry" + | "execute_append_entries_sync" + | "recv_propose_request_vote" => [t] + | "recv_append_entries" => [l, n] + | "recv_request_vote" => + match e.msg.getObjValD "packet" |>.getObjValD "msg" |>.getStr? with + | .ok "request_vote" => [v, l] + | _ => [] + | "recv_request_vote_response" => [w] + | "become_pre_vote_candidate" | "become_leader" => [w, l] + | "become_candidate" => [v, w, l] + | "become_follower" => [v, w, l, n] + | "commit" | "step_down_and_nominate_successor" => [l] + | _ => [] + +/-- Non-snapshot fields that are projections of `Declared` at the trace point. -/ +def stateFields (e : Ev) (s : Declared) : List (String × Json) := + let peerId := + if e.function == "recv_append_entries_response" then + getStr e.msg "from_node_id" + else + getStr e.msg "to_node_id" + let peer := + match peerId with + | .ok id => s.allOtherNodes.lookup id + | .error _ => none + [("configurations", configsJson s.configurations)] + ++ carried e s + ++ (match peer with + | some p => [("match_idx", toJson p.matchIdx), ("sent_idx", toJson p.sentIdx)] + | none => []) + ++ (match e.function with + | "retired_committed_tx" => [("node_id", toJson s.nodeId)] + | "replicate_entry" => + [("view", toJson s.currentView), ("seqno", toJson (s.lastIdx + 1))] + | _ => []) + +def compareObj (pfx : String) (model : List (String × Json)) (observed : Json) + : Except String Unit := do + let obs ← observed.getObj? + for (k, m) in model do + match obs.get? k with + | some o => + unless o == m do + throw s!"{pfx}{k}: observed {o.compress}, model {m.compress}" + | none => throw s!"{pfx}{k}: absent, model {m.compress}" + for (k, o) in obs.toList do + unless model.any (·.1 == k) do + throw s!"{pfx}{k}: observed {o.compress}, model has no such field" + +/-- Observe event `e` against the state `s` at its trace point and the model's label. -/ +def observe (e : Ev) (s : Declared) (label : Label) : Except String Unit := do + let obj ← e.msg.getObj? + let proj := stateFields e s + for (k, o) in obj.toList do + if k == "function" then continue + if k == "state" then compareObj "state." (snapshot s) o; continue + match proj.lookup k <|> label.lookup k with + | some m => + unless o == m do + throw s!"{k}: observed {o.compress}, model {m.compress}" + | none => + unless (inputFields e.function).contains k do + throw s!"{k}: observed {o.compress}, neither observed nor consumed by the model" + for (k, m) in label ++ carried e s do + unless obj.contains k do + throw s!"{k}: absent, model {m.compress}" + +/-- Whether event `e` is consistent with the declared state and label at its trace point. -/ +def consistent (e : Ev) (declared : Declared × Label) : Bool := + match observe e declared.1 declared.2 with + | .ok () => true + | .error _ => false + +/-! ## Lock-taking trace points -/ + +/-- Trace points that receive a message; they take the lock. -/ +def recvHeads : List String := + [ + "recv_append_entries", + "recv_append_entries_response", + "recv_request_vote", + "recv_request_vote_response", + "recv_propose_request_vote" + ] + +/-- Trace points that take the lock and open a section (`cft.h` takes it before them). -/ +def heads : List String := + recvHeads ++ ["tick", "replicate", "nomination", "init_as_backup", "drop_pending_to"] + +end Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/State.lean b/lean/consensus/Consensus/TraceValidation/State.lean new file mode 100644 index 000000000000..c44d4b6c01bb --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/State.lean @@ -0,0 +1,161 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Lean.Data.Json + +@[expose] public section + +/-! +# Declared state: the cft.h variables M_tv tracks (reviewed) + +One `Declared` state per node. Every field mirrors one implementation member, named +in its doc comment; there is no control, thread, lock or ghost state here. M_tv runs on +an extension of it (`Consensus.TraceValidation.Full`), which is not part of the reviewed +surface. `Consensus.TraceValidation.Observe` compares trace events against projections of +this structure only. + +The ledger is what the node holds: a node that joined from a snapshot holds only the +entries after the snapshot (`Ledger::init_idx`); the snapshot's index and view are +`base` and `baseView`. Every index-valued field is an absolute ledger index. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean + +abbrev NodeId := String + +/-- `ccf::kv::Configuration::Nodes`: node to address, ordered by node id. -/ +abbrev Nodes := List (NodeId × String) + +/-- `ccf::kv::LeadershipState`. -/ +inductive Leadership where + | none + | follower + | preVoteCandidate + | candidate + | leader +deriving DecidableEq, Repr, Inhabited + +/-- `ccf::kv::RetirementPhase`. -/ +inductive Phase where + | ordered + | signed + | completed + | retiredCommitted +deriving DecidableEq, Repr, Inhabited + +/-- `ccf::kv::Configuration`: `idx`, `nodes`, `rid`. -/ +structure Config where + idx : Nat + nodes : Nodes + rid : Nat +deriving DecidableEq, Repr, Inhabited + +/-- `Aft::NodeState` minus `node_info` (address, in `Config`) and `last_ack_timeout` (timer). -/ +structure Peer where + /-- `NodeState::sent_idx`. -/ + sentIdx : Nat + /-- `NodeState::match_idx`. -/ + matchIdx : Nat +deriving DecidableEq, Repr, Inhabited + +/-- A ledger entry, as far as consensus can see it through `Store` and hooks. -/ +structure Entry where + /-- The view the entry was written in (`get_term_internal` of its index). -/ + term : Nat + /-- `globally_committable`: a signature transaction. -/ + sig : Bool + /-- The `nodes` of the `ConfigurationChangeHook` the entry triggers, if any. -/ + config : Option Nodes := none + /-- Node ids of the retired_committed hook the entry triggers, if any. -/ + retired : List NodeId := [] +deriving DecidableEq, Repr, Inhabited + +structure Declared where + /-- `aft::State::node_id`. -/ + nodeId : NodeId + /-- `aft::State::current_view`. -/ + currentView : Nat := 0 + /-- `aft::State::last_idx`. -/ + lastIdx : Nat := 0 + /-- `aft::State::commit_idx`. -/ + commitIdx : Nat := 0 + /-- `aft::State::view_history.views`: start index of each view, view `v` at `views[v-1]`. -/ + views : Array Nat := #[] + /-- `aft::State::committable_indices`. -/ + committable : List Nat := [] + /-- `aft::State::leadership_state`. -/ + leadership : Leadership := .none + /-- `aft::State::membership_state == Retired`. -/ + retired : Bool := false + /-- `aft::State::retirement_phase`. -/ + retirementPhase : Option Phase := none + /-- `aft::State::retirement_idx`. -/ + retirementIdx : Option Nat := none + /-- `aft::State::retirement_committable_idx`. -/ + retirementCommittableIdx : Option Nat := none + /-- `aft::State::retired_committed_idx`. -/ + retiredCommittedIdx : Option Nat := none + /-- `Aft::voted_for`. -/ + votedFor : Option NodeId := none + /-- `Aft::leader_id`. -/ + leaderId : Option NodeId := none + /-- `Aft::votes_for_me`: configuration index to (`Votes::votes`, `Votes::quorum`), by index. -/ + votesForMe : List (Nat × List NodeId × Nat) := [] + /-- `Aft::is_new_follower`. -/ + isNewFollower : Bool := false + /-- `Aft::ticking`. -/ + ticking : Bool := false + /-- `Aft::configurations`. -/ + configurations : List Config := [] + /-- `Aft::all_other_nodes`, ordered by node id. -/ + allOtherNodes : List (NodeId × Peer) := [] + /-- + The `init_as_backup` snapshot index (the host's `Ledger::init_idx`); 0 for a node that + did not join from a snapshot. + -/ + base : Nat := 0 + /-- The `init_as_backup` snapshot view; 0 when `base` is. -/ + baseView : Nat := 0 + /-- + `Aft::ledger` (`LedgerProxy`) contents the node holds, after `base`: entry `i` is + `ledger[i - base - 1]`. + -/ + ledger : Array Entry := #[] + /-- + Not cft.h: the driver `Store`'s pending `retired_committed` entries + (`logging_stub.h`), which `compact` turns into `set_retired_committed` calls, + emulating the global-commit hook of a real node. + -/ + rcEntries : List (Nat × List NodeId) := [] +deriving DecidableEq, Inhabited + +/-! ## Encodings shared by the model and the observation (as `cft_trace_msgpack.h`) -/ + +def Leadership.name : Leadership -> String + | .none => "None" + | .follower => "Follower" + | .preVoteCandidate => "PreVoteCandidate" + | .candidate => "Candidate" + | .leader => "Leader" + +def Phase.name : Phase -> String + | .ordered => "Ordered" + | .signed => "Signed" + | .completed => "Completed" + | .retiredCommitted => "RetiredCommitted" + +def nodesJson (n : Nodes) : Json := + Json.mkObj (n.map fun (id, addr) => (id, Json.mkObj [("address", toJson addr)])) + +def configsJson (cs : List Config) : Json := + toJson + (cs.map + fun c => + Json.mkObj + [("idx", toJson c.idx), ("nodes", nodesJson c.nodes), ("rid", toJson c.rid)]) + +end Consensus.TraceValidation.Exec From 327c76cf2a78be6d01ce015c76c1bbf3d5decb40 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:07:27 +0000 Subject: [PATCH 06/25] Add M_tv, a model of cft.h with one step per trace point To validate a trace, each trace point must be explained by the code between it and the previous one. M_tv mirrors the cft.h handlers statement by statement over a full-ledger internal state (the declared suffix plus a ghost prefix for snapshot joiners), runs them as event-granular lock-hold sections, and checks at every release the local invariant the proofs use, that a snapshot base is a committed signature, and that the hold does not depend on ledger entries below the base. Rejections of behaviour cft.h can exhibit but the clean model cannot express are labelled as known implementation and specification differences. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 2 +- .../Consensus/TraceValidation/Aft.lean | 1154 +++++++++++++++++ .../Consensus/TraceValidation/Full.lean | 165 +++ .../Consensus/TraceValidation/Handler.lean | 177 +++ .../Consensus/TraceValidation/Invariant.lean | 387 ++++++ .../Consensus/TraceValidation/Machine.lean | 359 +++++ 6 files changed, 2243 insertions(+), 1 deletion(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Aft.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Full.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Handler.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Invariant.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Machine.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 71e46bf72469..9b86cb7dc5f9 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -2,7 +2,7 @@ module public import Consensus.Properties public import Consensus.Replay.Reduction -public import Consensus.TraceValidation.Abs +public import Consensus.TraceValidation.Machine import Consensus.Tests.CanonicalTraces import Consensus.Tests.ReplayDelivery diff --git a/lean/consensus/Consensus/TraceValidation/Aft.lean b/lean/consensus/Consensus/TraceValidation/Aft.lean new file mode 100644 index 000000000000..e8d1c8b78e19 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Aft.lean @@ -0,0 +1,1154 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Handler + +@[expose] public section + +/-! +# M_tv: cft.h, one trace point at a time + +Each definition mirrors the cft.h function of the same name, statement by +statement, and calls `trace` exactly where cft.h calls `trace::*`. Code between +trace points runs silently on `State`. Where cft.h depends on something the trace +does not carry (timers, batch sizes, ledger flush thresholds), the handler peeks +at the node's next event (`look`) and follows the branch that event requires. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean +open Consensus.Model.Node + +/-! ## Pure helpers over `State` (cft.h-aligned, no clean-model calls) -/ + +namespace State + +def isRetiredCommitted (v : State) : Bool := + v.retired && v.retirementPhase == some .retiredCommitted + +/-- `ViewHistory::view_at`: number of view starts at or below `idx`. -/ +def viewAt (v : State) (idx : Nat) : Nat := (v.views.toList.filter (· <= idx)).length + +def startOfView (v : State) (view : Nat) : Nat := + if view > v.views.size || view == 0 then + 0 + else + let tentative := v.views[view - 1]! + if view + 1 <= v.views.size && v.views[view]! == tentative then 0 else tentative + +def endOfView (v : State) (view : Nat) : Nat := + if v.startOfView view == 0 then + 0 + else if view >= v.views.size || view == 0 then + 0 + else + v.views[view]! - 1 + +/-- `get_term_internal`. -/ +def getTerm (v : State) (idx : Nat) : Nat := if idx > v.lastIdx then 0 else v.viewAt idx + +def lastCommittable (v : State) : Nat := v.committable.getLast?.getD v.commitIdx + +/-- `find_highest_possible_committable_index`. -/ +def highestCommittableLe (v : State) (idx : Nat) : Option Nat := + (v.committable.filter (· <= idx)).getLast? + +/-- `find_highest_possible_match`; each round moves to an earlier view. -/ +def highestMatchGo (v : State) (term probe tp : Nat) : Nat -> Nat + | 0 => probe + | fuel + 1 => + if tp > term then + let p := v.startOfView tp + let p := if p > 0 then p - 1 else p + highestMatchGo v term p (v.viewAt p) fuel + else + probe + +def highestMatch (v : State) (term idx : Nat) : Nat := + let probe := min idx v.lastIdx + v.highestMatchGo term probe (v.viewAt probe) (v.views.size + 1) + +def otherNodesInActiveConfigs (v : State) : List NodeId := + (v.configurations.flatMap (·.nodes.map Prod.fst)).filter (· != v.nodeId) + |>.mergeSort (· <= ·) + |>.eraseDups + +def peer? (v : State) (id : NodeId) : Option Peer := v.allOtherNodes.lookup id + +def setPeer (v : State) (id : NodeId) (p : Peer) : State := + let rest := v.allOtherNodes.filter (·.1 != id) + { v with allOtherNodes := (rest ++ [(id, p)]).mergeSort (fun a b => a.1 <= b.1) } + +def selfInLatestConfig (v : State) : Bool := + match v.configurations.getLast? with + | some c => c.nodes.any (·.1 == v.nodeId) + | none => false + +def quorum (n : Nat) : Nat := n / 2 + 1 + +/-- +Whether CheckQuorum can fail for some ack timers: some active configuration has fewer +members without peer state (counted live by cft.h) than its quorum. +-/ +def canLoseQuorum (v : State) : Bool := + v.configurations.any + fun c => + (c.nodes.filter fun (n, _) => (v.peer? n).isNone).length < quorum c.nodes.length + +end State + +/-! ## Messages -/ + +def aePacket (idx prevIdx term prevTerm leaderCommit termOfIdx : Nat) : Json := + Json.mkObj + [ + ("msg", "append_entries"), + ("idx", toJson idx), + ("prev_idx", toJson prevIdx), + ("term", toJson term), + ("prev_term", toJson prevTerm), + ("leader_commit_idx", toJson leaderCommit), + ("term_of_idx", toJson termOfIdx), + ("contains_new_view", toJson false) + ] + +def aerPacket (term idx : Nat) (ok : Bool) : Json := + Json.mkObj + [ + ("msg", "append_entries_response"), + ("term", toJson term), + ("last_log_idx", toJson idx), + ("success", toJson (if ok then "OK" else "FAIL")) + ] + +def rvPacket (pre : Bool) (term lci tlci : Nat) : Json := + Json.mkObj + [ + ("msg", toJson (if pre then "request_pre_vote" else "request_vote")), + ("term", toJson term), + ("last_committable_idx", toJson lci), + ("term_of_last_committable_idx", toJson tlci) + ] + +def rvrPacket (pre : Bool) (term : Nat) (granted : Bool) : Json := + Json.mkObj + [ + ( + "msg", + toJson (if pre then "request_pre_vote_response" else "request_vote_response") + ), + ("term", toJson term), + ("vote_granted", toJson granted) + ] + +def prvPacket (term : Nat) : Json := + Json.mkObj [("msg", "propose_request_vote"), ("term", toJson term)] + +/-- The term of the last entry of an AppendEntries, as `term_of_idx`. -/ +def aeTermOfIdx (r : AppendEntriesRequest) : Nat := + (r.entries.getLast?.map (·.term)).getD r.prevLogTerm + +def aeIdx (r : AppendEntriesRequest) : Nat := + r.prevLogIndex + r.entries.length + +/-- The `cft.h` packet of a message. -/ +def packetOf : Message -> Json + | .appendEntriesRequest r => + aePacket (aeIdx r) r.prevLogIndex r.term r.prevLogTerm r.primaryCommit + (aeTermOfIdx r) + | .appendEntriesResponse r => aerPacket r.term r.lastLogIndex r.success + | .requestVoteRequest r => + rvPacket false r.term r.lastCommittableIndex r.lastCommittableTerm + | .requestPreVoteRequest r => + rvPacket true r.term r.lastCommittableIndex r.lastCommittableTerm + | .requestVoteResponse r => rvrPacket false r.term r.voteGranted + | .requestPreVoteResponse r => rvrPacket true r.term r.voteGranted + | .proposeRequestVoteRequest t => prvPacket t + +def envAddr (env : Env) (id : NodeId) : String := (env.addrs.lookup id).getD "" + +def envNodes (env : Env) (s : CCF.Finset NodeID) : Nodes := + s.sort.map + fun i => + let n := env.names.name i; + (n, envAddr env n) + +/-- A received entry as the ledger and its hooks see it. -/ +def toExecEntry (env : Env) (e : Consensus.Model.Node.Entry) : Entry := + match e.content with + | .signature => { term := e.term, sig := true } + | .transaction _ md => + { + term := e.term, + sig := false, + config := md.configuration.map (envNodes env) + retired := md.retirementConfirmations.sort.map env.names.name + } + +/-! ## Handlers -/ + +/-- A receive's trace point, labelled with the delivered message. -/ +def traceRecv (fn : String) (from_ : NodeId) (m : Message) : M Unit := do + trace fn + emit "packet" (packetOf m) + emitStr "from_node_id" from_ + +/-- `send_append_entries_range`, given the sub-range end chosen by the batch size. -/ +def sendAppendEntriesRange (to : NodeId) (start endIdx : Nat) (ext : Bool) : M Unit := do + let v ← getV + let prevIdx := start - 1 + let some node := v.peer? to | fail s!"{← curLoc}: all_other_nodes.at({to}) failed" + let packet := + aePacket endIdx prevIdx v.currentView (v.getTerm prevIdx) v.commitIdx + (v.getTerm endIdx) + emit "packet" packet + emitStr "to_node_id" to + let names ← names + let entries := + (List.range' start (endIdx + 1 - start)).map fun i => absEntry names v.ledger[i - 1]! + send to + (.appendEntriesRequest + { + term := v.currentView, + prevLogIndex := prevIdx, + prevLogTerm := v.getTerm prevIdx, + entries, + primaryCommit := v.commitIdx + }) + note (.sendEntries to endIdx ext) + setV fun v => v.setPeer to { node with sentIdx := endIdx } + +/-- +`send_append_entries`. The batch size is not traced, so each sub-range end is +read from the next `send_append_entries` event and checked against what any +batch size allows: one size for the whole call, every non-final sub-range full. +-/ +def sendAppendEntries (to : NodeId) (start : Nat) (ext : Bool := false) : M Unit := do + let rec loop : Nat -> Nat -> Option Nat -> M Unit + | 0, _, _ => do fail s!"{← curLoc}: send_append_entries does not terminate" + | fuel + 1, start, batch => do + let v ← getV + let maxIdx := + match v.endOfView (v.viewAt start) with + | 0 => v.lastIdx + | e => e + -- Ends that some batch size >= 1 allows: maxIdx when start > maxIdx, else [start, maxIdx]. + let skipCertain := v.isRetiredCommitted && start >= maxIdx + let endIdx ← + if skipCertain then + pure maxIdx + else do + let next ← look + let isOurs := + match next with + | some a => + a.point == "send_append_entries" + && a.inputs.lookup "to_node_id" == some (toJson to) + | none => false + if v.isRetiredCommitted && !isOurs then + -- Only a batch size of one makes start == end, which is silently skipped. + if batch.any (· != 1) then + fail s!"{← curLoc}: expected send_append_entries to {to}" + pure start + else + trace "send_append_entries" + let packet ← use "packet" + let endIdx ← liftE (getNat packet "idx") + pure endIdx + let ok := + if start > maxIdx then endIdx == maxIdx else start <= endIdx && endIdx <= maxIdx + unless ok do + fail + s!"{← curLoc}: packet.idx: observed {endIdx}, model allows [{start}, {maxIdx}]" + let size := endIdx + 1 - start + let batch ← + if endIdx < maxIdx then do + if batch.any (· != size) then + fail + s!"{← curLoc}: packet.idx: sub-range of {size} entries after batches of {batch}" + pure (some size) + else do + if batch.any (· < size) then + fail + s!"{← curLoc}: packet.idx: final sub-range of {size} entries exceeds batch {batch}" + pure batch + let skipped := v.isRetiredCommitted && start >= endIdx + unless skipped do + -- Re-mark the packet as checked: the remaining fields are model-computed. + sendAppendEntriesRange to start endIdx ext + let v ← getV + unless endIdx == v.lastIdx do + loop fuel (min (endIdx + 1) v.lastIdx) batch + loop ((← getV).lastIdx + 2) start none + +def otherNodesSorted : M (List NodeId) := do + return (← getV).allOtherNodes.map Prod.fst + +def becomeRetired (idx : Nat) (phase : Phase) : M Unit := do + match phase with + | .ordered => + if (← getV).retirementIdx.isSome then + fail s!"{← curLoc}: retirement_idx already set" + setV fun v => { v with retirementIdx := some idx } + | .signed => setV fun v => { v with retirementCommittableIdx := some idx } + | .retiredCommitted => + nominateSuccessorUnsafe + setV fun v => { v with leaderId := none, leadership := .none } + | .completed => pure () + setV fun v => { v with retired := true, retirementPhase := some phase } +where + findSuccessor : M (Option NodeId) := do + let v ← getV + let mut successor := none + let mut maxMatch := 0 + let mut reconf := 0 + for (node, st) in v.allOtherNodes do + if st.matchIdx >= maxMatch then + let latest := + (v.configurations.reverse.find? (·.nodes.any (·.1 == node))).map (·.idx) + |>.getD 0 + if !(st.matchIdx == maxMatch && latest < reconf) then + reconf := latest + successor := some node + maxMatch := st.matchIdx + return successor + nominateSuccessorUnsafe : M Unit := do + let v ← getV + unless v.leadership == .leader do + return + if let some s ← findSuccessor then + trace "step_down_and_nominate_successor" + emitStr "to_node_id" s + send s (.proposeRequestVoteRequest v.currentView) + +def nominateSuccessorUnsafe : M Unit := becomeRetired.nominateSuccessorUnsafe + +def createAndRemoveNodeState : M Unit := do + let v ← getV + let active := + (v.configurations.flatMap (·.nodes.map Prod.fst)).mergeSort (· <= ·) |>.eraseDups + for id in active do + if id == v.nodeId then continue + let v ← getV + if (v.peer? id).isNone then + let index := v.lastIdx + 1 + setV fun v => v.setPeer id { sentIdx := index, matchIdx := 0 } + if v.leadership == .leader then sendAppendEntries id index + +/-- +`set_retired_committed` of the entry at `seqno` naming `ids`. `peers0` are the peers at +the start of the commit, from which the specification nominates a successor. +-/ +def setRetiredCommitted (seqno : Nat) (ids : List NodeId) (peers0 : List (NodeId × Peer)) + : M Unit := do + for id in ids do + let v ← getV + if id == v.nodeId then + unless v.retired && v.retirementPhase == some .completed do + fail + s!"{← curLoc}: set_retired_committed({seqno}) on self while not Retired/Completed" + -- Accepted by the implementation, rejected by validation: successor nomination. + -- cft.h erases the peers retired-committed earlier in the same commit before it + -- nominates; the specification nominates from the peers before the commit. + if v.leadership == .leader then + let actual ← becomeRetired.findSuccessor + setV fun v => { v with allOtherNodes := peers0 } + let specified ← becomeRetired.findSuccessor + setV fun _ => v + unless actual == specified do + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: successor nomination (known implementation and specification difference: cft.h nominates {actual} after erasing peers retired-committed in the same commit; the specification nominates {specified} from the peers before the commit)" + setV fun v => { v with retiredCommittedIdx := some seqno } + becomeRetired seqno .retiredCommitted + else + setV fun v => { v with allOtherNodes := v.allOtherNodes.filter (·.1 != id) } + +/-- Driver store `compact`: emulates the global-commit hook. -/ +def storeCompact (idx : Nat) : M Unit := do + let peers0 := (← getV).allOtherNodes + let rec go : List (Nat × List NodeId) -> M Unit + | [] => pure () + | (ver, ids) :: rest => + if ver <= idx then do + setRetiredCommitted ver ids peers0; go rest + else + pure () + go (← getV).rcEntries + setV fun v => { v with rcEntries := v.rcEntries.filter (·.1 > idx) } + +def commit (idx : Nat) : M Unit := do + let v ← getV + if idx > v.lastIdx then fail s!"{← curLoc}: commit({idx}) beyond last_idx {v.lastIdx}" + if idx <= v.commitIdx then return + trace "commit" + emitNat "idx" idx + setV fun v => { v with committable := v.committable.filter (· > idx), commitIdx := idx } + let v ← getV + if v.retired && v.retirementPhase == some .signed then + if let some rci := v.retirementCommittableIdx then + if idx >= rci then becomeRetired idx .completed + storeCompact idx + let cs := (← getV).configurations + let rec pop : List Config -> List Config + | c :: n :: rest => if idx < n.idx then c :: n :: rest else pop (n :: rest) + | cs => cs + let cs' := pop cs + if cs'.length != cs.length then + setV fun v => { v with configurations := cs' } + createAndRemoveNodeState + +/-- The match indexes of a configuration's members, the leader's own being its last index. -/ +def matchIdxs (v : State) (c : Config) : Except String (List Nat) := + c.nodes.mapM + fun (id, _) => + if id == v.nodeId then + .ok v.lastIdx + else + match v.peer? id with + | some p => .ok p.matchIdx + | none => .error s!"all_other_nodes.at({id}) failed in highest_committable_idx" + +/-- The index a majority of `c` has reached: the median of its sorted match indexes. -/ +def confirmedIdx (v : State) (c : Config) : Except String Nat := do + let sorted := (← matchIdxs v c).mergeSort + match sorted[(sorted.length - 1) / 2]? with + | some x => .ok x + | none => .error s!"empty configuration {c.idx}" + +/-- +The loop of `highest_committable_idx` over the configurations from `first`: `lowest` is the +lowest median so far; the loop stops at a configuration it does not reach. +-/ +def agreementGo (v : State) + : Option Nat -> List Config -> Option Nat -> Except String (Option Nat) + | _, [], agreement => .ok agreement + | lowest, c :: rest, agreement => do + let confirmed ← confirmedIdx v c + let lo := + match lowest with + | some l => min l confirmed + | none => confirmed + if lo < c.idx then return agreement + agreementGo v (some lo) rest + (some + (match rest.head? with + | some n => min lo (n.idx - 1) + | none => lo)) + +/-- `highest_committable_idx(first)`, as a function of the state. -/ +def highestCommittableIdxOf (v : State) (first : Nat) : Except String (Option Nat) := do + let confs := v.configurations.drop first + let some a ← agreementGo v none confs none | return none + if a > v.lastIdx then throw "followers appear to have later match indices than leader" + let some nc := v.highestCommittableLe a | return none + if nc < (confs.head?.map (·.idx)).getD 0 then return none + if v.getTerm nc != v.currentView then return none + return some nc + +def highestCommittableIdx (first : Nat) : M (Option Nat) := do + liftE (highestCommittableIdxOf (← getV) first) + +/-- The inner `while` of `update_commit`: skip configurations that `i` reaches. -/ +def advanceFirst (cs : List Config) (i : Nat) : Nat -> Nat -> Nat + | first, 0 => first + | first, fuel + 1 => + if cs[first + 1]?.any (·.idx <= i) then + advanceFirst cs i (first + 1) fuel + else + first + +/-- The outer loop of `update_commit`; each round strictly raises the candidate index. -/ +def updateCommitGo (first : Nat) (newCommit : Option Nat) : Nat -> M (Option Nat) + | 0 => fail s!"update_commit does not terminate" + | fuel + 1 => do + match ← highestCommittableIdx first with + | none => return newCommit + | some i => + if newCommit.any (i <= ·) then return newCommit + let cs := (← getV).configurations + updateCommitGo (advanceFirst cs i first cs.length) (some i) fuel + +def updateCommit : M Unit := do + let v ← getV + unless v.leadership == .leader do + fail s!"{← curLoc}: update_commit while not leader" + if let some i ← updateCommitGo 0 none (v.lastIdx + 2) then commit i + +def commitIfPossible (idx : Nat) : M Unit := do + let v ← getV + if idx > v.commitIdx && v.getTerm idx <= v.currentView then + if let some h := v.highestCommittableLe idx then commit h + +def rollback (idx : Nat) : M Unit := do + let v ← getV + if idx < v.commitIdx then return + setV + fun v => + let v := + { + v with + rcEntries := v.rcEntries.filter (·.1 <= idx), + ledger := v.ledger.extract 0 idx, + lastIdx := idx, + views := v.views.filter (· <= idx), + committable := v.committable.filter (· <= idx) + } + let v := + if v.retired + && v.retirementPhase == some .signed + && v.retirementCommittableIdx.any (· > idx) then + { v with retirementCommittableIdx := none, retirementPhase := some .ordered } + else + v + if v.retired + && v.retirementPhase == some .ordered + && v.retirementIdx.any (· > idx) then + { v with retirementIdx := none, retirementPhase := none, retired := false } + else + v + let cs := (← getV).configurations + let cs' := cs.filter (·.idx <= idx) + if cs'.length != cs.length then + setV fun v => { v with configurations := cs' } + createAndRemoveNodeState + +def resetVotesForMe : M Unit := + setV + fun v => + { + v with + votesForMe := + v.configurations.map fun c => (c.idx, [], State.quorum c.nodes.length) + } + +def becomeFollower : M Unit := do + setV fun v => { v with leaderId := none, leadership := .follower } + trace "become_follower" + +def becomeAwareOfNewTerm (term : Nat) : M Unit := do + setV + fun v => + { + v with + votedFor := if v.currentView != term then none else v.votedFor, + currentView := term + } + resetVotesForMe + becomeFollower + setV fun v => { v with isNewFollower := true } + +def sendRequestVote (pre : Bool) (to : NodeId) : M Unit := do + let v ← getV + let lci := v.lastCommittable + if lci < v.commitIdx then fail s!"{← curLoc}: lci < ci" + let packet := rvPacket pre v.currentView lci (v.getTerm lci) + trace "send_request_vote" + emit "packet" packet + emitStr "to_node_id" to + let r : RequestVoteRequest := + { + term := v.currentView, + lastCommittableTerm := v.getTerm lci, + lastCommittableIndex := lci + } + send to (if pre then .requestPreVoteRequest r else .requestVoteRequest r) + +def becomeLeader : M Bool := do + let v ← getV + if v.isRetiredCommitted then return false + let electionIndex := v.lastCommittable + if v.commitIdx > 0 then + rollback electionIndex + -- Accepted by the implementation, rejected by validation: peers kept across the + -- election rollback. cft.h keeps in all_other_nodes (and sends AppendEntries to) a + -- node whose only configuration the rollback removed; the specification's peers are + -- the eligible peers of the remaining log. + let names ← names + let v ← getV + let peers := v.allOtherNodes.map (names.id ·.1) + let eligible := (eligiblePeers (abs names v) (names.id v.nodeId)).sort + unless peers == eligible do + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: peers kept across rollback (known implementation and specification difference: after rolling back to {electionIndex}, cft.h keeps peers {v.allOtherNodes.map (·.1)}, the specification's eligible peers are {eligible.map names.name})" + setV fun v => { v with leadership := .leader, leaderId := some v.nodeId } + trace "become_leader" + if (← getV).otherNodesInActiveConfigs.isEmpty then updateCommit + let next := (← getV).lastIdx + 1 + for id in ← otherNodesSorted do + setV fun v => v.setPeer id { matchIdx := 0, sentIdx := next - 1 } + sendAppendEntries id next + return true + +/-- The vote-recording part of `add_vote_for_me`: whether the node is now elected. -/ +def recordVote (from_ : NodeId) : M Bool := do + let v ← getV + if v.configurations.isEmpty then return false + let mut votes := v.votesForMe + for c in v.configurations do + unless c.nodes.any (·.1 == from_) do + continue + votes := + match votes.find? (·.1 == c.idx) with + | some _ => + votes.map + fun (i, vs, q) => + if i == c.idx then + (i, if vs.contains from_ then vs else vs ++ [from_], q) + else + (i, vs, q) + | none => (votes ++ [(c.idx, [from_], 0)]).mergeSort (fun a b => a.1 <= b.1) + setV fun v => { v with votesForMe := votes } + return votes.all fun (_, vs, q) => vs.length >= q + +def becomeCandidate : M Unit := do + if (← getV).configurations.isEmpty then return + setV + fun v => + { v with leadership := .candidate, leaderId := none, votedFor := some v.nodeId } + resetVotesForMe + setV fun v => { v with currentView := v.currentView + 1 } + trace "become_candidate" + -- `add_vote_for_me(node_id)` as a candidate. + if ← recordVote (← getV).nodeId then discard becomeLeader + for id in (← getV).otherNodesInActiveConfigs do + sendRequestVote false id + +def addVoteForMe (from_ : NodeId) : M Unit := do + let leadership := (← getV).leadership + if ← recordVote from_ then + match leadership with + | .preVoteCandidate => becomeCandidate + | .candidate => discard becomeLeader + | _ => do fail s!"{← curLoc}: add_vote_for_me() while not a candidate" + +def becomePreVoteCandidate : M Unit := do + if (← getV).configurations.isEmpty then return + setV fun v => { v with leadership := .preVoteCandidate, leaderId := none } + resetVotesForMe + trace "become_pre_vote_candidate" + addVoteForMe (← getV).nodeId + for id in (← getV).otherNodesInActiveConfigs do + sendRequestVote true id + +/-! ## Configuration hooks -/ + +/-- +`add_configuration`, called by a `ConfigurationChangeHook`. On the primary the +traced `nodes` is the entry's content (input); on a follower it must equal the +configuration carried by the replicated entry. +-/ +def addConfiguration (idx? : Option Nat) (expected : Option Nodes) : M Nodes := do + trace "add_configuration" + let v ← getV + let idx ← + match idx? with + | some i => do emitNat "idx" i; pure i + | none => inNat "idx" + emitNat "rid" idx + let nodes ← + match expected with + | some n => do emit "nodes" (nodesJson n); pure n + | none => do liftE (parseNodes (← use "nodes")) + if let some last := v.configurations.getLast? then + if last.nodes.any (·.1 == v.nodeId) && !nodes.any (·.1 == v.nodeId) then + becomeRetired idx .ordered + let v ← getV + if v.configurations.isEmpty + || some nodes != (v.configurations.getLast?.map (·.nodes)) then + setV + fun v => + { v with configurations := v.configurations ++ [{ idx, nodes, rid := idx }] } + createAndRemoveNodeState + return nodes + +def startTickingIfNecessary : M Unit := + setV + fun v => if !v.ticking && v.selfInLatestConfig then { v with ticking := true } else v + +/-! ## Entry points: one per section head -/ + +/-- +Accepted by the implementation, rejected by validation: the election guard. cft.h starts +an election (on a timeout or a ProposeRequestVote) when the node is not retired-committed +and `ticking`; the clean `canStartElection` also needs a follower or candidate role and +membership of a signed active configuration (or a completed retirement). `ticking` is +sticky, so a real node can keep it after a rollback (with peers kept across it) drops it +from every signed configuration; the driver also ticks a node of role none. Validation +rejects such an election; removing this check is a one-line change (`pure ()`). +-/ +def electionGuard : M Unit := do + let names ← names + let v ← getV + unless decide (canStartElection (abs names v) (names.id v.nodeId)) do + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: election guard (known implementation and specification difference: cft.h only needs ticking, the specification also needs a role and membership of a signed configuration)" + +def periodic : M Unit := do + trace "tick" + let v ← getV + if v.leadership == .leader then + -- request_timeout is not traced: it fired iff the next event is a send. + if (← lookFn) == some "send_append_entries" then + note .heartbeatTimeout + for id in ← otherNodesSorted do + let some p := (← getV).peer? id | continue + sendAppendEntries id (p.sentIdx + 1) (ext := true) + -- CheckQuorum depends on untraced ack timers: it fired iff become_follower follows. + -- cft.h counts a configuration member without peer state (self, or a node erased at + -- retired_committed) as live, so it can only step down if, in some active + -- configuration, the other members could leave it without a quorum. + if (← getV).canLoseQuorum && (← lookFn) == some "become_follower" then + note .checkQuorum + becomeFollower + else + if !v.isRetiredCommitted + && v.ticking + && (← lookFn) == some "become_pre_vote_candidate" then + electionGuard + note .electionTimeout + becomePreVoteCandidate + +/-- The `retired_committed_tx` hooks of the entry at `index`. -/ +def retiredHooks (index : Nat) : Nat -> List NodeId -> M (List NodeId) + | 0, _ => do fail s!"{← curLoc}: hooks do not terminate" + | fuel + 1, acc => do + if (← lookFn) == some "retired_committed_tx" then + trace "retired_committed_tx" + emitNat "seqno" index + let id ← inStr "retired_node_id" + retiredHooks index fuel (acc ++ [id]) + else + return acc + +def replicateEntry : M Unit := do + trace "replicate_entry" + let v ← getV + let index := v.lastIdx + 1 + let sig ← inBool "globally_committable" + -- Entry admission (Node.lean's appendEntry): the signature timer starts only after the + -- genesis (or recovery, or join) transaction, so a ledger never starts with a signature. + if sig && v.lastIdx == 0 then + fail + s!"{← curLoc}: entry admission: a signature as the first entry of an empty ledger" + -- Hooks: the entry's content is only visible through the hooks it triggers. + let retired ← retiredHooks index ((← get).queue.length + 1) [] + if !retired.isEmpty then + -- Accepted by the implementation, rejected by validation: retirement confirmations. + -- hooks.h fires retired_committed_tx on every write of a node record whose + -- retired_committed flag is set: the default constitution's remove_node on a node + -- already retired-committed rewrites its record and confirms it again. The + -- specification only confirms nodes whose retirement is completed and not yet + -- confirmed in the ledger. + let names ← names + let a := abs names v + unless decide + (names.set retired + ⊆ a.retirementCompletedNodes \ retiredCommittedNodes a.log) do + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: retirement confirmation (known implementation and specification difference: hooks.h confirms {retired} again whenever their node records are rewritten; the specification only confirms nodes whose retirement is completed and not yet confirmed)" + setV fun v => { v with rcEntries := v.rcEntries ++ [(index, retired)] } + -- hooks.h runs the retired_committed_tx hooks, then add_configuration, for one entry. + let mut config := none + if (← lookFn) == some "add_configuration" then + let nodes ← addConfiguration (some index) none + -- The decoder reads a configuration from a JSON object, whose node ids are distinct. + unless (nodes.map Prod.fst).eraseDups == nodes.map Prod.fst do + fail s!"{← curLoc}: configuration {nodes.map Prod.fst} repeats a node id" + -- Entry admission (Node.lean's appendEntry): hooks.h only calls add_configuration + -- when the node set changed from cft.h's latest configuration, the latest ledger one. + -- The checks read the clean log, as the specification does: the latest configuration + -- and the removed nodes of its configuration history. + let ids := (nodes.map Prod.fst).mergeSort (· <= ·) |>.eraseDups + let names ← names + let log := (abs names v).log + -- Accepted by the implementation, rejected by validation: an empty configuration. + -- A single node that removes itself makes hooks.h call add_configuration with no + -- nodes; the specification requires a non-empty configuration. + if ids.isEmpty then + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: empty configuration (known implementation and specification difference: hooks.h adds an empty configuration when the last node removes itself; the specification requires a non-empty configuration)" + if decide (names.set ids = latestConfigurationMembers (configurationHistory log)) then + fail + s!"{← curLoc}: entry admission: configuration {ids} unchanged from the latest configuration in the ledger" + -- Node identities are never reused: a retired node cannot be added back. + let back := ids.filter fun i => decide (names.id i ∈ removedNodes log) + unless back.isEmpty do + fail + s!"{← curLoc}: entry admission: configuration {ids} names {back}, removed by an earlier configuration" + config := some nodes + -- The decoder names every node id of the trace, in order (Validator.lean), so the + -- hooks' node ids are named and the names are sorted. + let names ← names + let ids := (config.getD []).map Prod.fst ++ retired + unless ids.isEmpty + || ids.all names.known.contains + && (names.known.toList.zip names.known.toList.tail).all + fun (x, y) => decide (x < y) do + fail s!"{← curLoc}: hook node ids {ids} not among the trace's sorted node ids" + -- Entry admission: a signature transaction writes only the signatures table, so it + -- triggers no hook (the clean model's signature entry has no metadata). + if sig && (!retired.isEmpty || config.isSome) then + fail s!"{← curLoc}: entry admission: a signature entry triggers hooks" + if sig then + let v ← getV + if v.retired && v.retirementPhase == some .ordered then becomeRetired index .signed + setV fun v => { v with committable := v.committable ++ [index] } + startTickingIfNecessary + let entry : Entry := { term := (← getV).currentView, sig, config, retired } + setV fun v => { v with lastIdx := index, ledger := v.ledger.push entry } + note (.appendEntry entry) + let v ← getV + if v.views.back?.any (index < ·) then + fail s!"{← curLoc}: view history moves backwards" + setV + fun v => + { v with views := v.views ++ Array.replicate (v.currentView - v.views.size) index } + -- The flush threshold depends on untraced entry sizes. + if (← lookFn) == some "batch_flush" then + trace "batch_flush" + note .batchFlush + for id in ← otherNodesSorted do + let some p := (← getV).peer? id | continue + sendAppendEntries id (p.sentIdx + 1) (ext := true) + +def replicateEntries : Nat -> M Unit + | 0 => do fail s!"{← curLoc}: replicate does not terminate" + | fuel + 1 => do + if (← lookFn) == some "replicate_entry" then + replicateEntry + replicateEntries fuel + +def replicate : M Unit := do + trace "replicate" + let v ← getV + unless v.leadership == .leader && !v.isRetiredCommitted do + fail s!"{← curLoc}: replicate traced while not able to replicate" + -- A configuration in this batch may add a node; commit is decided by the nodes before it. + let noOtherNodes := v.otherNodesInActiveConfigs.isEmpty + replicateEntries ((← get).queue.length + 1) + if noOtherNodes then updateCommit + +def viewUpdate (idx view : Nat) : M Unit := do + let v ← getV + if v.views.back?.any (idx < ·) then + fail + s!"{← curLoc}: view_history.update({idx}, {view}) moves backwards from {v.views.back?}" + setV fun v => { v with views := v.views ++ Array.replicate (view - v.views.size) idx } + +def sendAer (to : NodeId) (term idx : Nat) (ok : Bool) : M Unit := do + let packet := aerPacket term idx ok + trace "send_append_entries_response" + emit "packet" packet + emitStr "to_node_id" to + send to (.appendEntriesResponse { term, success := ok, lastLogIndex := idx }) + +def nack (to : NodeId) : M Unit := do + let v ← getV + sendAer to v.currentView v.lastIdx false + +def nackRejected (to : NodeId) (term idx : Nat) : M Unit := do + let v ← getV + let i := v.highestMatch term idx + sendAer to (v.getTerm i) i false + +def recvAppendEntries (from_ : NodeId) (r : AppendEntriesRequest) : M Unit := do + traceRecv "recv_append_entries" from_ (.appendEntriesRequest r) + let rTerm := r.term + let rIdx := aeIdx r + let rPrevIdx := r.prevLogIndex + let rPrevTerm := r.prevLogTerm + let rLeaderCommit := r.primaryCommit + let rTermOfIdx := aeTermOfIdx r + let env := (← get).env + let payload := (r.entries.map (toExecEntry env)).toArray + let v ← getV + if v.currentView == rTerm + && (v.leadership == .candidate || v.leadership == .preVoteCandidate) then + becomeAwareOfNewTerm rTerm + else if v.currentView < rTerm then + becomeAwareOfNewTerm rTerm + else if v.currentView > rTerm then + nack from_ + return + let v ← getV + -- Two leaders in one view violate election safety; cft.h has no guard and would + -- overwrite leader_id, so a trace reaching this exhibits a bug. + if v.leadership == .leader && v.currentView == rTerm then + fail s!"{← curLoc}: AppendEntries from {from_} to a leader in its own view {rTerm}" + let prevTerm := v.getTerm rPrevIdx + if prevTerm != rPrevTerm then + if prevTerm == 0 then nack from_ else nackRejected from_ rPrevTerm rPrevIdx + return + setV fun v => { v with leaderId := some from_ } + let v ← getV + if rPrevIdx < v.commitIdx then return + if rPrevIdx > v.lastIdx then return + let mut toApply : Array (Nat × Entry × Bool) := #[] + for i in [rPrevIdx + 1 : rIdx + 1] do + let entry? := payload[i - rPrevIdx - 1]? + if entry?.isNone then + nack from_ + return + let entry := entry?.get! + let v ← getV + if i <= v.lastIdx then + if rTermOfIdx != v.viewAt i then + if v.isNewFollower then + rollback (i - 1) + setV fun v => { v with isNewFollower := false } + else + return + else + continue + -- store->deserialize: the driver store records retired_committed entries here. + if !entry.retired.isEmpty then + setV fun v => { v with rcEntries := v.rcEntries ++ [(i, entry.retired)] } + toApply := toApply.push (i, entry, entry.term == rTermOfIdx) + -- execute_append_entries_sync + for (i, entry, ok) in toApply do + trace "execute_append_entries_sync" + emitStr "from_node_id" from_ + unless ok do + setV fun v => { v with ledger := v.ledger.extract 0 (i - 1) } + nack from_ + return + setV fun v => { v with lastIdx := i } + -- hooks.h runs the retired_committed_tx hooks, then add_configuration. + for id in entry.retired do + trace "retired_committed_tx" + emitNat "seqno" i + emitStr "retired_node_id" id + if let some nodes := entry.config then + let _ ← addConfiguration (some i) (some nodes) + if entry.sig then startTickingIfNecessary + setV fun v => { v with ledger := (v.ledger.extract 0 (i - 1)).push entry } + if entry.sig then + let v ← getV + if v.retired && v.retirementPhase == some .ordered then becomeRetired i .signed + setV fun v => { v with committable := v.committable ++ [i] } + if entry.term != 0 then + if rTermOfIdx == 0 then + viewUpdate 1 rTerm + else + viewUpdate (rPrevIdx + 1) entry.term + commitIfPossible (min rLeaderCommit rIdx) + -- execute_append_entries_finish + commitIfPossible (min rLeaderCommit rIdx) + let lci := (← getV).lastCommittable + if rTermOfIdx == 0 then + viewUpdate 1 rTerm + else if rIdx > lci then + viewUpdate (lci + 1) rTermOfIdx + sendAer from_ (← getV).currentView rIdx true + +def recvAppendEntriesResponse (from_ : NodeId) (r : AppendEntriesResponse) : M Unit := do + let some node := (← getV).peer? from_ + | fail + s!"recv_append_entries_response from {from_} is traced, but {from_} is not in all_other_nodes" + traceRecv "recv_append_entries_response" from_ (.appendEntriesResponse r) + let rTerm := r.term + let rIdx := r.lastLogIndex + let ok := r.success + let v ← getV + if v.leadership != .leader then return + if v.currentView < rTerm then + becomeAwareOfNewTerm rTerm + return + if v.currentView != rTerm then + if ok then return + else if rIdx < node.matchIdx then + if ok then return + if !ok then + let m := v.highestMatch rTerm rIdx + setV + fun v => + v.setPeer from_ { node with sentIdx := max (min m node.sentIdx) node.matchIdx } + return + setV fun v => v.setPeer from_ { node with matchIdx := max node.matchIdx rIdx } + updateCommit + +def recvRequestVote (from_ : NodeId) (pre : Bool) (r : RequestVoteRequest) : M Unit := do + traceRecv "recv_request_vote" from_ + (if pre then .requestPreVoteRequest r else .requestVoteRequest r) + let rTerm := r.term + let rLci := r.lastCommittableIndex + let rTlci := r.lastCommittableTerm + let respond (granted : Bool) : M Unit := do + let term := (← getV).currentView + trace "send_request_vote_response" + emit "packet" (rvrPacket pre term granted) + emitStr "to_node_id" from_ + let r : RequestVoteResponse := { term, voteGranted := granted } + send from_ (if pre then .requestPreVoteResponse r else .requestVoteResponse r) + if (← getV).currentView > rTerm then + respond false + return + if (← getV).currentView < rTerm then becomeAwareOfNewTerm rTerm + let v ← getV + let mut grant := true + if !pre && v.leaderId.isSome then grant := false + if !pre && v.votedFor.any (· != from_) then grant := false + let lci := v.lastCommittable + let tlci := v.getTerm lci + unless rTlci > tlci || (rTlci == tlci && rLci >= lci) do + grant := false + if grant && !pre then setV fun v => { v with leaderId := none, votedFor := some from_ } + respond grant + +/-- +`recv_request_vote_response`. Accepted by the implementation, rejected by validation: a +granted (pre-)vote from a peer in no active configuration. cft.h records a vote only in the +configurations that name the voter, so it ignores such a vote; the clean model adds any +eligible peer, which includes a node whose retirement completed, to the votes granted. A +candidate asks only the members of its configurations, which stay fixed in its view, so +for votes this needs an implementation bug. A pre-vote candidate can ask again in the same +view: for example, pre-vote candidate n1 asks n3 in view 2, learns from the primary of +view 2 a committed configuration without n3 and steps down, and starts another pre-vote +in view 2 when n3's late grant arrives. +-/ +def recvRequestVoteResponse (from_ : NodeId) (pre : Bool) (r : RequestVoteResponse) + : M Unit := do + traceRecv "recv_request_vote_response" from_ + (if pre then .requestPreVoteResponse r else .requestVoteResponse r) + let rTerm := r.term + let granted := r.voteGranted + let v ← getV + if (v.peer? from_).isNone then return + if v.currentView < rTerm then + becomeAwareOfNewTerm rTerm + return + if v.currentView != rTerm then return + if v.leadership != .preVoteCandidate && v.leadership != .candidate then return + if !pre && v.leadership != .candidate then return + if pre && v.leadership != .preVoteCandidate then return + if !granted then return + unless v.configurations.any (·.nodes.any (·.1 == from_)) do + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: granted vote from {from_}, in no active configuration (known implementation and specification difference: cft.h ignores the vote, the specification counts the vote of any eligible peer)" + addVoteForMe from_ + +/-- +`recv_propose_request_vote`. Accepted by the implementation, rejected by validation: a +proposal in the node's view to a node that is not ticking but can start an election. cft.h +ignores it; the clean model starts an election. For example, a joiner named by a +configuration that a configuration without it supersedes before the next signature never +starts ticking (it is not in the latest configuration at a signature), yet is a member of +a signed active configuration, and the primary can nominate it. +-/ +def recvProposeRequestVote (from_ : NodeId) (rTerm : Nat) : M Unit := do + traceRecv "recv_propose_request_vote" from_ (.proposeRequestVoteRequest rTerm) + let v ← getV + if !v.isRetiredCommitted && v.ticking && rTerm == v.currentView then + -- Only a leader proposes, in its own view: two leaders in one view violate election + -- safety (cft.h would demote this leader to candidate). + if v.leadership == .leader then + fail + s!"{← curLoc}: ProposeRequestVote from {from_} to a leader in its own view {rTerm}" + electionGuard + becomeCandidate + else if !v.ticking && rTerm == v.currentView then + let names ← names + if decide (canStartElection (abs names v) (names.id v.nodeId)) then + fail + s!"{← curLoc}: accepted by the implementation, rejected by validation: ProposeRequestVote from {from_} to a node that is not ticking (known implementation and specification difference: cft.h ignores it, the specification starts an election)" + +def nominateSuccessor : M Unit := do + trace "nomination" + nominateSuccessorUnsafe + +/-- `init_as_backup(index, term, {})`, as the driver calls it for a joiner. -/ +def initAsBackup : M Unit := do + trace "init_as_backup" + let index ← inNat "seqno" + let term ← inNat "view" + -- The driver initialises a joiner once, before anything else happens to it. + let v ← getV + unless v.leadership == .none && v.currentView == 0 && v.lastIdx == 0 do + fail s!"{← curLoc}: init_as_backup on a node that is not fresh" + -- A snapshot at index 0 is no snapshot, and starts in view 0; any other is in a view. + unless (index == 0) == (term == 0) do + fail + s!"{← curLoc}: init_as_backup at index {index} in view {term}: index 0 iff view 0" + note (.initAsBackup index term) + -- From a snapshot, `term_history` is untraced: assume every entry up to `index` + -- is in view `term`, and the snapshotted entries are opaque (no hooks); a snapshot is + -- taken at a signature, so entry `index` is one. The node does not hold them (the + -- ledger starts after `index`, the base); the machine replaces them at release by a + -- ghost from a node that has committed them. + let views := if index == 0 then #[] else Array.replicate term 1 + let ledger := + (Array.replicate index { term, sig := false }).modify (index - 1) + ({ · with sig := true }) + -- The configurations the snapshot's hooks installed (outside the lock) are entries of it. + let ledger := + (← getV).configurations.foldl (init := ledger) + fun l c => + if c.idx ≥ 1 && c.idx ≤ index then + l.modify (c.idx - 1) ({ · with config := some c.nodes }) + else + l + setV + fun v => + { + v with + lastIdx := index, + commitIdx := index, + views, + ledger, + base := index, + baseView := term + } + becomeAwareOfNewTerm term + +/-- +`add_configuration` from `ConfigurationChangeHook` while a snapshot is installed, +outside the lock, before `init_as_backup`. The configuration version is input. +-/ +def outOfLockHook : M Unit := discard (addConfiguration none none) + +/-- `force_become_primary()` is untraced; its `become_leader` opens the section. -/ +def forceBecomePrimary : M Unit := do + setV fun v => { v with currentView := v.currentView + 2 } + let ok ← becomeLeader + unless ok do + fail "force_become_primary on a retired-committed node" + +/-- The driver dropping a queued message: no lock; the dropped message is input. -/ +def dropPendingTo : M Unit := do + trace "drop_pending_to" + emitStr "from_node_id" (← getV).nodeId + +/-! ## Dispatch: the handler an event starts -/ + +/-- `recv_message`: dispatch on the message type. -/ +def receive (from_ : NodeId) : Message -> M Unit + | .appendEntriesRequest r => recvAppendEntries from_ r + | .appendEntriesResponse r => recvAppendEntriesResponse from_ r + | .requestVoteRequest r => recvRequestVote from_ false r + | .requestPreVoteRequest r => recvRequestVote from_ true r + | .requestVoteResponse r => recvRequestVoteResponse from_ false r + | .requestPreVoteResponse r => recvRequestVoteResponse from_ true r + | .proposeRequestVoteRequest t => recvProposeRequestVote from_ t + +/-- +The handler the event `function` starts, given the delivered message (with its sender). +`become_leader` starts `force_become_primary` (whose own code is untraced). +-/ +def handlerFor (function : String) : Option (NodeId × Message) -> Option (M Unit) + | some (from_, m) => + if recvHeads.contains function then some (receive from_ m) else none + | none => + match function with + | "drop_pending_to" => some dropPendingTo + | "tick" => some periodic + | "replicate" => some replicate + | "nomination" => some nominateSuccessor + | "init_as_backup" => some initAsBackup + | "add_configuration" => some outOfLockHook + | "become_leader" => some forceBecomePrimary + | _ => none + +end Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Full.lean b/lean/consensus/Consensus/TraceValidation/Full.lean new file mode 100644 index 000000000000..0649f14cf0b5 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Full.lean @@ -0,0 +1,165 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Abs + +@[expose] public section + +/-! +# M_tv's working state (not reviewed) + +The handlers (`Consensus.TraceValidation.Aft`) run on `State`: the reviewed declared +state (`Exec.Declared`) with the whole ledger instead of the entries the node holds. For a +node that joined from a snapshot, the entries up to `base` are a ghost: the machine fills +them at the `init_as_backup` release from a node that has committed them +(`Consensus.TraceValidation.Machine.fillSnapshot`), so that the clean `initAsBackup` input +is admitted. `State.declared` projects them away; the machine checks that no hold's +outcome depends on them (`Machine.ghostFree`). + +`abs` and `agrees` are the reviewed `Declared.abs` and `Declared.agrees` with the whole +ledger as the held entries; the proofs relate them (`Consensus.TraceValidation.Proofs.Suffix`). +-/ + +namespace Consensus.TraceValidation.Exec + +/-- `Declared`, with the whole ledger. -/ +structure State where + nodeId : NodeId + currentView : Nat := 0 + lastIdx : Nat := 0 + commitIdx : Nat := 0 + views : Array Nat := #[] + committable : List Nat := [] + leadership : Leadership := .none + retired : Bool := false + retirementPhase : Option Phase := none + retirementIdx : Option Nat := none + retirementCommittableIdx : Option Nat := none + retiredCommittedIdx : Option Nat := none + votedFor : Option NodeId := none + leaderId : Option NodeId := none + votesForMe : List (Nat × List NodeId × Nat) := [] + isNewFollower : Bool := false + ticking : Bool := false + configurations : List Config := [] + allOtherNodes : List (NodeId × Peer) := [] + /-- The whole ledger: entry `i` is `ledger[i-1]`; up to `base`, a ghost. -/ + ledger : Array Entry := #[] + rcEntries : List (Nat × List NodeId) := [] + base : Nat := 0 + baseView : Nat := 0 +deriving DecidableEq, Inhabited + +/-- The declared state: the ledger after `base`. -/ +def State.declared (d : State) : Declared := + { + nodeId := d.nodeId + currentView := d.currentView + lastIdx := d.lastIdx + commitIdx := d.commitIdx + views := d.views + committable := d.committable + leadership := d.leadership + retired := d.retired + retirementPhase := d.retirementPhase + retirementIdx := d.retirementIdx + retirementCommittableIdx := d.retirementCommittableIdx + retiredCommittedIdx := d.retiredCommittedIdx + votedFor := d.votedFor + leaderId := d.leaderId + votesForMe := d.votesForMe + isNewFollower := d.isNewFollower + ticking := d.ticking + configurations := d.configurations + allOtherNodes := d.allOtherNodes + base := d.base + baseView := d.baseView + ledger := d.ledger.extract d.base d.ledger.size + rcEntries := d.rcEntries + } + +/-- +A declared state, with placeholders for the entries up to `base` it does not hold: view 0, +which no ledger entry has (`inv`'s `positive_terms`), and no signature or metadata. +-/ +def Declared.expand (d : Declared) : State := + { + nodeId := d.nodeId + currentView := d.currentView + lastIdx := d.lastIdx + commitIdx := d.commitIdx + views := d.views + committable := d.committable + leadership := d.leadership + retired := d.retired + retirementPhase := d.retirementPhase + retirementIdx := d.retirementIdx + retirementCommittableIdx := d.retirementCommittableIdx + retiredCommittedIdx := d.retiredCommittedIdx + votedFor := d.votedFor + leaderId := d.leaderId + votesForMe := d.votesForMe + isNewFollower := d.isNewFollower + ticking := d.ticking + configurations := d.configurations + allOtherNodes := d.allOtherNodes + base := d.base + baseView := d.baseView + ledger := Array.replicate d.base { term := 0, sig := false } ++ d.ledger + rcEntries := d.rcEntries + } + +end Consensus.TraceValidation.Exec + +namespace Consensus.TraceValidation + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) + +/-- `Declared.abs`, with the whole ledger as the held entries. -/ +def abs (names : Names) (d : State) : NodeState := + let peer (f : Exec.Peer -> Nat) (n : NodeID) : Nat := + match d.allOtherNodes.find? (fun (id, _) => names.id id == n) with + | some (_, p) => f p + | none => 0 + -- `votes_for_me` only counts the self-vote in configurations the node is in; + -- a (pre-vote) candidate has always voted for itself. + let votes := names.set (d.nodeId :: d.votesForMe.flatMap fun (_, vs, _) => vs) + { + role := absRole d.leadership + currentTerm := d.currentView + log := (d.ledger.toList.take d.lastIdx).map (absEntry names) + commitIndex := d.commitIdx + sentIndex := peer (·.sentIdx) + matchIndex := peer (·.matchIdx) + isNewFollower := d.isNewFollower + votedFor := d.votedFor.map names.id + primaryKnown := d.leaderId.isSome + votesGranted := votes + preVotesGranted := votes + retiredCommittedIndex := d.retiredCommittedIdx + } + +/-- `Declared.trackedPeers`. -/ +def trackedPeers (names : Names) (d : State) : List NodeID := + if d.leadership == .leader then d.allOtherNodes.map fun (id, _) => names.id id else [] + +/-- `Declared.agrees` on the whole ledger. -/ +def agrees (names : Names) (c : NodeState) (d : State) : Bool := + let a := abs names d + c.role == a.role + && c.currentTerm == a.currentTerm + && c.log == a.log + && c.commitIndex == a.commitIndex + && (trackedPeers names d).all + (fun n => c.sentIndex n == a.sentIndex n && c.matchIndex n == a.matchIndex n) + && c.isNewFollower == a.isNewFollower + && c.votedFor == a.votedFor + && c.primaryKnown == a.primaryKnown + && (a.role != .candidate || c.votesGranted == a.votesGranted) + && (a.role != .preVoteCandidate || c.preVotesGranted == a.preVotesGranted) + && c.retiredCommittedIndex == a.retiredCommittedIndex + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Handler.lean b/lean/consensus/Consensus/TraceValidation/Handler.lean new file mode 100644 index 000000000000..9496f213feb1 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Handler.lean @@ -0,0 +1,177 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Full + +@[expose] public section + +/-! +# M_tv extension: the handler monad (not reviewed) + +A lock hold is one run of a `cft.h` handler, written in `M`: a plain state and exception +monad over `Ctx`, with no suspension. The run consumes the hold's actions from +`Ctx.queue`, one per `trace` call, in order. The program counter is therefore the +number of actions consumed: M_tv steps an event by rerunning the handler from the +declared state at lock acquisition with one more action queued +(`Consensus.TraceValidation.Machine`). + +A run that has consumed every queued action stops (`Stop.blocked`) at the first state +mutation, trace or peek after the last trace point, so the state it stops in is the +state at that trace point. In `final` mode (the release) it never stops early, and +`look` sees `none` once the queue is empty. +-/ + +namespace Consensus.TraceValidation.Exec + +open Lean +open Consensus.Model.Node + +/-- What a hold did, in clean-model vocabulary, for the diagnostic lock-step check only. -/ +inductive Note where + /-- `ext`: an independent clean `sendEntries` (heartbeat or batch flush). -/ + | sendEntries (dest : NodeId) (endIdx : Nat) (ext : Bool) + | appendEntry (entry : Entry) + | batchFlush + | heartbeatTimeout + | electionTimeout + | checkQuorum + | initAsBackup (index term : Nat) +deriving Inhabited + +structure Ctx where + /-- Trace-wide parameters: node names and addresses. -/ + env : Env + vars : State + /-- Sends, in order, with clean node ids. -/ + outbox : List (CCF.Envelope NodeID Message) := [] + /-- The actions not yet consumed. -/ + queue : List Action + /-- The release: run to completion. -/ + final : Bool := false + /-- The action consumed last, whose inputs `in*` reads. -/ + cur : Option Action := none + /-- A trace point consumed an action and nothing has happened since. -/ + atPoint : Bool := false + label : Label := [] + notes : List Note := [] + +inductive Stop where + | error (msg : String) + /-- Every queued action is consumed: the state at the last trace point. -/ + | blocked (c : Ctx) + +abbrev M := StateT Ctx (Except Stop) + +def fail {α} (msg : String) : M α := throw (.error msg) + +/-- After a trace point: stop if no action is left (unless final), else go on. -/ +def yieldAtPoint : M Unit := do + let c ← get + if c.atPoint then + if c.queue.isEmpty && !c.final then throw (.blocked c) + set { c with atPoint := false, label := [] } + +def getV : M State := do + return (← get).vars + +def setV (f : State -> State) : M Unit := do + yieldAtPoint + modify fun c => { c with vars := f c.vars } + +/-- The next action, if any; `none` at release. -/ +def look : M (Option Action) := do + yieldAtPoint + let c ← get + match c.queue with + | a :: _ => return some a + | [] => if c.final then return none else throw (.blocked c) + +def lookFn : M (Option String) := do + return (← look).map (·.point) + +def curLoc : M String := do + match (← get).cur with + | some a => return s!"at {a.point}" + | none => return "between trace points" + +/-- Reach the trace point `fn`: it must be the next action. -/ +def trace (fn : String) : M Unit := do + yieldAtPoint + let c ← get + match c.queue with + | a :: rest => + unless a.point == fn do + fail s!"expected trace point {fn}, got {a.point}" + set { c with queue := rest, cur := some a, atPoint := true, label := [] } + | [] => + if c.final then + fail s!"expected trace point {fn} before lock release" + else + throw (.blocked c) + +/-- Label a field of the current trace point with the model's value. -/ +def emit (k : String) (model : Json) : M Unit := do + unless (← get).atPoint do + fail s!"emit {k} outside a trace point" + modify fun c => { c with label := c.label ++ [(k, model)] } + +def emitNat (k : String) (n : Nat) : M Unit := emit k (toJson n) +def emitStr (k : String) (s : String) : M Unit := emit k (toJson s) + +def liftE {α} (x : Except String α) : M α := do + match x with + | .ok a => return a + | .error e => fail s!"{← curLoc}: {e}" + +/-- An input field of the current action. -/ +def use (k : String) : M Json := do + let some a := (← get).cur | fail s!"no current action for input {k}" + match a.inputs.lookup k with + | some j => return j + | none => fail s!"{a.point}: {k} is not an input" + +def inNat (k : String) : M Nat := do + liftE (natural (← use k)) + +def inStr (k : String) : M String := do + liftE (← use k).getStr? + +def inBool (k : String) : M Bool := do + liftE (← use k).getBool? + +def parseNodes (j : Json) : Except String Nodes := do + let o ← j.getObj? + o.toList.mapM + fun (id, info) => do + let addr ← (← info.getObjVal? "address").getStr? + unless (← info.getObj?).size == 1 do + throw s!"node {id}: unexpected node info {info.compress}" + return (id, addr) + +def note (n : Note) : M Unit := modify fun c => { c with notes := c.notes ++ [n] } + +def names : M Names := do + return (← get).env.names + +/-- Send `m` to `dst`. -/ +def send (dst : NodeId) (m : Message) : M Unit := do + modify + fun c => + let x : CCF.Envelope NodeID Message := + { + source := c.env.names.id c.vars.nodeId, + target := c.env.names.id dst, + payload := m + } + { c with outbox := c.outbox ++ [x] } + +/-- Run a handler from `vars` on `queue`. -/ +def run (env : Env) (vars : State) (queue : List Action) (final : Bool) (h : M Unit) + : Except Stop Ctx := + match h.run ({ env, vars, queue, final } : Ctx) with + | .ok ((), c) => .ok c + | .error s => .error s + +end Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Invariant.lean b/lean/consensus/Consensus/TraceValidation/Invariant.lean new file mode 100644 index 000000000000..4a0e5552f490 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Invariant.lean @@ -0,0 +1,387 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Aft + +@[expose] public section + +/-! +# M_tv invariants (not reviewed) + +The refinement proof relates a node's clean state to its declared state by `Rel` +(`Consensus.TraceValidation.Proofs.Obligation`): the reviewed agreement (`agrees`) or, +before the node's first ledger entry, the clean initial state; in both cases with the +local invariant `inv` of the declared state. Messages in flight satisfy `msgInv`. + +The machine (`Consensus.TraceValidation.Machine`) evaluates `inv` at every release and +rejects the trace when a conjunct fails, so each handler obligation assumes `inv` of the +declared state at release rather than proving it. A rejection by a conjunct is of one of +two kinds, stated in its doc comment: + +* *first kind*: the state cannot arise in a correct implementation, so the trace exhibits + an implementation (or driver) bug; +* *second kind*: legitimate implementation behaviour that the frozen specification cannot + express; `knownDifference` describes it, and the diagnostic says it is a known + implementation and specification difference. + +`msgInv` stays a conclusion of each obligation about the messages it sends; the +diagnostic lock-step check (`Consensus.TraceValidation.Lockstep`) evaluates it at every +send. + +Each conjunct of `inv` is named; the names are what rejections and lock-step findings +report. +-/ + +namespace Consensus.TraceValidation + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State Leadership) + +/-- Signature indexes of the declared ledger in `(lo, hi]`. -/ +def signaturesIn (d : State) (lo hi : Nat) : List Nat := + (List.range' (lo + 1) (hi - lo)).filter fun i => d.ledger[i - 1]?.any (·.sig) + +/-- +Declared configurations against the clean ones, as (index, sorted members): equal, except +that the first declared index may be later than the clean one, up to the commit index. +-/ +def configurationsMatch (commitIdx : Nat) + : List (Nat × List NodeID) -> List (Nat × List NodeID) -> Bool + | (i, n) :: ds, (j, m) :: cs => + n == m && (i == j || (j <= i && i <= commitIdx)) && ds == cs + | [], [] => true + | _, _ => false + +/-- The named conjuncts of the local invariant. -/ +def invChecks (names : Names) (d : State) : List (String × Bool) := + let a := abs names d + let self := names.id d.nodeId + [ + -- First kind: `lastIdx` counts the ledger. + ("ledger_size", d.ledger.size == d.lastIdx), + -- First kind: the commit index is within the ledger. + ("commit_le_last", decide (d.commitIdx <= d.lastIdx)), + -- First kind: `committable_indices` are the signatures above the commit index. + ("committable", d.committable == signaturesIn d d.commitIdx d.lastIdx), + -- First kind: a positive commit index is at a signature. + ("commit_at_signature", d.commitIdx == 0 || d.ledger[d.commitIdx - 1]?.any (·.sig)), + -- First kind for nodes started by `create`/`join`: each entry's term is the view the + -- view history assigns to its index. A leader elected with commit index 0 skips the + -- election rollback (cft.h `become_leader`), which only driver start states reach. + ( + "terms_are_views", + (List.range' 1 d.lastIdx).all + fun i => d.ledger[i - 1]?.map (·.term) == some (d.viewAt i) + ), + -- First kind: the view history has at most one start per view. + ("views_bounded", decide (d.views.size <= d.currentView)), + -- First kind: a candidate has started no view since it became one (it incremented its + -- view from one bounding the view history and appended nothing), so its own view has + -- no start yet. + ("candidate_views", d.leadership != .candidate || d.views.size < d.currentView), + -- First kind: a leader is its own leader. + ("leader_knows_itself", d.leadership != .leader || d.leaderId == some d.nodeId), + -- First kind: at view 0 a node has no ledger and is neither leader nor candidate. + ( + "view_zero", + d.currentView != 0 + || (d.lastIdx == 0 && d.leadership != .leader && d.leadership != .candidate) + ), + -- First kind (given that a primary rejects an unchanged configuration): the declared + -- configurations are the clean active configurations, except that the first may sit at + -- a later index at or below the commit index. A joiner's snapshot hook (hooks.h) + -- installs the latest configuration at the version of the snapshot's last nodes-table + -- write, which follows the configuration's entry when a later write (a node's + -- deletion) kept the membership. cft.h reads a configuration's index only against + -- later configurations and indexes above the commit index, or for its order, so the + -- two indexes behave alike. + ( + "configurations", + d.lastIdx == 0 + || configurationsMatch d.commitIdx + (d.configurations.map + (fun c => (c.idx, (names.set (c.nodes.map Prod.fst)).sort))) + ((activeConfigurations a.log a.commitIndex).map + fun c => (c.index, c.nodes.sort)) + ), + -- Second kind (`knownDifference`): a node with a role has exactly the clean eligible + -- peers. cft.h keeps peers across a rollback that the clean model drops. + ( + "peers", + d.lastIdx == 0 + || d.leadership == .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers a (names.id d.nodeId)).sort + ), + -- First kind: the same for a node without a role. + ( + "peers_without_role", + d.lastIdx == 0 + || d.leadership != .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers a (names.id d.nodeId)).sort + ), + -- First kind: every view start is positive. + ("views_positive", d.views.all (0 < ·)), + -- First kind: the node voted for is named in the table. + ("voted_for_named", d.votedFor.all fun x => names.name (names.id x) == x), + -- First kind: once the node's own retirement is committed, the latch is set. + ( + "latched", + d.retiredCommittedIdx.isSome + || !(d.ledger.toList.take d.commitIdx).any (·.retired.contains d.nodeId) + ), + -- First kind: the latched index is the first committed entry confirming this node's + -- retirement (what the clean `recordCommit` latches). + ( + "rci_first", + d.retiredCommittedIdx + == firstLogIndexAfter (a.log.take d.commitIdx) 0 + fun c => decide (self ∈ c.metadata.retirementConfirmations) + ), + -- First kind: the latched confirmation follows a configuration that removes this node, + -- so the clean model clears the role when it latches. + ( + "rci_retired", + d.retiredCommittedIdx.all fun j => (retirementIndexInLog self (a.log.take j)).isSome + ), + -- First kind: a primary without ledger entries has no peers. The clean primary with + -- an empty log has no eligible peers, so it cannot nominate one. + ( + "empty_leader_alone", + d.lastIdx != 0 || d.leadership != .leader || d.allOtherNodes.isEmpty + ), + -- Second kind (`knownDifference`): an initialised node without ledger entries has no + -- peers, as the clean node without a log has no eligible peers. cft.h keeps peers + -- across a rollback to an empty ledger. + ( + "empty_ledger_alone", + (d.currentView == 0 && d.leadership == .none) + || d.lastIdx != 0 + || d.allOtherNodes.isEmpty + ), + -- First kind: configuration members and peers are named in the table, so `names.id` + -- is injective on them and string membership is clean id membership. + ( + "names_round_trip", + (d.configurations.flatMap (·.nodes.map Prod.fst) + ++ d.allOtherNodes.map Prod.fst).all + fun id => names.name (names.id id) == id + ), + -- First kind: M_tv's `is_retired_committed` is the clean `isRetiredCommitted`. + ("retired_committed", d.isRetiredCommitted == decide (a.isRetiredCommitted self)), + -- First kind: the pending retired-committed records are exactly the uncommitted + -- entries with retirement confirmations, in ledger order, with their confirmations. + ( + "rc_entries", + d.rcEntries + == (List.range' (d.commitIdx + 1) (d.lastIdx - d.commitIdx)).filterMap + fun i => + d.ledger[i - 1]?.bind + fun e => if e.retired.isEmpty then none else some (i, e.retired) + ), + -- First kind: a leader has committed everything the clean model can commit, i.e. its + -- commit index is at least the clean `highestCommittableIndex` (which never goes + -- below the commit index, so the two are equal). + ( + "commit_maximal", + d.leadership != .leader || highestCommittableIndex a self <= d.commitIdx + ), + -- First kind: the view history is sorted by index. + ("views_sorted", (d.views.toList.zip d.views.toList.tail).all fun (x, y) => x <= y), + -- First kind: every view starts at most one past the end of the ledger. + ("views_le_last", d.views.all (· <= d.lastIdx + 1)), + -- First kind: every ledger entry has a positive term. + ("positive_terms", d.ledger.all (0 < ·.term)), + -- First kind: a leader has sent and seen acknowledged no index beyond its ledger. + -- Stricter than cft.h: cft.h tolerates one peer acknowledging beyond the leader's log + -- (it only throws once a quorum does); a correct follower never does. + ( + "peer_bounds", + d.leadership != .leader + || d.allOtherNodes.all + fun (_, p) => p.sentIdx <= d.lastIdx && p.matchIdx <= d.lastIdx + ), + -- First kind: ids in ledger configurations and retirement confirmations are named in + -- the table. + ( + "ledger_names_round_trip", + d.ledger.all + fun e => + ((e.config.getD []).map Prod.fst ++ e.retired).all + fun id => names.name (names.id id) == id + ), + -- First kind: once the node knows a configuration or peer, the name table is strictly + -- sorted, so it is duplicate-free and `names.id` is order-preserving on named ids. + ( + "names_sorted", + (d.configurations.isEmpty && d.allOtherNodes.isEmpty) + || (names.known.toList.zip names.known.toList.tail).all fun (x, y) => decide (x < y) + ), + -- First kind: the members of each active configuration are distinct (cft.h's + -- `Configuration::Nodes` is a map), so a configuration's size is its clean size. + ( + "configuration_members_distinct", + d.configurations.all + fun c => (c.nodes.map Prod.fst).eraseDups == c.nodes.map Prod.fst + ), + -- First kind: a (pre-)candidate has one vote record per active configuration, at its + -- index with its quorum, whose votes are duplicate-free and are exactly the members of + -- that configuration that are the node itself or voted for it in any configuration. + ( + "votes_for_me", + !(d.leadership == .candidate || d.leadership == .preVoteCandidate) + || (d.votesForMe.length == d.configurations.length + && let voters := d.nodeId :: d.votesForMe.flatMap (·.2.1) + (d.votesForMe.zip d.configurations).all + fun ((i, vs, q), c) => + let members := (c.nodes.map Prod.fst).filter voters.contains + i == c.idx + && q == State.quorum c.nodes.length + && vs.eraseDups == vs + && vs.all members.contains + && members.all vs.contains) + ), + -- First kind: the node's own id is named in the table (the validator's table holds + -- every node id of the trace), so `names.id` separates it from other named ids. + ("self_named", names.name (names.id d.nodeId) == d.nodeId), + -- First kind: a primary without ledger entries knows no configuration. A joining node + -- learns its start configuration before it has ledger entries, but becomes primary + -- only by an election, which needs ledger entries, or as the genesis node, which has + -- no configuration until its first entry's hook. + ( + "empty_leader_unconfigured", + d.lastIdx != 0 || d.leadership != .leader || d.configurations.isEmpty + ), + -- First kind: a leader is not retired-committed. cft.h clears the leadership when the + -- node's retirement commits, and a retired-committed node does not become leader. + ("leader_not_retired_committed", d.leadership != .leader || !d.isRetiredCommitted), + -- First kind: the peers are strictly sorted by node id (cft.h's `all_other_nodes` is a + -- `std::map`), so re-inserting a peer keeps every peer in place. + ( + "peers_sorted", + (d.allOtherNodes.zip d.allOtherNodes.tail).all fun (p, q) => decide (p.1 < q.1) + ), + -- First kind: a leader's pending retired-committed records name no other node that is a + -- member of the configurations left once the record commits (CCF never reuses a node + -- id, and a node's removal commits before its retirement is confirmed). cft.h would + -- otherwise erase the peer at the commit and re-create it, with an AppendEntries, as it + -- drops the older configurations. + ( + "rc_entries_retired", + d.leadership != .leader + || d.rcEntries.all + fun (ver, ids) => + ids.all + fun id => + id == d.nodeId + || !(Exec.commit.pop ver d.configurations).any (·.nodes.any (·.1 == id)) + ), + -- First kind: a leader's pending retirement confirmations name removed nodes (a node is + -- confirmed only once its removal commits, and CCF never reuses a node id), so no + -- configuration it appends names them. + ( + "rc_entries_removed", + d.leadership != .leader + || d.rcEntries.all + fun (_, ids) => ids.all fun id => decide (names.id id ∈ removedNodes a.log) + ), + -- First kind: a leader's nodes whose retirement completed are removed nodes (CCF never + -- reuses a node id), so no configuration it appends names them. + ( + "retirement_completed_removed", + d.leadership != .leader || decide (a.retirementCompletedNodes ⊆ removedNodes a.log) + ), + -- First kind: a leader that is the only node of its configurations has not been removed + -- (its latest configuration names it). + ( + "alone_not_removed", + d.leadership != .leader + || !d.configurations.all (·.nodes.all (·.1 == d.nodeId)) + || decide (self ∉ removedNodes a.log) + ), + -- First kind: every active configuration has a member. cft.h's configurations come from + -- the start state or from the ledger, and a configuration entry names at least one node. + ("configurations_nonempty", d.configurations.all fun c => !c.nodes.isEmpty), + -- First kind: every member of an active configuration is in the name table (the + -- validator's table holds every node id of the trace, and a configuration lists its + -- members with their addresses), so `names.id` orders members as their names do. + ( + "members_known", + (d.configurations.flatMap (·.nodes.map Prod.fst)).all names.known.contains + ) + ] + +/-- The local invariant of a declared state. -/ +def inv (names : Names) (d : State) : Bool := (invChecks names d).all (·.2) + +/-- +The conjuncts whose failure is legitimate implementation behaviour that the frozen +specification cannot express (second kind), with the scenario. +-/ +def knownDifference : String -> Option String + | "peers" => + some + ("cft.h keeps a peer in all_other_nodes across a rollback that the clean model " + ++ "drops: n0 appends a configuration adding n3 without replicating it and is " + ++ "partitioned, n1 wins the next view, and when n0 rolls the configuration back it " + ++ "keeps n3 as a peer") + | "empty_ledger_alone" => + some + ("cft.h keeps a peer in all_other_nodes across a rollback to an empty ledger, " + ++ "which the clean model, without configurations, does not have: as for peers, " + ++ "when the rolled-back configuration was the node's only one") + | _ => none + +/-- Why `inv` fails: the failed conjuncts, each second-kind one with its known difference. -/ +def invDiagnostic (names : Names) (d : State) : String := + let failed := (invChecks names d).filter (!·.2) |>.map (·.1) + let described := + failed.map + fun n => + match knownDifference n with + | some why => + s!"{n} (accepted by the implementation, rejected by validation: known implementation and specification difference: {why})" + | none => n + s!"invariant fails: {", ".intercalate described}" + +/-- +What every message in flight satisfies: it goes between two different nodes whose ids +round-trip through the name table, an AppendEntries batch is in one positive view, the +ids in its entries' configurations and retirement confirmations round-trip too, and its +transactions have request id 0. +-/ +def msgInv (names : Names) (e : CCF.Envelope NodeID Message) : Bool := + names.id (names.name e.source) == e.source + && e.source != e.target + && (match e.payload with + | .appendEntriesRequest r => + r.entries.all + fun x => + ((x.content.metadata.configuration.map (·.sort)).getD [] + ++ x.content.metadata.retirementConfirmations.sort).all + fun i => names.id (names.name i) == i + | _ => true) + && (match e.payload with + | .appendEntriesRequest r => + (r.entries.all + fun x => + some x.term == r.entries.getLast?.map (·.term) + && 0 < x.term + && x.term <= r.term) + && (r.prevLogIndex == 0 || 0 < r.prevLogTerm) + | _ => true) + -- Every AppendEntries transaction has request id 0, as `absEntry` writes it: the clean + -- request id is not observable, so received entries round-trip through the ledger. + && (match e.payload with + | .appendEntriesRequest r => + r.entries.all + fun x => + match x.content with + | .transaction q _ => q == 0 + | .signature => true + | _ => true) + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Machine.lean b/lean/consensus/Consensus/TraceValidation/Machine.lean new file mode 100644 index 000000000000..7259041b1cfd --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Machine.lean @@ -0,0 +1,359 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.Model +public import Consensus.TraceValidation.Abs +public import Consensus.TraceValidation.Aft +public import Consensus.TraceValidation.Invariant +public import CCF.Sections + +@[expose] public section + +/-! +# M_tv as a `CCF.Sections.Machine` (not reviewed) + +The local state is the reviewed declared state (`Exec.State`, at the last release) plus +`sec`, the open lock hold if any: its head event, the message it delivered, the declared +state at lock acquisition (`saved`), the hold's actions so far (the program counter), and +the handler's context at the latest trace point. + +`step` runs one event: it reruns the hold's `cft.h` handler from `saved` with the event's +action appended, up to that action's trace point, and observes the event against the +declared state there (`Exec.observe`, reviewed). `close` runs the handler to completion +(the trailing code after the last trace point) and returns its sends. A joiner's +`init_as_backup` additionally takes the ledger prefix up to its snapshot from a node that +has committed it (the donor): the implementation installs a snapshot, whose entries are +not traced; until some node has committed the snapshot index, the release waits. Every +release also checks the local invariant `inv` of the declared state it releases, and +rejects the trace, naming the failed conjuncts, when it does not hold. +-/ + +namespace Consensus.TraceValidation + +open Lean +open CCF (Finset) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State Ev Ctx Action) + +/-- An open lock hold. -/ +structure Sec where + /-- The event that opened the hold. -/ + head : Ev + /-- The message the head delivered, if any, with its sender. -/ + recv : Option (NodeID × Message) + /-- The declared state at lock acquisition. -/ + saved : State + /-- The hold's actions so far. -/ + actions : List Action + /-- The handler's context at the latest trace point. -/ + ctx : Ctx + +/-- M_tv's local state. -/ +structure Local where + /-- The declared state at the last release. -/ + vars : State + /-- The open hold. -/ + sec : Option Sec := none + +def Local.idle (l : Local) : Bool := l.sec.isNone + +/-- The working state at the latest trace point. -/ +def current (l : Local) : State := + match l.sec with + | some s => s.ctx.vars + | none => l.vars + +/-- The declared state at the latest trace point, with the model's label there (none when idle). -/ +def declare (l : Local) : Exec.Declared × Exec.Label := + match l.sec with + | some s => (s.ctx.vars.declared, s.ctx.label) + | none => (l.vars.declared, []) + +/-- +A node before its first event. Whether the host has already called `start_ticking()` is +not traced (the driver does at creation, a real node does not), so it is a parameter. +-/ +def initialLocal (env : Env) (node : NodeID) (ticking : Bool) : Local := + { vars := { nodeId := env.names.name node, ticking } } + +/-- +The genesis primary before its first ledger entry: the clean model starts it already +past `force_become_primary` and the genesis `replicate`, which `cft.h` still has to run. +-/ +def pristine (env : Env) (d : State) : Bool := + env.genesis.min? == some (env.names.id d.nodeId) && d.lastIdx == 0 + +/-- +Whether the host has initialised the node: `init_as_backup` or `force_become_primary` made +it a follower or leader in a positive view (a retired-committed node keeps its view). +-/ +def initialised (s : State) : Bool := s.currentView != 0 || s.leadership != .none + +/-- +What an uninitialised node may do. The host creates the consensus and initialises it in +one callback (node_state.h: the snapshot's hooks then `init_as_backup` for a joiner, +`force_become_primary` for a genesis or recovery primary), so no message is delivered to +it before; a tick finds it not ticking, and the driver may drop messages it sent. +-/ +def uninitialisedHeads : List String := + ["add_configuration", "tick", "init_as_backup", "become_leader", "drop_pending_to"] + +/-- +Events that may open a hold in state `s`: lock-taking events, the out-of-lock snapshot +hook, and the `become_leader` of the genesis primary's untraced `force_become_primary`; +before the node is initialised, only those of `uninitialisedHeads`. +-/ +def isHead (env : Env) (s : State) (e : Ev) : Bool := + (initialised s || uninitialisedHeads.contains e.function) + && (opens e + || Exec.outOfLock s.declared e + || (e.function == "become_leader" + && s.currentView == 0 + && s.leadership == .none + && pristine env s)) + +def at_ {α : Type} (e : Ev) (x : Except String α) : Except String α := + x.mapError fun err => s!"{e.loc} h_ts={e.hts} node={e.node}: {err}" + +/-- Run the handler that `head` opens from `saved` on `actions`; in `final` mode to completion. -/ +def runHold (env : Env) (saved : State) (recv : Option (NodeID × Message)) (head : Ev) + (actions : List Action) (final : Bool) + : Except String Ctx := + if !isHead env saved head then + .error s!"{head.function} is not a section head here and no section is open" + else + match Exec.handlerFor head.function + (recv.map fun (n, m) => (env.names.name n, m)) with + | none => .error s!"{head.function} cannot open a section with this delivery" + | some h => + match Exec.run env saved actions final h with + | .ok c => + if c.queue.isEmpty then + .ok c + else + .error + s!"event not explained by the section opened at {head.loc} h_ts={head.hts}" + | .error (.blocked c) => + if final then .error "internal: blocked at release" else .ok c + | .error (.error err) => .error err + +def sameLedger (x y : Array Exec.Entry) : Bool := + @decide (x = y) (withPtrEqDecEq x y fun _ => inferInstance) + +/-- `a = b`, cheaply when the ledger (or the whole state) is shared, as it is across most holds. -/ +def sameVars (a b : State) : Bool := + @decide (a = b) + (withPtrEqDecEq a b + fun _ => + if h + : sameLedger a.ledger b.ledger = true + ∧ { a with ledger := #[] } = { b with ledger := #[] } then + isTrue + (by + obtain ⟨l, r⟩ := h + simp only [sameLedger, decide_eq_true_eq] at l + cases a; cases b; simp_all) + else + isFalse (by intro e; subst e; simp [sameLedger] at h)) + +/-- One event. -/ +def stepE (env : Env) (l : Local) (recv : Option (NodeID × Message)) (e : Ev) + : Except String Local := + match Exec.actionOf e with + | .error err => at_ e (.error err) + | .ok a => + match l.sec with + | none => + match runHold env l.vars recv e [a] false with + | .error err => at_ e (.error err) + | .ok c => + match Exec.observe e c.vars.declared c.label with + | .error err => at_ e (.error err) + | .ok () => + if opens e && !sameVars c.vars l.vars then + at_ e (.error "the lock-taking event changed the declared state") + else + .ok + { + l with + sec := + some + { + head := e, recv, saved := l.vars, actions := [a], ctx := c + } + } + | some s => + match recv with + | some _ => at_ e (.error "a message delivered inside a section") + | none => + match runHold env s.saved s.recv s.head (s.actions ++ [a]) false with + | .error err => at_ e (.error err) + | .ok c => + match Exec.observe e c.vars.declared c.label with + | .error err => at_ e (.error err) + | .ok () => + .ok + { + l with + sec := some { s with actions := s.actions ++ [a], ctx := c } + } + +/-! ## Release -/ + +/-- The snapshot a joiner's hold installed, from its notes. -/ +def snapshotOf (c : Ctx) : Option (Nat × Nat) := + c.notes.findSome? + fun + | .initAsBackup index term => some (index, term) + | _ => none + +/-- +Fill a joiner's ledger prefix up to its snapshot `index` (its `base`) from a donor: another +node whose declared state has committed `index`. The joiner does not hold the prefix +(`State.declared` drops it): it is a ghost, for the proof. `init_as_backup` gets an empty term history from +the driver, so every snapshotted entry is in view `term`; the donor's entries must agree. +-/ +def fillSnapshot (others : List (NodeID × Local)) (index term : Nat) (vars : State) + : Except String State := + match others.find? + fun (_, o) => index <= o.vars.commitIdx && index <= o.vars.ledger.size with + | none => .error s!"wait: no node has committed {index} yet" + | some (_, donor) => + let prefix_ := donor.vars.ledger.extract 0 index + if !prefix_.all (·.term == term) then + .error + s!"snapshot at {index} in view {term} spans earlier views {prefix_.toList.map (·.term) |>.eraseDups}, which the driver's empty term history cannot express" + -- A snapshot is taken at a signature. + else if index != 0 && !prefix_[index - 1]?.any (·.sig) then + .error s!"snapshot at {index}: the donor's entry {index} is not a signature" + -- The snapshot's hooks installed configurations of the snapshotted prefix. hooks.h + -- installs a snapshot's configuration at the version of the snapshot's last write + -- to the nodes table, which may follow the entry that set the membership (a node's + -- deletion does not change it): the configuration in force at that index. + else if !vars.configurations.all + fun c => + 1 <= c.idx + && c.idx <= index + && (prefix_.extract 0 c.idx).toList.reverse.findSome? (·.config) + == some c.nodes then + .error + s!"snapshot at {index}: the configurations its hooks installed, {vars.configurations.map (·.idx)}, are not configurations of the donor's prefix" + else if prefix_.any (·.retired.contains vars.nodeId) then + .error + s!"snapshot at {index}: the snapshotted prefix retires the joiner {vars.nodeId}" + else + .ok { vars with ledger := prefix_ ++ vars.ledger.extract index vars.ledger.size } + +/-- The declared state at release: a joiner's snapshot prefix is filled from a donor. -/ +def closeVars (others : List (NodeID × Local)) (head : Ev) (c : Ctx) + : Except String State := + match snapshotOf c with + | some (index, term) => + if head.function == "init_as_backup" then + fillSnapshot others index term c.vars + else + .ok c.vars + | none => .ok c.vars + +/-- +A hold from a pristine state may only bring the node to where the clean model starts it: +it receives nothing and sends nothing, and leaves the node pristine or in the clean initial +state; no other hold makes a node pristine. This is the one lifecycle check M_tv adds to +`cft.h`; it rejects a genesis node that does anything but `force_become_primary` and +replicate the genesis configuration first, or that later truncates its ledger to nothing. +-/ +def genesisOk (env : Env) (s : Sec) (c : Ctx) (vars : State) : Bool := + if pristine env s.saved then + s.recv.isNone + && c.outbox.isEmpty + && (pristine env vars + || agrees env.names + (Consensus.Model.initialNodeState env.genesis (env.names.id vars.nodeId)) + vars) + else + !pristine env vars + +/-- +The release check of the local invariant: `inv` of the declared state at release. A hold +that leaves the declared state as it was at acquisition, as most do, keeps `inv` without +evaluating it, because that state was itself checked at its release (or is initial). +-/ +def keepsInv (names : Names) (saved vars : State) : Bool := + sameVars vars saved || inv names vars + +/-- +The snapshot base is committed, and the ledger has the snapshot's signature there, in the +snapshot view: what the declared state's relation (`Exec.Declared.agrees`) says of the +prefix the node does not hold. Checked at every release. +-/ +def baseOk (d : State) : Bool := + d.base <= d.commitIdx + && (d.base == 0 || d.ledger[d.base - 1]?.any fun e => e.sig && e.term == d.baseView) + +/-- +The hold's outcome does not depend on the ledger up to the snapshot base, which the node +does not hold: rerun from the saved declared state with placeholders there +(`Declared.expand`), it releases the same declared state and sends. Checked at every +release of a node with a base; the placeholders are in view 0, so any entry read there +and sent, or term read there, differs. Accepted by the implementation, rejected by +validation: a primary that joined from a snapshot sends a follower that lags below its +base AppendEntries below it; the host (`node_connections.h`) cannot read those entries and +drops the message, while the specification sends them. +-/ +def ghostFree (env : Env) (s : Sec) (c : Ctx) : Bool := + s.saved.base == 0 + || match runHold env s.saved.declared.expand s.recv s.head s.actions true with + | .ok c' => c'.vars.declared == c.vars.declared && c'.outbox == c.outbox + | .error _ => false + +/-- +Release: run the hold's trailing code; the declared state at release and the sends. The +declared state at release must satisfy `inv` and `baseOk`, and the hold be `ghostFree`. +-/ +def closeX (env : Env) (others : List (NodeID × Local)) (l : Local) + : Except String (Local × List (CCF.Envelope NodeID Message) × Ctx) := + match l.sec with + | none => .error "release outside a section" + | some s => + let loc := s!"release of the section opened at {s.head.loc} h_ts={s.head.hts}" + match runHold env s.saved s.recv s.head s.actions true with + | .error err => .error s!"{loc}: {err}" + | .ok c => + match closeVars others s.head c with + | .error err => + .error (if err.startsWith "wait:" then err else s!"{loc}: {err}") + | .ok vars => + if genesisOk env s c vars then + if keepsInv env.names s.saved vars then + if baseOk vars then + if ghostFree env s c then + .ok ({ vars }, c.outbox, c) + else + .error + s!"{loc}: the hold's outcome depends on the ledger up to the snapshot base {s.saved.base}, which the node does not hold (if it sends AppendEntries below the base: accepted by the implementation, rejected by validation: known implementation and specification difference: the host cannot read entries below a snapshot base and drops the message, the specification sends them)" + else + .error + s!"{loc}: snapshot base {vars.base} in view {vars.baseView} not a committed signature" + else + .error s!"{loc}: {invDiagnostic env.names vars}" + else + .error + s!"{loc}: the genesis node must first become primary and replicate the genesis configuration, alone" + +/-- M_tv as an event-granular node machine. -/ +def machine (env : Env) : CCF.Sections.Machine NodeID Message Local Ev where + init node l := + env.names.id (env.names.name node) = node + ∧ (node ∈ env.genesis → env.genesis.min? = some node) + ∧ ∃ ticking, l = initialLocal env node ticking + idle := Local.idle + opens := opens + step _ l recv e := (stepE env l recv e).toOption + close others _ l := ((closeX env others l).toOption).map fun (l, sends, _) => (l, sends) + +/-- The clean protocol M_tv refines. -/ +abbrev protocol (env : Env) := Consensus.Model.protocol env.genesis + +end Consensus.TraceValidation From 57cf5a6429216094fa9f3822a1cc2feae3282861 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:08:02 +0000 Subject: [PATCH 07/25] Replace the consensus replayer with the M_tv validator The old replayer checked driver observations against direct clean-model transitions and could not follow real nodes or cft.h's own control flow. The validator splits a trace into per-node streams, runs them through M_tv with lock-hold sections, and compares every trace point with the declared state; `--refine` additionally runs every release in lock step against the clean model. The old Replay modules, their test and fixtures are replaced by fixtures captured from the native driver, and CI validates them and the scenario captures with `--refine`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/workflows/lean-package.yml | 2 +- .github/workflows/lean.yml | 2 +- lean/consensus/Consensus.lean | 5 +- lean/consensus/Consensus/Replay/Input.lean | 114 ----- .../Consensus/Replay/Interpreter.lean | 375 --------------- .../consensus/Consensus/Replay/Reduction.lean | 438 ------------------ .../Consensus/Tests/ReplayDelivery.lean | 55 --- .../Consensus/Tests/TraceValidationHooks.lean | 194 ++++++++ .../Consensus/TraceValidation/Lockstep.lean | 253 ++++++++++ .../Consensus/TraceValidation/Validator.lean | 354 ++++++++++++++ lean/consensus/replay/ReplayMain.lean | 71 ++- lean/consensus/replay/fixtures/README.md | 42 +- .../fixtures/invalid/bootstrap-event.ndjson | 13 - .../invalid/bootstrap-flush-send.ndjson | 30 -- .../fixtures/invalid/commit-mismatch.ndjson | 64 +++ .../invalid/configuration-mismatch.ndjson | 64 +++ .../fixtures/invalid/disabled-append.ndjson | 26 -- .../fixtures/invalid/malformed-append.ndjson | 25 - .../invalid/match-idx-mismatch.ndjson | 64 +++ .../fixtures/invalid/missing-commit.ndjson | 63 +++ .../fixtures/invalid/missing-field.ndjson | 64 +++ .../fixtures/invalid/missing-packet.ndjson | 24 - .../fixtures/invalid/missing-send.ndjson | 63 +++ .../fixtures/invalid/packet-mismatch.ndjson | 88 +++- .../fixtures/invalid/reordered-events.ndjson | 64 +++ .../invalid/retirement-node-mismatch.ndjson | 7 - .../invalid/retirement-nonadjacent.ndjson | 8 - .../fixtures/invalid/retirement-orphan.ndjson | 6 - .../invalid/retirement-seqno-mismatch.ndjson | 7 - .../invalid/retirement-signature.ndjson | 7 - .../fixtures/invalid/snapshot-mismatch.ndjson | 24 - .../fixtures/invalid/state-mismatch.ndjson | 64 +++ .../invalid/uncommitted-snapshot.ndjson | 18 - .../fixtures/invalid/ungrouped-event.ndjson | 24 - .../invalid/unknown-trace-point.ndjson | 64 +++ .../invalid/unsupported-snapshot-field.ndjson | 24 - .../replay/fixtures/valid/append.ndjson | 40 ++ .../replay/fixtures/valid/bootstrap.ndjson | 12 - .../replay/fixtures/valid/reconfig_0_1.ndjson | 94 ++++ .../fixtures/valid/rejected-replicate.ndjson | 5 - .../replay/fixtures/valid/replication.ndjson | 28 -- .../fixtures/valid/startup_2nodes.ndjson | 64 +++ 42 files changed, 1706 insertions(+), 1347 deletions(-) delete mode 100644 lean/consensus/Consensus/Replay/Input.lean delete mode 100644 lean/consensus/Consensus/Replay/Interpreter.lean delete mode 100644 lean/consensus/Consensus/Replay/Reduction.lean delete mode 100644 lean/consensus/Consensus/Tests/ReplayDelivery.lean create mode 100644 lean/consensus/Consensus/Tests/TraceValidationHooks.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Lockstep.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Validator.lean delete mode 100644 lean/consensus/replay/fixtures/invalid/bootstrap-event.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/bootstrap-flush-send.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/commit-mismatch.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/configuration-mismatch.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/disabled-append.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/malformed-append.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/match-idx-mismatch.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/missing-commit.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/missing-field.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/missing-packet.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/missing-send.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/reordered-events.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/retirement-node-mismatch.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/retirement-nonadjacent.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/retirement-orphan.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/retirement-seqno-mismatch.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/retirement-signature.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/snapshot-mismatch.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/state-mismatch.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/uncommitted-snapshot.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/ungrouped-event.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/unknown-trace-point.ndjson delete mode 100644 lean/consensus/replay/fixtures/invalid/unsupported-snapshot-field.ndjson create mode 100644 lean/consensus/replay/fixtures/valid/append.ndjson delete mode 100644 lean/consensus/replay/fixtures/valid/bootstrap.ndjson create mode 100644 lean/consensus/replay/fixtures/valid/reconfig_0_1.ndjson delete mode 100644 lean/consensus/replay/fixtures/valid/rejected-replicate.ndjson delete mode 100644 lean/consensus/replay/fixtures/valid/replication.ndjson create mode 100644 lean/consensus/replay/fixtures/valid/startup_2nodes.ndjson diff --git a/.github/workflows/lean-package.yml b/.github/workflows/lean-package.yml index 318225f28560..06f573751be2 100644 --- a/.github/workflows/lean-package.yml +++ b/.github/workflows/lean-package.yml @@ -111,7 +111,7 @@ jobs: shopt -s failglob for trace in lean/consensus/replay/fixtures/valid/*.ndjson; do echo "::group::Validate $trace" - lean/consensus/.lake/build/bin/consensus-replay "$trace" + lean/consensus/.lake/build/bin/consensus-replay --refine "$trace" echo "::endgroup::" done diff --git a/.github/workflows/lean.yml b/.github/workflows/lean.yml index 339c19a99826..35a58cb8d971 100644 --- a/.github/workflows/lean.yml +++ b/.github/workflows/lean.yml @@ -268,7 +268,7 @@ jobs: shopt -s failglob for trace in "$RUNNER_TEMP"/cft-scenario-traces/*.ndjson; do echo "::group::Validate $trace" - lean/consensus/.lake/build/bin/consensus-replay "$trace" + lean/consensus/.lake/build/bin/consensus-replay --refine "$trace" echo "::endgroup::" done diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 9b86cb7dc5f9..e4ff7c14d2c3 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -1,8 +1,7 @@ module public import Consensus.Properties -public import Consensus.Replay.Reduction -public import Consensus.TraceValidation.Machine +public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces -import Consensus.Tests.ReplayDelivery +import Consensus.Tests.TraceValidationHooks diff --git a/lean/consensus/Consensus/Replay/Input.lean b/lean/consensus/Consensus/Replay/Input.lean deleted file mode 100644 index 0f774bd04f62..000000000000 --- a/lean/consensus/Consensus/Replay/Input.lean +++ /dev/null @@ -1,114 +0,0 @@ -module - --- Copyright (c) Microsoft Corporation. All rights reserved. --- Licensed under the Apache 2.0 License. - -public import Consensus.Replay.Interpreter - -public section - -namespace Consensus.Replay - -open Lean - -def require (condition : Bool) (message : String) : Except String Unit := - unless condition do throw message - -def object (value : Json) : Except String (List (String × Json)) := - (·.toList) <$> value.getObj? - -def field (value : Json) (key : String) : Except String Json := - (value.getObjVal? key).mapError (fun error => s!"{key}: {error}") - -def optional (value : Json) (key : String) : Option Json := - (value.getObjVal? key).toOption - -def text (value : Json) : Except String String := - value.getStr? - -def natural : Json → Except String Nat - | .num { mantissa := .ofNat value, exponent := 0 } => pure value - | _ => throw "expected natural number" - -def string (value : Json) (key : String) : Except String String := - field value key >>= text - -def nat (value : Json) (key : String) : Except String Nat := - field value key >>= natural - -def boolean (value : Json) (key : String) : Except String Bool := - field value key >>= Json.getBool? - -def configuration (value : Json) : Except String (List String) := do - let nodes ← object (← field value "nodes") - return nodes.map Prod.fst - -structure Record where - file : String - line : Nat - value : Json -deriving Inhabited - -def Record.location (record : Record) : String := s!"{record.file}:{record.line}" - -/-- Read one JSON record per line without a schema pass. -/ -def parseLog (file input : String) : Except String (Array Record) := do - let mut records := #[] - let lines := if input.isEmpty then [] else input.splitOn "\n" - let lines := if input.endsWith "\n" then lines.dropLast else lines - for raw in lines, line in [1:lines.length + 1] do - let raw := if raw.endsWith "\r" then raw.dropEnd 1 |>.toString else raw - let value ← (Json.parse raw).mapError (fun error => s!"{file}:{line}: {error}") - records := records.push { file, line, value } - return records - -def readLog (path : System.FilePath) : IO (Except String (Array Record)) := do - let path ← IO.FS.realPath path - let bytes ← IO.FS.readBinFile path - let some input := String.fromUTF8? bytes - | return .error s!"{path}: invalid UTF-8" - return parseLog path.toString input - -structure Event where - record : Record - command : Option Record - function : String - node : String - message : Json - state : Json -deriving Inhabited - -def Event.origin (event : Event) (rule : String) : Origin := - { file := event.record.file, line := event.record.line, rule } - -/-- Project events, carry command provenance, and collect node identities. -/ -def prepareEvents (records : Array Record) - : Except String (Array Event × List String) := do - let mut events := #[] - let mut command : Option Record := none - let mut declared : List String := [] - for record in records do - try - let message ← field record.value "msg" - if (optional message "cmd").isSome then - command := some record - else - let function ← string message "function" - let state ← - if function == "retired_committed_tx" then - pure Json.null - else - field message "state" - let node ← - string (if function == "retired_committed_tx" then message else state) "node_id" - events := events.push { record, command, function, node, message, state } - declared := node :: declared - if function == "retired_committed_tx" then - declared := (← string message "retired_node_id") :: declared - if function == "add_configuration" then - declared := (← configuration message) ++ declared - catch error => - throw s!"{record.location}: {error}" - return (events, declared.mergeSort.eraseDups) - -end Consensus.Replay diff --git a/lean/consensus/Consensus/Replay/Interpreter.lean b/lean/consensus/Consensus/Replay/Interpreter.lean deleted file mode 100644 index b9453554c733..000000000000 --- a/lean/consensus/Consensus/Replay/Interpreter.lean +++ /dev/null @@ -1,375 +0,0 @@ -module - --- Copyright (c) Microsoft Corporation. All rights reserved. --- Licensed under the Apache 2.0 License. - -public import Consensus.Model -public import Lean.Data.Json - -public section - -namespace Consensus.Replay - -open Lean Model.Node -open CCF (Finset) -open CCF.MultiNodeTransitionSystem (nodeState removeOne) - -abbrev Envelope := Model.Envelope - -/-- Source evidence and the named rule which uses it. -/ -structure Origin where - file : String - line : Nat - rule : String -deriving Inhabited - -def Origin.label (origin : Origin) : String := - s!"{origin.file}:{origin.line} [{origin.rule}]" - -/-- Bootstrap and nodes identified by native events or configurations. -/ -structure Header where - bootstrap : Finset NodeID - declared : List String - -def Header.nodeId (header : Header) (node : String) : Except String NodeID := do - let some index := header.declared.findIdx? (· == node) - | throw s!"undeclared node '{node}'" - return index - -def Header.initial (header : Header) : Model.State := - { - nodes := - header.declared.mapIdx - fun node _ => - (node, Model.initialNodeState header.bootstrap node) - } - -inductive Step where - | local (node : String) (input : Input) - | receive (source destination : String) (packet : Json) - /-- Initialize from a node's committed prefix ending at `index` in term `view`. -/ - | initAsBackup (node : String) (index view : Nat) - -def Step.name : Step → String - | .local _ (.append _) => "append" - | .local _ (.sendEntries ..) => "sendEntries" - | .local _ (.timeout _) => "timeout" - | .local _ .nominateSuccessor => "nominateSuccessor" - | .local _ (.initAsBackup _) | .initAsBackup .. => "initAsBackup" - | .receive .. => "receive" - -structure ReplayState where - state : Model.State - /-- Envelopes queued by actions since the last send observation. -/ - queued : List Envelope := [] - -/-- A traced native send, or the proposal a nomination implies. -/ -structure NativeSend where - target : String - packet : Json - origin : Origin - -/-- Direct model actions and boundary snapshots; there is no replay wire schema. -/ -inductive Instruction where - | action (step : Step) (origin : Origin) - | observeNodeState (node : String) (expected : Json) (origin : Origin) - /-- The envelopes queued since the last send observation must equal `sends`, as a multiset. -/ - | observeSends (sends : List NativeSend) (origin : Origin) - -def Instruction.origin : Instruction → Origin - | .action _ origin - | .observeNodeState _ _ origin - | .observeSends _ origin => origin - -private def checkValue {α : Type} [ToJson α] (actual : α) (expected : Json) - : Except String Unit := do - let actual := toJson actual - unless expected == actual do - throw s!"observed {expected.compress}, model {actual.compress}" - -private def checkFields (resolve : String → Option (Json → Except String Unit)) - (expected : Json) - : Except String Unit := do - let fields ← expected.getObj? - if fields.isEmpty then - throw "observation must contain at least one field" - for (key, value) in fields.toList do - let path := s!"$[{(toJson key).compress}]" - let some check := resolve key - | throw s!"unsupported observation field '{path}'" - (check value).mapError (fun error => s!"{path}: {error}") - -private def lookup (header : Header) (replay : ReplayState) (node : String) - : Except String NodeState := do - let nodeId ← header.nodeId node - let some state := nodeState replay.state nodeId - | throw s!"node '{node}' is not in the network" - return state - -private def members (header : Header) (nodes : Finset NodeID) : List String := - (header.declared.zipIdx).filterMap - fun (name, index) => - if index ∈ nodes then some name else none - -/-- Compare an action-boundary snapshot with the current model node. -/ -def observeState (header : Header) (node : String) (expected : Json) - (replay : ReplayState) - : Except String Unit := do - let state ← lookup header replay node - let self ← header.nodeId node - checkFields - (fun - | "node_id" => some (checkValue node) - | "leadership_state" => - some - (checkValue - (match state.role with - | .none => "None" - | .follower => "Follower" - | .preVoteCandidate => "PreVoteCandidate" - | .candidate => "Candidate" - | .primary => "Leader")) - | "current_view" => some (checkValue state.currentTerm) - | "last_idx" => some (checkValue state.log.length) - | "commit_idx" => some (checkValue state.commitIndex) - | "committable_indices" => - let indices := - (state.log.zipIdx 1).filterMap - fun (entry, index) => - if index > state.commitIndex && entry.content.isSignature then - some index - else - none - -- Native telemetry records only the first and last cache entries. - some - (checkValue - (match indices with - | [] => [] - | first :: rest => first :: rest.getLast?.toList)) - | "configurations" => - some - fun value => do - let observed ← - (← value.getArr?).toList.mapM - fun configuration => do - let index ← configuration.getObjValAs? Nat "idx" - let nodes ← configuration.getObjVal? "nodes" >>= Json.getObj? - return (index, (nodes.toList.map Prod.fst).mergeSort) - let actual := - (activeConfigurations state.log state.commitIndex).filterMap - fun configuration => - if configuration.index == 0 then - none - else - some (configuration.index, members header configuration.nodes) - checkValue actual (toJson observed) - | "membership_state" => - some - (checkValue - (if (state.retirement self).phase == .noRetirementObserved then - "Active" - else - "Retired")) - | "retirement_phase" => - some - (checkValue - (match (state.retirement self).phase with - | .noRetirementObserved => none - | .retirementOrdered => some "Ordered" - | .retirementSigned => some "Signed" - | .retirementCompleted => some "Completed" - | .retiredCommitted => some "RetiredCommitted")) - | "retirement_idx" => some (checkValue (state.retirement self).index) - | "retirement_committable_idx" => - some (checkValue (state.retirement self).committableIndex) - | "retired_committed_idx" => some (checkValue state.retiredCommittedIndex) - | _ => none) - expected - -/-- Physical packet coordinates; lower-term NACK hints are not election terms. -/ -def messageJson (message : Model.Node.Message) : Json := - let fields := - match message with - | .appendEntriesRequest request => - [ - ("msg", toJson "append_entries"), - ("prev_idx", toJson request.prevLogIndex), - ("prev_term", toJson request.prevLogTerm), - ("idx", toJson (request.prevLogIndex + request.entries.length)), - ("leader_commit_idx", toJson request.primaryCommit), - ( - "term_of_idx", - toJson (request.entries.getLast?.map Entry.term |>.getD request.prevLogTerm) - ), - ("contains_new_view", toJson false) - ] - | .appendEntriesResponse response => - [ - ("msg", toJson "append_entries_response"), - ("success", toJson (if response.success then "OK" else "FAIL")), - ("last_log_idx", toJson response.lastLogIndex) - ] - | .requestVoteRequest request => - [ - ("msg", toJson "request_vote"), - ("last_committable_idx", toJson request.lastCommittableIndex), - ("term_of_last_committable_idx", toJson request.lastCommittableTerm) - ] - | .requestPreVoteRequest request => - [ - ("msg", toJson "request_pre_vote"), - ("last_committable_idx", toJson request.lastCommittableIndex), - ("term_of_last_committable_idx", toJson request.lastCommittableTerm) - ] - | .requestVoteResponse response => - [ - ("msg", toJson "request_vote_response"), - ("vote_granted", toJson response.voteGranted) - ] - | .requestPreVoteResponse response => - [ - ("msg", toJson "request_pre_vote_response"), - ("vote_granted", toJson response.voteGranted) - ] - | .proposeRequestVoteRequest _ => [("msg", toJson "propose_request_vote")] - Json.mkObj (("term", toJson message.term) :: fields) - -/-- A native packet matches when it has exactly the fields the model renders, with equal values. -/ -private def checkPacket (packet : Json) (message : Model.Node.Message) - : Except String Unit := do - let actual := messageJson message - checkFields (fun key => (actual.getObjVal? key).toOption.map checkValue) packet - let missing := - (← actual.getObj?).toList.map Prod.fst - |>.filter fun key => !(packet.getObjVal? key).isOk - unless missing.isEmpty do - throw s!"packet lacks fields {missing}" - -/-- The first matching envelope, else the first with the same `msg`, to diagnose a mismatch. -/ -private def closest (packet : Json) (envelopes : List Envelope) : Option Envelope := - envelopes.find? (fun envelope => (checkPacket packet envelope.payload).isOk) - <|> envelopes.find? - fun envelope => - ((messageJson envelope.payload).getObjVal? "msg").toOption - == (packet.getObjVal? "msg").toOption - -/-- Deliver any matching queued envelope; loss is non-delivery. -/ -private def selectPacket (replay : ReplayState) (source destination : NodeID) - (packet : Json) - : Except String Envelope := do - let pending := - replay.state.network.filter - fun envelope => envelope.source == source && envelope.target == destination - let some envelope := closest packet pending <|> pending.head? - | throw s!"no pending packet from '{source}' to '{destination}'" - checkPacket packet envelope.payload - unless pending.all - fun other => - !(checkPacket packet other.payload).isOk - || other.payload == envelope.payload do - throw - s!"ambiguous delivery from '{source}' to '{destination}': matching packets differ in model payload" - return envelope - -/-- Run one model action, recording the envelopes it queues. -/ -private def ReplayState.run (replay : ReplayState) (header : Header) - (action : Model.Action) (name : String) - : Except String ReplayState := do - let some state := Model.networkStep header.bootstrap replay.state action - | throw s!"disabled model action '{name}'" - -- A step appends the acting node's sends to the network left after any delivery. - let pending := replay.state.network.length - if action matches .deliver _ then 1 else 0 - return { state, queued := replay.queued ++ state.network.drop pending } - -/-- Observations never change model state or repair a disabled action. -/ -def runInstruction (header : Header) (replay : ReplayState) (instruction : Instruction) - : Except String ReplayState := do - match instruction with - | .observeNodeState node expected _ => - observeState header node expected replay - return replay - | .observeSends sends _ => - let mut queued := replay.queued - for send in sends do - let context := s!"{send.origin.label}: send to '{send.target}'" - let target ← (header.nodeId send.target).mapError (s!"{context}: " ++ ·) - let some envelope := closest send.packet (queued.filter (·.target == target)) - | throw s!"{context}: not queued by the model: {send.packet.compress}" - (checkPacket send.packet envelope.payload).mapError (s!"{context}: " ++ ·) - queued := removeOne envelope queued - if let some envelope := queued.head? then - let target := header.declared[envelope.target]?.getD (toString envelope.target) - throw - s!"model queued {(messageJson envelope.payload).compress} to '{target}' with no native send" - return { replay with queued := [] } - | .action (step@(.local node input)) _ => - let node ← header.nodeId node - match input with - | .sendEntries destination _ => - unless destination < header.declared.length do - throw s!"undeclared model node {destination}" - | .append entries => - for entry in entries do - let metadata := entry.content.metadata - for member - in metadata.configuration.getD ∅ ∪ metadata.retirementConfirmations - |>.sort do - unless member < header.declared.length do - throw s!"undeclared model node {member}" - for (destination, _) in entry.flushes do - unless destination < header.declared.length do - throw s!"undeclared model node {destination}" - | _ => pure () - replay.run header (.local node input) step.name - | .action (.receive source destination packet) _ => - let source ← header.nodeId source - let destination ← header.nodeId destination - let envelope ← selectPacket replay source destination packet - replay.run header (.deliver envelope) "receive" - | .action (step@(.initAsBackup node index view)) _ => - let joiner ← header.nodeId node - -- Committed prefixes in a reachable state are comparable, so any such node will do. - let some (_, source) := - replay.state.nodes.find? - fun (_, state) => - index <= state.commitIndex - && (index == 0 || isSignatureAt state.log index) - && termAt state.log index == view - | throw s!"no node has a committed signature at {index} in term {view}" - replay.run header (.local joiner (.initAsBackup (source.log.take index))) step.name - -structure Result where - instructions : Nat - actions : Nat - observations : Nat -deriving Repr, BEq - -def replay (header : Header) (instructions : Array Instruction) - : Except String Result := do - unless !header.declared.isEmpty - && header.declared.all (!·.isEmpty) - && header.declared.eraseDups == header.declared do - throw "declared nodes must be nonempty and distinct" - unless header.declared == header.declared.mergeSort do - throw "declared nodes must be sorted lexically" - unless header.bootstrap.Nonempty do - throw "initial membership must be nonempty" - for node in header.bootstrap.sort do - unless node < header.declared.length do - throw s!"undeclared model node {node}" - if instructions.isEmpty then throw "replay instructions must not be empty" - let mut state : ReplayState := { state := header.initial } - let mut actions := 0 - for instruction in instructions, index in [:instructions.size] do - state ← - (runInstruction header state instruction).mapError - fun error => - s!"instruction {index + 1} at {instruction.origin.label}: {error}" - if let .action .. := instruction then actions := actions + 1 - return { - instructions := instructions.size, - actions, - observations := instructions.size - actions - } - -end Consensus.Replay diff --git a/lean/consensus/Consensus/Replay/Reduction.lean b/lean/consensus/Consensus/Replay/Reduction.lean deleted file mode 100644 index b1bfba313c68..000000000000 --- a/lean/consensus/Consensus/Replay/Reduction.lean +++ /dev/null @@ -1,438 +0,0 @@ -module - --- Copyright (c) Microsoft Corporation. All rights reserved. --- Licensed under the Apache 2.0 License. - -public import Consensus.Replay.Input - -import CCF.Parsec - -public section - -/-! -Rules peek action arguments, consume named events, and emit direct model actions. -Explicit native boundaries distinguish related events from subsequent actions. -After bootstrap, each rule observes its native group's starting snapshot before emitting actions. -Each rule that may send checks the native sends among its events against the envelopes its -actions queued. -Reduction never executes or repairs model state. --/ - -namespace Consensus.Replay.Reducer - -open Lean Model.Node -open CCF (Finset) -open CCF.Parsec (failure validated attempt many_ optional_) - -private structure ReductionState where - header : Header - nextRequestId : ReqID := 1 - instructions : Array Instruction := #[] - -private abbrev Reduction := CCF.Parsec.ParserT Event ReductionState - -private def liftExcept {α : Type} (event : Event) (result : Except String α) - : Reduction α := - validated - (result.mapError fun error => s!"{event.record.location}: {event.function}: {error}") - -private def readJson {α : Type} (event : Event) (value : Json) - (decode : Json → Except String α) - : Reduction α := - liftExcept event (decode value) - -private def peek : Reduction Event := do - let some event ← CCF.Parsec.peek | failure "unexpected end of input" - return event - -/-- The cursor position, from which `extractSends` finds the events a rule consumed. -/ -private def position : Reduction Nat := - liftM (m := CCF.Parsec.Parser Event) - ((fun input => .success input input.position) : CCF.Parsec.Parser Event Nat) - -/-- Native sends among the events consumed since `start`, and proposals nominations imply. -/ -private def extractSends (start : Nat) : Reduction (List NativeSend) := do - let events ← - liftM (m := CCF.Parsec.Parser Event) - ((fun input => .success input (input.events.extract start input.position)) - : CCF.Parsec.Parser Event (Array Event)) - events.toList.filterMapM - fun event => do - let packet ← - if event.function.startsWith "send_" then - some <$> readJson event event.message (field · "packet") - else if event.function == "step_down_and_nominate_successor" then - -- Native then sends an untraced proposal in its current view. - let term ← readJson event event.state (nat · "current_view") - pure - (some - (Json.mkObj - [("msg", toJson "propose_request_vote"), ("term", toJson term)])) - else - pure none - packet.mapM - fun packet => do - let target ← readJson event event.message (string · "to_node_id") - return { target, packet, origin := event.origin event.function } - -private def event (source : Event) (name : String) : Reduction Unit := do - let next ← peek - unless next.function == name do - failure s!"{next.record.location}: expected {name}, got {next.function}" - liftExcept next do - require (next.node == source.node) s!"expected event on node {source.node}" - discard CCF.Parsec.take - -private def modelNode (event : Event) (name : String) : Reduction NodeID := do - liftExcept event ((← get).header.nodeId name) - -private def modelMembers (event : Event) (names : List String) - : Reduction (Finset NodeID) := do - return Finset.ofList (← names.mapM (modelNode event)) - -private def appendInstruction (instr : Instruction) : Reduction Unit := - modify fun s => { s with instructions := s.instructions.push instr } - -private def emitAction (event : Event) (rule : String) (step : Step) : Reduction Unit := - appendInstruction (.action step (event.origin rule)) - -private def emitObserve (event : Event) (rule : String) : Reduction Unit := - appendInstruction (.observeNodeState event.node event.state (event.origin rule)) - -private def emitObserveSends (event : Event) (sends : List NativeSend) : Reduction Unit := - appendInstruction (.observeSends sends (event.origin "sends")) - -/-- -Genesis runs asynchronously after the first node becomes leader, so bare ticks may precede -it; the model starts after genesis, so they are not observed. -`replicate` flushes a genesis entry over the append entries size limit. The node has no peers -yet, so the flush sends nothing. --/ -private def ruleBootstrap : Reduction String := do - let head ← peek - -- consume - event head "become_leader" - many_ (event head "tick") - event head "replicate" - event head "replicate_entry" - event head "add_configuration" - optional_ (event head "batch_flush") - return head.node - -private def readAppendContent (head : Event) (config : Option Event) - (retirements : List Event) - : Reduction EntryContent := do - let signature ← readJson head head.message (boolean · "globally_committable") - if signature then - liftExcept head (require retirements.isEmpty "retirement metadata on signature") - if let some config := config then - liftExcept config (throw "configuration write pair mismatch") - return .signature - let configuration ← - match config with - | some config => do - liftExcept config do - require - ((← nat config.message "idx") == (← nat head.message "seqno")) - "configuration write pair mismatch" - some <$> modelMembers config (← readJson config config.message configuration) - | none => pure none - let retiredNodes ← - retirements.mapM - fun retirement => - readJson retirement retirement.message (string · "retired_node_id") - let retirementConfirmations ← modelMembers head retiredNodes - let request := (← get).nextRequestId - modify fun s => { s with nextRequestId := request + 1 } - return .transaction request { configuration, retirementConfirmations } - -/-- One entry of a batch: its replicate event, retirements, configuration and flush. -/ -private def readReplicateEntry (head : Event) : Reduction AppendEntryInput := do - let seqno ← readJson head head.message (nat · "seqno") - -- consume - event head "replicate_entry" - let retirements ← - CCF.Parsec.many do - let retirement ← peek - event head "retired_committed_tx" - liftExcept retirement do - let retirementSeqno ← nat retirement.message "seqno" - require (retirementSeqno == seqno) - s!"expected seqno {seqno}, got {retirementSeqno}" - return retirement - let config ← - CCF.Parsec.optionalRule do - let config ← peek - event head "add_configuration" - many_ (event head "send_append_entries") - return config - let flushes ← - CCF.Parsec.optionalRule do - event head "batch_flush" - CCF.Parsec.many do - let next ← peek - event head "send_append_entries" - let packet ← readJson next next.message (field · "packet") - let destination ← - modelNode next (← readJson next next.message (string · "to_node_id")) - let last ← readJson next packet (nat · "idx") - return (destination, last) - let content ← readAppendContent head config retirements - return { content, flushes := flushes.getD [] } - -/-- -The entries after a native `replicate` event, each starting with its `replicate_entry` -event, are appended to the model as one batch, which checks commit once at the end, as -CCF does. A call rejected at its first entry traces no entries and appends nothing. --/ -private def ruleAppend : Reduction Unit := do - let head ← peek - -- consume - let start ← position - event head "replicate" - let entries ← - CCF.Parsec.many do - let next ← peek - unless next.function == "replicate_entry" && next.node == head.node do - failure s!"{next.record.location}: not an entry of the batch" - readReplicateEntry next - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - -- emit - emitObserve head "append" - unless entries.isEmpty do - emitAction head "append" (.local head.node (.append entries)) - emitObserveSends head (← extractSends start) - -private def readReceive (head : Event) (families : List String) : Reduction Step := do - let sender ← readJson head head.message (string · "from_node_id") - let packet ← readJson head head.message (field · "packet") - let family ← readJson head packet (string · "msg") - liftExcept head (require (families.contains family) "receive function/packet mismatch") - return .receive sender head.node packet - -private def ruleRecvAppendEntries : Reduction Unit := do - let head ← peek - let action ← readReceive head ["append_entries"] - -- consume - let start ← position - event head "recv_append_entries" - optional_ (event head "become_follower") - many_ - ((do - event head "execute_append_entries_sync" - many_ (event head "retired_committed_tx")) - <|> (do - event head "add_configuration" - many_ (event head "send_append_entries")) - <|> (do - event head "commit" - optional_ (event head "step_down_and_nominate_successor"))) - optional_ (event head "send_append_entries_response") - -- emit - emitObserve head "recv-append-entries" - emitAction head "recv-append-entries" action - emitObserveSends head (← extractSends start) - -private def ruleRecvAppendEntriesResponse : Reduction Unit := do - let head ← peek - let action ← readReceive head ["append_entries_response"] - -- consume - let start ← position - event head "recv_append_entries_response" - optional_ (event head "become_follower") - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - -- emit - emitObserve head "recv-append-entries-response" - emitAction head "recv-append-entries-response" action - emitObserveSends head (← extractSends start) - -private def ruleRecvRequestVote : Reduction Unit := do - let head ← peek - let action ← readReceive head ["request_vote", "request_pre_vote"] - -- consume - let start ← position - event head "recv_request_vote" - optional_ (event head "become_follower") - optional_ (event head "send_request_vote_response") - -- emit - emitObserve head "recv-request-vote" - emitAction head "recv-request-vote" action - emitObserveSends head (← extractSends start) - -private def ruleRecvProposeRequestVote : Reduction Unit := do - let head ← peek - let action ← readReceive head ["propose_request_vote"] - -- consume - let start ← position - event head "recv_propose_request_vote" - optional_ do - event head "become_candidate" - optional_ do - event head "become_leader" - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - many_ (event head "send_append_entries") - many_ (event head "send_request_vote") - -- emit - emitObserve head "recv-propose-request-vote" - emitAction head "recv-propose-request-vote" action - emitObserveSends head (← extractSends start) - -private def ruleRecvRequestVoteResponse : Reduction Unit := do - let head ← peek - let action ← readReceive head ["request_vote_response", "request_pre_vote_response"] - -- consume - let start ← position - event head "recv_request_vote_response" - optional_ - (event head "become_follower" - <|> (do - event head "become_candidate" - optional_ do - event head "become_leader" - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - many_ (event head "send_append_entries") - many_ (event head "send_request_vote")) - <|> (do - event head "become_leader" - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - many_ (event head "send_append_entries"))) - -- emit - emitObserve head "recv-request-vote-response" - emitAction head "recv-request-vote-response" action - emitObserveSends head (← extractSends start) - -private def ruleTick : Reduction Unit := do - let head ← peek - -- consume - let start ← position - event head "tick" - let election ← CCF.Parsec.optionalRule (event head "become_pre_vote_candidate") - if election.isSome then - optional_ do - event head "become_candidate" - optional_ do - event head "become_leader" - optional_ do - event head "commit" - optional_ (event head "step_down_and_nominate_successor") - many_ (event head "send_append_entries") - many_ (event head "send_request_vote") - many_ (event head "send_request_vote") - -- emit - emitObserve head "tick-election" - emitAction head "tick-election" (.local head.node (.timeout .election)) - else - let sends ← - CCF.Parsec.many do - let next ← peek - event head "send_append_entries" - let packet ← readJson next next.message (field · "packet") - let destination ← - modelNode next (← readJson next next.message (string · "to_node_id")) - let last ← readJson next packet (nat · "idx") - return (next, destination, last) - let demoted ← CCF.Parsec.optionalRule (event head "become_follower") - -- emit - emitObserve head "tick" - for (source, destination, last) in sends do - emitAction source "tick-send" (.local head.node (.sendEntries destination last)) - if demoted.isSome then - emitAction head "tick-check-quorum" (.local head.node (.timeout .checkQuorum)) - emitObserveSends head (← extractSends start) - -private def ruleNomination : Reduction Unit := do - let head ← peek - -- consume - let start ← position - event head "nomination" - let nominated ← CCF.Parsec.optionalRule (event head "step_down_and_nominate_successor") - -- emit - emitObserve head "nomination" - if nominated.isSome then - emitAction head "nomination" (.local head.node .nominateSuccessor) - emitObserveSends head (← extractSends start) - -/-- Dropped packets stay queued in the model network, never delivered. -/ -private def ruleDrop : Reduction Unit := do - let head ← peek - -- consume - event head "drop_pending_to" - -/-- -Snapshot installation runs ledger hooks outside the consensus lock, so bare ticks -may interleave with their events. --/ -private def ruleInitAsBackup : Reduction Unit := do - let head ← peek - let hooks := ["add_configuration", "retired_committed_tx"] - unless hooks.contains head.function || head.function == "init_as_backup" do - failure s!"{head.record.location}: expected init_as_backup, got {head.function}" - -- consume - many_ (hooks.foldr (fun name rest => event head name <|> rest) (event head "tick")) - unless (← CCF.Parsec.peek).any (·.function == "init_as_backup") do - liftExcept head - (throw - "not grouped with replicate_entry, execute_append_entries_sync or init_as_backup") - let init ← peek - event head "init_as_backup" - event head "become_follower" - let index ← readJson init init.message (nat · "seqno") - let view ← readJson init init.message (nat · "view") - -- emit - emitObserve init "init-as-backup" - emitAction init "init-as-backup" (.initAsBackup head.node index view) - -private def ruleStep : Reduction Unit := do - -- Recv rules - attempt ruleRecvAppendEntries - <|> attempt ruleRecvAppendEntriesResponse - <|> attempt ruleRecvRequestVote - <|> attempt ruleRecvProposeRequestVote - <|> attempt ruleRecvRequestVoteResponse - -- Async rules - <|> attempt ruleInitAsBackup - <|> attempt ruleAppend - <|> attempt ruleTick - <|> attempt ruleNomination - <|> attempt ruleDrop - -private def ruleTrace : Reduction String := do - let leader ← ruleBootstrap - many_ ruleStep - if let some event ← CCF.Parsec.peek then - failure s!"{event.record.location}: ungrouped event {event.function}" - return leader - -/-- Consume every event exactly once; an ungrouped event is never a stutter. -/ -def reduce (events : Array Event) (header : Header) - : Except String (String × Array Instruction) := do - let (leader, state) ← CCF.Parsec.run events (ruleTrace.run { header }) - return (leader, state.instructions) - -end Consensus.Replay.Reducer - -namespace Consensus.Replay - -/-- Prepared initialization and instructions for direct model replay. -/ -structure Reduced where - header : Header - instructions : Array Instruction - -/-- Prepare replay identities and reduce the associated event stream. -/ -def reduce (events : Array Event) (declared : List String) : Except String Reduced := do - let header : Header := { bootstrap := ∅, declared } - let (leader, instructions) ← Reducer.reduce events header - let header := { header with bootstrap := {← header.nodeId leader} } - return { header, instructions } - -end Consensus.Replay diff --git a/lean/consensus/Consensus/Tests/ReplayDelivery.lean b/lean/consensus/Consensus/Tests/ReplayDelivery.lean deleted file mode 100644 index 5894b5b74191..000000000000 --- a/lean/consensus/Consensus/Tests/ReplayDelivery.lean +++ /dev/null @@ -1,55 +0,0 @@ -module - --- Copyright (c) Microsoft Corporation. All rights reserved. --- Licensed under the Apache 2.0 License. - -meta import Consensus.Replay.Interpreter - -public import Consensus.Replay.Interpreter - -public section - -namespace Consensus.Tests.ReplayDelivery - -open Consensus Consensus.Replay Consensus.Model.Node - -private def header : Header := { bootstrap := {0}, declared := ["0", "1"] } - -/-- An AppendEntries from 0 to 1; its rendered packet omits the entry request ID. -/ -private def appendEntries (request : ReqID) : Envelope := - { - source := 0 - target := 1 - payload := - .appendEntriesRequest - { - term := 2 - prevLogIndex := 0 - prevLogTerm := 0 - entries := [{ term := 2, content := .transaction request {} }] - primaryCommit := 0 - } - } - -private def receive (network : List Envelope) : Except String ReplayState := - runInstruction header { state := { header.initial with network } } - (.action (.receive "0" "1" (messageJson (appendEntries 1).payload)) default) - -/-- Checks delivery selection among queued envelopes whose rendered packets are equal. -/ -def run : IO Unit := do - match receive [appendEntries 1, appendEntries 1] with - | .ok replay => - unless replay.state.network.count (appendEntries 1) == 1 do - throw - (IO.userError "identical candidates: exactly one occurrence must be delivered") - | .error error => throw (IO.userError s!"identical candidates: {error}") - match receive [appendEntries 1, appendEntries 2] with - | .error error => - unless error.startsWith "ambiguous delivery" do - throw (IO.userError s!"different entries: unexpected error {error}") - | .ok _ => throw (IO.userError "different entries: delivery must be ambiguous") - IO.println "Replay delivery checks passed." - -#eval run - -end Consensus.Tests.ReplayDelivery diff --git a/lean/consensus/Consensus/Tests/TraceValidationHooks.lean b/lean/consensus/Consensus/Tests/TraceValidationHooks.lean new file mode 100644 index 000000000000..324d491731ad --- /dev/null +++ b/lean/consensus/Consensus/Tests/TraceValidationHooks.lean @@ -0,0 +1,194 @@ +module + +meta import Consensus.TraceValidation.Lockstep + +public import Consensus.TraceValidation.Lockstep + +public section + +/-! +# M_tv: one entry carrying both configuration hooks + +hooks.h's `ConfigurationChangeHook::call` can run, for one entry, the +`retired_committed_tx` hooks and then `add_configuration`. These checks run M_tv on a +synthetic hold of each kind, independently of the driver, and compare the release with +the clean model as `consensus-replay --refine` does. + +Three nodes, view 2: `C1 = {n0, n1, n2}` at 1 and `C2 = {n0, n2}` at 3 are committed +(commit 4), so `n1`'s retirement is completed (and `n1` is still a peer). Entry 5 confirms `n1`'s retirement and +changes the configuration to `{n0}`. The same primary may not confirm `n2`, whose +retirement is not completed, nor add an empty configuration (second-kind guards). +-/ + +namespace Consensus.Tests.TraceValidationHooks + +open Lean +open Consensus.Model.Node +open Consensus.TraceValidation +open Consensus.TraceValidation.Exec (State Action Ev) + +private def check (condition : Bool) (message : String) : IO Unit := + unless condition do + throw (IO.userError message) + +private def names : Names := { known := #["n0", "n1", "n2"] } + +private def env : Env := + { + names, + addrs := [("n0", "a0"), ("n1", "a1"), ("n2", "a2")], + genesis := CCF.Finset.ofList [0] + } + +private def c1 : Exec.Nodes := [("n0", "a0"), ("n1", "a1"), ("n2", "a2")] +private def c2 : Exec.Nodes := [("n0", "a0"), ("n2", "a2")] +private def c3 : Exec.Nodes := [("n0", "a0")] + +private def ledger : Array Exec.Entry := + #[ + { term := 2, sig := false, config := some c1 }, + { term := 2, sig := true }, + { term := 2, sig := false, config := some c2 }, + { term := 2, sig := true } + ] + +private def entry5 : Exec.Entry := + { term := 2, sig := false, config := some c3, retired := ["n1"] } + +private def base : State := + { + nodeId := "n0" + currentView := 2 + lastIdx := 4 + commitIdx := 4 + views := #[1, 1] + leaderId := some "n0" + ticking := true + configurations := [{ idx := 3, nodes := c2, rid := 3 }] + ledger + } + +private def leader : State := + { + base with + leadership := .leader + allOtherNodes := + [("n1", { sentIdx := 4, matchIdx := 4 }), ("n2", { sentIdx := 4, matchIdx := 4 })] + } + +private def follower : State := + { + base with + nodeId := "n2" + leadership := .follower + allOtherNodes := + [("n0", { sentIdx := 0, matchIdx := 0 }), ("n1", { sentIdx := 0, matchIdx := 0 })] + } + +private def nodesJson (ns : Exec.Nodes) : Json := + Json.mkObj (ns.map fun (id, addr) => (id, Json.mkObj [("address", toJson addr)])) + +private def ev (node function : String) : Ev := + { file := "test", line := 0, process := "", hts := 0, node, function, msg := Json.null } + +/-- Run one hold and check its release as `--refine` does. -/ +private def hold (name : String) (saved : State) (recv : Option (NodeID × Message)) + (actions : List Action) (h : Exec.M Unit) + : IO State := do + let failed := (invChecks names saved).filter (!·.2) |>.map (·.1) + check failed.isEmpty s!"{name}: saved state breaks {failed}" + let ctx ← + match Exec.run env saved actions true h with + | .ok c => pure c + | .error (.error e) => throw (IO.userError s!"{name}: M_tv rejects: {e}") + | .error (.blocked _) => throw (IO.userError s!"{name}: M_tv blocked") + check ctx.queue.isEmpty s!"{name}: actions left over" + let node := names.id saved.nodeId + let r : Release := + { + node, + ctx, + vars := ctx.vars, + sec := { head := ev saved.nodeId (actions.head!.point), recv, saved, actions, ctx } + } + match checkRelease env [(node, abs names saved)] r with + | .ok (_, []) => pure () + | .ok (_, findings) => throw (IO.userError s!"{name}: {findings}") + | .error e => throw (IO.userError s!"{name}: {e}") + check (ctx.vars.ledger.back? == some entry5) s!"{name}: entry 5 is not {repr entry5}" + return ctx.vars + +private def primaryBothHooks : IO Unit := do + let _ ← + hold "primary" leader none + [ + { point := "replicate", inputs := [] }, + { + point := "replicate_entry", inputs := [("globally_committable", toJson false)] + }, + { point := "retired_committed_tx", inputs := [("retired_node_id", toJson "n1")] }, + { + point := "add_configuration", + inputs := [("idx", toJson 5), ("nodes", nodesJson c3)] + } + ] + Exec.replicate + +private def followerBothHooks : IO Unit := do + let request : AppendEntriesRequest := + { + term := 2, + prevLogIndex := 4, + prevLogTerm := 2, + entries := [absEntry names entry5], + primaryCommit := 4 + } + let _ ← + hold "follower" follower (some (0, .appendEntriesRequest request)) + [ + { point := "recv_append_entries", inputs := [] }, + { point := "execute_append_entries_sync", inputs := [] }, + { point := "retired_committed_tx", inputs := [] }, + { point := "add_configuration", inputs := [] }, + { point := "send_append_entries_response", inputs := [] } + ] + (Exec.recvAppendEntries "n0" request) + +/-- M_tv rejects the hold with a diagnostic naming `rule`. -/ +private def rejects (name rule : String) (saved : State) (actions : List Action) + (h : Exec.M Unit) + : IO Unit := + match Exec.run env saved actions true h with + | .error (.error e) => + check ((e.splitOn rule).length > 1) s!"{name}: rejected for another reason: {e}" + | _ => throw (IO.userError s!"{name}: M_tv accepts") + +/-- The second-kind admission guards on the primary. -/ +private def primaryGuards : IO Unit := do + let entry (hooks : List Action) : List Action := + [ + { point := "replicate", inputs := [] }, + { point := "replicate_entry", inputs := [("globally_committable", toJson false)] } + ] + ++ hooks + rejects "confirm n2" "retirement confirmation" leader + (entry + [{ point := "retired_committed_tx", inputs := [("retired_node_id", toJson "n2")] }]) + Exec.replicate + rejects "empty configuration" "empty configuration" leader + (entry + [{ + point := "add_configuration", + inputs := [("idx", toJson 5), ("nodes", Json.mkObj [])] + }]) + Exec.replicate + +def run : IO Unit := do + primaryBothHooks + followerBothHooks + primaryGuards + IO.println "Trace validation hook checks passed." + +#eval run + +end Consensus.Tests.TraceValidationHooks diff --git a/lean/consensus/Consensus/TraceValidation/Lockstep.lean b/lean/consensus/Consensus/TraceValidation/Lockstep.lean new file mode 100644 index 000000000000..992997ef51ba --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Lockstep.lean @@ -0,0 +1,253 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Validator +public import Consensus.TraceValidation.Invariant + +@[expose] public section + +/-! +# Lock-step check (diagnostic, not part of acceptance) + +`lockstep` replays an accepted trace's releases, in order, against the clean model: +for each lock hold it rebuilds the clean inputs from the handler's notes, runs the clean +local steps from the node's clean state, and reports every release where the result is +not related (`Rel`) to the declared state, where a clean primary has a stale match index +for a node outside its configurations (`UnnamedUnmatched`), where a conjunct of the local +invariant `inv` fails, where the clean sends differ from the hold's, or where a send breaks `msgInv`. +It is a regression oracle for the refinement proof's invariants, run by +`consensus-replay --refine`. +-/ + +namespace Consensus.TraceValidation + +open Lean +open CCF (Finset Capabilities) +open Consensus.Model (initialNodeState) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State Ev Ctx Note) + +/-! ## Rendering, for diagnostics -/ + +def showEntry (e : Entry) : String := + match e.content with + | .signature => s!"{e.term}s" + | .transaction _ md => + let c := + match md.configuration with + | some ns => s!"c{ns.sort}" + | none => "" + let r := + if md.retirementConfirmations.sort.isEmpty then + "" + else + s!"r{md.retirementConfirmations.sort}" + s!"{e.term}{c}{r}" + +def showLog (l : List Entry) : String := toString (l.map showEntry) + +def showRole : Role -> String + | .none => "none" + | .follower => "follower" + | .preVoteCandidate => "preVoteCandidate" + | .candidate => "candidate" + | .primary => "primary" + +def showMessage : Message -> String + | .appendEntriesRequest r => + s!"AE(t{r.term} prev {r.prevLogIndex}/{r.prevLogTerm} {showLog r.entries} c{r.primaryCommit})" + | .appendEntriesResponse r => s!"AER(t{r.term} {r.success} {r.lastLogIndex})" + | .requestVoteRequest r => + s!"RV(t{r.term} {r.lastCommittableIndex}/{r.lastCommittableTerm})" + | .requestPreVoteRequest r => + s!"PRV(t{r.term} {r.lastCommittableIndex}/{r.lastCommittableTerm})" + | .requestVoteResponse r => s!"RVR(t{r.term} {r.voteGranted})" + | .requestPreVoteResponse r => s!"PRVR(t{r.term} {r.voteGranted})" + | .proposeRequestVoteRequest t => s!"PROPOSE(t{t})" + +def eventKind : Event -> String + | .internal (.append es) => s!"append[{es.length}]" + | .internal (.sendEntries _ _) => "sendEntries" + | .internal (.timeout .election) => "timeout.election" + | .internal (.timeout .checkQuorum) => "timeout.checkQuorum" + | .internal .nominateSuccessor => "nominateSuccessor" + | .internal (.initAsBackup _) => "initAsBackup" + | .receive _ m => + "receive." + ++ match m with + | .appendEntriesRequest _ => "AE" + | .appendEntriesResponse _ => "AER" + | .requestVoteRequest _ => "RV" + | .requestVoteResponse _ => "RVR" + | .requestPreVoteRequest _ => "PRV" + | .requestPreVoteResponse _ => "PRVR" + | .proposeRequestVoteRequest _ => "PROPOSE" + +/-- The clean guard a failed clean step corresponds to, for diagnostics. -/ +def guardHint : Event -> String + | .internal (.append _) => + " (Node.lean's appendEntry or sendEntries does not admit an entry the host submitted or a flush cft.h made)" + | .internal (.sendEntries _ _) => " (Node.lean's sendEntries guard)" + | .internal (.timeout .election) => " (Node.lean's canStartElection)" + | _ => "" + +/-- Run clean local steps, accumulating sends. -/ +def runClean (node : NodeID) (st : NodeState) + : List Event -> Except String (NodeState × List (CCF.Envelope NodeID Message)) + | [] => .ok (st, []) + | ev :: rest => + match (Consensus.Model.Node.step (Capabilities.record node) node st ev).run {} with + | some (st', o) => + match runClean node st' rest with + | .ok (f, s) => .ok (f, o.outgoing ++ s) + | .error err => .error err + | none => .error s!"clean guard failed at {eventKind ev}{guardHint ev}" + +/-- The section's clean events. -/ +def cleanEvents (recv : Option (NodeID × Message)) (inputs : List Input) : List Event := + (recv.map fun (source, m) => Event.receive source m).toList ++ inputs.map .internal + +/-- The clean result of a section: its clean local steps, run from the ghost state. -/ +def cleanSection (node : NodeID) (clean : NodeState) (recv : Option (NodeID × Message)) + (inputs : List Input) + : Except String (NodeState × List (CCF.Envelope NodeID Message)) := + runClean node clean (cleanEvents recv inputs) + +/-- Field-wise differences between a clean state and `abs` of a declared state. -/ +def relatedDiff (env : Env) (c : NodeState) (d : State) : List String := + let a := abs env.names d + let f (name : String) (x y : String) := + if x == y then [] else [s!"{name}: clean={x} declared={y}"] + let peers := trackedPeers env.names d + f "role" (showRole c.role) (showRole a.role) + ++ f "currentTerm" (toString c.currentTerm) (toString a.currentTerm) + ++ f "log" (showLog c.log) (showLog a.log) + ++ f "commitIndex" (toString c.commitIndex) (toString a.commitIndex) + ++ f "sentIndex" (toString (peers.map c.sentIndex)) (toString (peers.map a.sentIndex)) + ++ f "matchIndex" (toString (peers.map c.matchIndex)) + (toString (peers.map a.matchIndex)) + ++ f "isNewFollower" (toString c.isNewFollower) (toString a.isNewFollower) + ++ f "votedFor" (toString c.votedFor) (toString a.votedFor) + ++ f "primaryKnown" (toString c.primaryKnown) (toString a.primaryKnown) + ++ (if a.role == .candidate then + f "votesGranted" (toString c.votesGranted.sort) (toString a.votesGranted.sort) + else + []) + ++ (if a.role == .preVoteCandidate then + f "preVotesGranted" (toString c.preVotesGranted.sort) + (toString a.preVotesGranted.sort) + else + []) + ++ f "retiredCommittedIndex" (toString c.retiredCommittedIndex) + (toString a.retiredCommittedIndex) + +/-- The hold's clean internal inputs, from its head and the handler's notes. -/ +def cleanInputs (env : Env) (others : List (NodeID × NodeState)) (pristine : Bool) + (r : Release) + : Except String (List Input) := do + let s := r.sec + if pristine then return [] + match s.head.function with + | "become_leader" | "add_configuration" | "drop_pending_to" => return [] + -- A non-primary's nomination is traced and does nothing. + | "nomination" => + return (if s.saved.leadership == .leader then [.nominateSuccessor] else []) + | _ => pure () + let mut evs : Array Input := #[] + let mut batch : Array AppendEntryInput := #[] + let mut flushing := false + let mut tickSends := false + for n in r.ctx.notes do + match n with + | .heartbeatTimeout => tickSends := true + | .checkQuorum => evs := evs.push (.timeout .checkQuorum) + | .electionTimeout => evs := evs.push (.timeout .election) + | .appendEntry e => + batch := batch.push { content := (absEntry env.names e).content } + flushing := false + | .batchFlush => flushing := true + | .sendEntries d e true => + if flushing then + let some last := batch.back? | throw "flush before any entry" + batch := + batch.pop.push { last with flushes := last.flushes ++ [(env.names.id d, e)] } + else if tickSends then + evs := evs.push (.sendEntries (env.names.id d) e) + else + throw "independent send outside a heartbeat or flush" + | .sendEntries _ _ false => pure () + | .initAsBackup index _ => + let some (_, donor) := others.find? fun (_, o) => index <= o.commitIndex + | throw s!"no clean node has committed {index}" + evs := evs.push (.initAsBackup (donor.log.take index)) + if !batch.isEmpty then evs := evs.push (.append batch.toList) + return evs.toList + +/-- +The clean-model findings of one release, given the clean states before it. From a pristine +genesis primary (`pristine`), whose clean state is still the initial one, a hold has no +clean counterpart (`genesisOk`). +-/ +def checkRelease (env : Env) (cleans : List (NodeID × NodeState)) (r : Release) + : Except String (NodeState × List String) := do + let node := r.node + let loc := + s!"section opened at {r.sec.head.loc} h_ts={r.sec.head.hts} node={r.sec.head.node}" + let some clean := cleans.lookup node | throw s!"{loc}: no clean state" + let others := cleans.filter (·.1 != node) + let preGenesis := pristine env r.sec.saved + let inputs ← (cleanInputs env others preGenesis r).mapError fun err => s!"{loc}: {err}" + let events := cleanEvents (if preGenesis then none else r.sec.recv) inputs + let (clean', sends) ← (runClean node clean events).mapError fun err => s!"{loc}: {err}" + let mut findings := [] + let failed := (invChecks env.names r.vars).filter (!·.2) |>.map (·.1) + unless failed.isEmpty do + findings := findings ++ [s!"{loc}: invariant fails: {failed}"] + unless r.vars.nodeId == env.names.name node + && env.names.id r.vars.nodeId == node + && ((preGenesis && pristine env r.vars) || agrees env.names clean' r.vars) do + findings := findings ++ [s!"{loc}: not related: {relatedDiff env clean' r.vars}"] + -- `UnnamedUnmatched` (Proofs/Obligation.lean, the proof relation's clean-side conjunct), + -- on the trace's nodes: a clean primary has match index 0 for every other node that no + -- configuration in its log names. + let named := configurationMembers (configurationHistory clean'.log) + let stale := + if clean'.role == .primary then + (List.range env.names.known.size).filter + fun n => n != node && !decide (n ∈ named) && clean'.matchIndex n != 0 + else + [] + unless stale.isEmpty do + findings := findings ++ [s!"{loc}: stale clean match index of unnamed nodes {stale}"] + unless r.ctx.outbox == sends do + findings := + findings + ++ [s!"{loc}: sends differ: clean {sends.map fun x => (x.target, showMessage x.payload)}, cft.h {r.ctx.outbox.map fun x => (x.target, showMessage x.payload)}"] + for x in r.ctx.outbox do + unless msgInv env.names x do + findings := + findings ++ [s!"{loc}: message invariant fails: {showMessage x.payload}"] + return (clean', findings) + +/-- Every finding of the lock-step check over an accepted trace's releases. -/ +def lockstep (env : Env) (v : Verdict) : Except String (List String) := do + let mut cleans := v.keys.map fun k => (k, initialNodeState env.genesis k) + let mut findings := #[] + let mut seen : List NodeID := [] + for r in v.releases do + -- A hold that changed nothing has the same verdict as the node's previous release. + if seen.contains r.node + && r.sec.recv.isNone + && r.ctx.notes.isEmpty + && r.ctx.outbox.isEmpty + && sameVars r.sec.saved r.vars then + continue + seen := if seen.contains r.node then seen else r.node :: seen + let (c, fs) ← checkRelease env cleans r + cleans := cleans.map fun (k, x) => if k == r.node then (k, c) else (k, x) + findings := findings ++ fs + return findings.toList + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Validator.lean b/lean/consensus/Consensus/TraceValidation/Validator.lean new file mode 100644 index 000000000000..b01dea15bb84 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Validator.lean @@ -0,0 +1,354 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Machine + +@[expose] public section + +/-! +# The validator (not reviewed, except through `validate_sound`) + +`schedule` finds an action list for the event-granular network of M_tv: one stream per +node, ordered by `h_ts` within the node's process; any node whose next event is enabled +steps (receives and joiner releases may wait); a node releases when its next event is a +section head or its stream has ended. It never compares `h_ts` across nodes. + +`certify` then replays the action list with the framework's own `next` (`emitsCheck`), +which yields the observation list, and checks that the run started in an initial state +and ended with every lock released. `validate_sound` (in `Consensus.TraceValidation.Proofs.Validator`) turns +a successful `validate` into `CCF.Sections.Accepts`, whatever `schedule` did. +-/ + +namespace Consensus.TraceValidation + +open Lean +open CCF (Envelope) +open CCF.Sections (next) +open CCF.MultiNodeTransitionSystem (nodeState) +open Consensus.Model (initialNodeState) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Ev State Ctx) + +abbrev GState := CCF.Sections.State NodeID Message Local +abbrev GAction := CCF.Sections.Action NodeID Message Ev + +/-! ## Certification: the part `validate_sound` is about -/ + +/-- `CCF.Sections.Emits` as a function: replay the actions, collecting observations. -/ +def emitsCheck (env : Env) : GState -> List GAction -> Option (GState × List Obs) + | s, [] => some (s, []) + | s, .event node e :: rest => + match next (machine env) s (.event node e) with + | none => none + | some s' => + match nodeState s' node with + | none => none + | some slot => + match emitsCheck env s' rest with + | none => none + | some (f, os) => some (f, ⟨node, e, declare slot.current⟩ :: os) + | s, .deliver x e :: rest => + match next (machine env) s (.deliver x e) with + | none => none + | some s' => + match nodeState s' x.target with + | none => none + | some slot => + match emitsCheck env s' rest with + | none => none + | some (f, os) => some (f, ⟨x.target, e, declare slot.current⟩ :: os) + | s, .release node :: rest => + match next (machine env) s (.release node) with + | none => none + | some s' => emitsCheck env s' rest + +/-- The initial network over `keys`. -/ +def start (env : Env) (keys : List NodeID) (ticking : NodeID -> Bool) : GState := + { + nodes := keys.map fun k => (k, { current := initialLocal env k (ticking k) }), + network := [] + } + +/-- +Clean ids of the trace's nodes are their positions in the name table, and a genesis member +is the genesis primary (the clean model starts the other members as followers in term 2, +which `cft.h` has no event for). +-/ +def initOk (env : Env) (k : NodeID) : Bool := + env.names.id (env.names.name k) == k + && (!(k ∈ env.genesis) || env.genesis.min? == some k) + +/-- Replay from the initial state; the observations, if the run is a complete accepted one. -/ +def certify (env : Env) (keys : List NodeID) (ticking : NodeID -> Bool) + (actions : List GAction) + : Option (List Obs) := + if keys.Nodup /\ keys.all (initOk env) = true /\ env.genesis.Nonempty then + match emitsCheck env (start env keys ticking) actions with + | some (f, obs) => + if f.nodes.all (fun e => e.2.entry.isNone) + && obs.all (fun o => Exec.consistent o.event o.declared) then + some obs + else + none + | none => none + else + none + +/-! ## Scheduling (untrusted search for an action list) -/ + +/-- A release, for the diagnostic lock-step check. -/ +structure Release where + node : NodeID + sec : Sec + /-- The handler's context at the end of the hold. -/ + ctx : Ctx + /-- The declared state at release. -/ + vars : State + +structure World where + st : GState + pos : Array Nat + actions : Array GAction := #[] + /-- Dropped copies, still in the framework's network. -/ + dead : List (Envelope NodeID Message) := [] + /-- Drops that found no live copy: a later identical send settles each. -/ + debts : List (NodeID × NodeID × Json) := [] + sections : Nat := 0 + waits : Nat := 0 + releases : Array Release := #[] + +inductive Progress where + | moved + | blocked (why : String) + | done + +def count (x : Envelope NodeID Message) (l : List (Envelope NodeID Message)) : Nat := + (l.filter (· == x)).length + +def World.live (w : World) (x : Envelope NodeID Message) : Bool := + let inboxes := w.st.nodes.filterMap (·.2.inbox) + count x w.st.network > count x w.dead + count x inboxes + +/-- A live in-flight envelope from `source` to `target` with this packet; unique up to identity. -/ +def findLive (w : World) (source target : NodeID) (packet : Json) + : Except String (Option (Envelope NodeID Message)) := do + let hits := + w.st.network.filter + fun x => + x.source == source + && x.target == target + && Exec.packetOf x.payload == packet + && w.live x + match hits with + | [] => return none + | x :: rest => + unless rest.all (· == x) do + throw + s!"ambiguous envelope {source}->{target} {packet.compress}: in-flight copies differ" + return some x + +def apply (env : Env) (w : World) (a : GAction) (diagnose : Unit -> String) + : Except String World := + match next (machine env) w.st a with + | some st => .ok { w with st, actions := w.actions.push a } + | none => .error (diagnose ()) + +def stepNode (env : Env) (streams : Array (NodeID × Array Ev)) (w : World) (i : Nat) + : Except String (World × Progress) := do + let (k, evs) := streams[i]! + let some slot := nodeState w.st k | throw s!"node {k} missing" + let next? := evs[w.pos[i]!]? + let others := (CCF.Sections.without w.st.nodes k).map fun e => (e.1, e.2.base) + if slot.entry.isSome then + if next?.all (isHead env (current slot.current)) then + let release ← + match closeX env others slot.current with + | .error err => + if err.startsWith "wait:" then + return ( + { w with waits := w.waits + 1 }, + .blocked s!"node {env.names.name k}: {err}" + ) + else + throw err + | .ok (l, _, c) => + match slot.current.sec with + | some sec => pure { node := k, sec, ctx := c, vars := l.vars : Release } + | none => throw "internal: release without a section" + let pendingLen := w.st.network.length - (if slot.inbox.isSome then 1 else 0) + let w ← + apply env w (.release k) fun _ => s!"node {env.names.name k}: release refused" + -- Sends that settle earlier drops are dead on arrival. + let mut w2 := + { w with sections := w.sections + 1, releases := w.releases.push release } + for x in w2.st.network.drop pendingLen do + match w2.debts.findIdx? + fun (s, t, p) => + s == x.source && t == x.target && p == Exec.packetOf x.payload with + | some j => w2 := { w2 with debts := w2.debts.eraseIdx j, dead := x :: w2.dead } + | none => pure () + return (w2, .moved) + else + let e := next?.get! + let w ← + apply env w (.event k e) + fun _ => + match stepE env slot.current none e with + | .error err => err + | .ok _ => s!"{e.loc}: lock-taking event inside a section" + return ({ w with pos := w.pos.set! i (w.pos[i]! + 1) }, .moved) + else + let some e := next? | return (w, .done) + let mut w := w + let mut action : GAction := .event k e + if Exec.recvHeads.contains e.function then + let from_ ← at_ e (Exec.getStr e.msg "from_node_id") + let packet ← at_ e (e.msg.getObjVal? "packet") + match ← at_ e (findLive w (env.names.id from_) k packet) with + | some x => action := .deliver x e + | none => + return ( + w, + .blocked + s!"{e.loc} h_ts={e.hts} waits for {from_}->{e.node} {packet.compress}" + ) + else if e.function == "drop_pending_to" then + let to ← at_ e (Exec.getStr e.msg "to_node_id") + let packet ← at_ e (e.msg.getObjVal? "packet") + match ← at_ e (findLive w k (env.names.id to) packet) with + | some x => w := { w with dead := x :: w.dead } + | none => + -- Some receiver took an identical copy early; this drop owes a later identical send. + unless env.names.known.contains to do + throw s!"{e.loc} h_ts={e.hts}: drops a message to unknown node {to}" + w := { w with debts := w.debts ++ [(k, env.names.id to, packet)] } + let recv := + match action with + | .deliver x _ => some (x.source, x.payload) + | _ => none + let w' ← + apply env w action + fun _ => + match stepE env slot.current recv e with + | .error err => err + | .ok _ => s!"{e.loc}: the framework refused the step" + return ({ w' with pos := w'.pos.set! i (w'.pos[i]! + 1) }, .moved) + +structure Verdict where + keys : List NodeID + releases : List Release + actions : List GAction + observations : List Obs + sections : Nat + waits : Nat + inFlight : Nat + +def schedule (env : Env) (ticking : NodeID -> Bool) (streams : Array (NodeID × Array Ev)) + : Except String World := do + let keys := streams.toList.map Prod.fst + let mut w : World := { st := start env keys ticking, pos := streams.map fun _ => 0 } + let total := streams.foldl (fun a (_, s) => a + s.size) 0 + let mut fuel := 4 * total + 4 * streams.size + 16 + repeat + let mut moved := false + let mut blocked := #[] + for i in [0:streams.size] do + let mut go := true + while go do + let (w', p) ← stepNode env streams w i + w := w' + match p with + | .moved => moved := true + | .blocked why => blocked := blocked.push why; go := false + | .done => go := false + if !moved then + if blocked.isEmpty then break + throw + s!"deadlock: every unfinished node waits:\n {"\n ".intercalate blocked.toList}" + fuel := fuel - 1 + if fuel == 0 then throw "scheduler fuel exhausted" + unless w.debts.isEmpty do + throw + s!"drops never settled by an identical send: {w.debts.map fun (s, t, _) => (s, t)}" + return w + +/-- Certify a scheduled action list. -/ +def conclude (env : Env) (ticking : NodeID -> Bool) (streams : List (NodeID × List Ev)) + (w : World) + : Except String Verdict := + let keys := streams.map Prod.fst + match certify env keys ticking w.actions.toList with + | none => .error "internal: the scheduled run does not certify" + | some observations => + if streamsMatch streams observations then + .ok + { + keys, + releases := w.releases.toList, + actions := w.actions.toList, + observations, + sections := w.sections + waits := w.waits, + inFlight := w.st.network.length + } + else + .error "internal: observations differ from the streams" + +/-- +The initial `ticking` of a node: the value carried by its first event that carries one +(every write to `ticking` follows such an event in the same hold), else unobservable. +-/ +def initialTicking (streams : List (NodeID × List Ev)) (k : NodeID) : Bool := + ((streams.lookup k).bind + fun evs => + evs.findSome? fun e => (e.msg.getObjValAs? Bool "ticking").toOption).getD + true + +/-- Schedule, then certify the action list. -/ +def validate (env : Env) (streams : List (NodeID × List Ev)) : Except String Verdict := + let ticking := initialTicking streams + match schedule env ticking (streams.map fun (k, evs) => (k, evs.toArray)).toArray with + | .error err => .error err + | .ok w => conclude env ticking streams w + +/-! ## Trace-wide parameters, from the decoded trace -/ + +partial def collectAddrs (j : Json) (acc : List (Exec.NodeId × String)) + : List (Exec.NodeId × String) := + match j with + | .obj kvs => + kvs.toArray.foldl (init := acc) + fun acc (k, v) => + match v.getObjValAs? String "address" with + | .ok a => if acc.contains (k, a) then acc else (k, a) :: acc + | .error _ => collectAddrs v acc + | .arr vs => vs.foldl (init := acc) fun acc v => collectAddrs v acc + | _ => acc + +/-- The environment and the per-node streams, keyed by clean id. -/ +def environment (ss : List (Exec.NodeId × Array Ev)) + : Except String (Env × List (NodeID × List Ev)) := do + let addrs := + ss.foldl (init := []) + fun acc (_, evs) => + evs.foldl (init := acc) fun acc e => collectAddrs e.msg acc + for (n, a) in addrs do + if addrs.any fun (m, b) => m == n && b != a then throw s!"node {n} has two addresses" + let ids := ((ss.map Prod.fst) ++ addrs.map Prod.fst).mergeSort (· <= ·) |>.eraseDups + let names : Names := { known := ids.toArray } + let firsts := + ss.filterMap + fun (n, evs) => + if (evs[0]?.map (·.function)) == some "become_leader" then + some (names.id n) + else + none + unless firsts.length == 1 do + throw + s!"expected one genesis node (stream starting with become_leader), found {firsts.length}" + let env : Env := { names, addrs, genesis := CCF.Finset.ofList firsts } + return (env, ss.map fun (n, evs) => (names.id n, evs.toList)) + +end Consensus.TraceValidation diff --git a/lean/consensus/replay/ReplayMain.lean b/lean/consensus/replay/ReplayMain.lean index dd7f7c2b12c1..1d076a697cff 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -3,35 +3,60 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.Replay.Reduction +public import Consensus.TraceValidation.Lockstep public section -open Lean Consensus.Replay +open Lean Consensus.TraceValidation.Exec + +/-- +Validate one trace with `Consensus.TraceValidation.validate`, the validator whose +acceptance `Consensus.TraceValidation.accepted_refines` is about. With `refine`, also +run the diagnostic lock-step check against the clean model and fail on any finding. +-/ +def check (refine : Bool) (path : String) : IO Bool := do + let t0 ← IO.monoMsNow + match ← readTrace path with + | .error e => IO.eprintln s!"FAIL {path}: {e}"; return false + | .ok trace => + let r := do + let (env, ss) ← Consensus.TraceValidation.environment (← streams trace) + Consensus.TraceValidation.validate env ss + let t1 ← IO.monoMsNow + match r with + | .ok v => + IO.println + s!"PASS {path}: nodes={v.keys.length} events={v.observations.length} sections={v.sections} actions={v.actions.length} ms={t1 - t0}" + if !refine then return true + let (env, _) ← + IO.ofExcept + (do + Consensus.TraceValidation.environment (← streams trace)) + match Consensus.TraceValidation.lockstep env v with + | .error e => IO.eprintln s!"REFINE-ERROR {path}: {e}"; return false + | .ok [] => return true + | .ok fs => + for f in fs do + IO.eprintln s!"REFINE {path}: {f}" + return false + | .error e => IO.eprintln s!"FAIL {path}: {e}"; return false def main (args : List String) : IO UInt32 := do - try + let (refine, args) := match args with - | [path] => - let records ← readLog path - let result := do - let (events, declared) ← prepareEvents (← records) - let reduced ← reduce events declared - replay reduced.header reduced.instructions - match result with - | .error error => IO.eprintln s!"{path}: {error}"; return 1 - | .ok result => - let result := - Json.mkObj - [ - ("status", toJson "ok"), - ("instructions", toJson result.instructions), - ("actions", toJson result.actions), - ("observations", toJson result.observations) - ] - IO.println result.compress - return 0 - | _ => IO.eprintln "usage: consensus-replay TRACE.ndjson"; return 2 + | "--refine" :: rest => (true, rest) + | _ => (false, args) + if args.isEmpty then + IO.eprintln "usage: consensus-replay [--refine] TRACE.ndjson..." + return 2 + try + let mut failed := 0 + for path in args do + unless ← check refine path do + failed := failed + 1 + if args.length > 1 then + IO.println s!"{args.length - failed}/{args.length} accepted" + return if failed == 0 then 0 else 1 catch error => IO.eprintln s!"{error}" return 1 diff --git a/lean/consensus/replay/fixtures/README.md b/lean/consensus/replay/fixtures/README.md index b6aeda506dc7..94ef5a57f35b 100644 --- a/lean/consensus/replay/fixtures/README.md +++ b/lean/consensus/replay/fixtures/README.md @@ -1,32 +1,24 @@ -# Replay failure fixtures +# Trace validation fixtures -The [Lean workflow](../../../../.github/workflows/lean.yml) runs the synthetic fixtures through the real replay executable. -Replication failures follow a two-node history with a committed signature, membership expansion, a further signature, a joiner initializing from a snapshot at the committed signature, a heartbeat and log replication. -The [valid control](valid/replication.ndjson) continues through follower catch-up, acknowledgement and commit. -Its snapshot installation hooks directly follow the leader's `replicate` batch and include a bare tick, both of which replay must accept. -The [rejected replicate](valid/rejected-replicate.ndjson) control is a `replicate` call that CCF rejected at its first entry, so it traces no `replicate_entry` and appends nothing. -The [bootstrap](valid/bootstrap.ndjson) control starts like a real node: bare ticks before genesis, then a flush of the genesis entry. +The [Lean workflow](../../../../.github/workflows/lean-package.yml) runs these fixtures through the `consensus-replay` executable. +The valid fixtures are unmodified `cft_driver` captures: [two-node startup](valid/startup_2nodes.ndjson), [append](valid/append.ndjson) and [reconfiguration](valid/reconfig_0_1.ndjson). +Each invalid fixture is the two-node startup capture with one change, and must be rejected with exit status 1. -| Fixture | Expected failure | -| ----------------------------------------------------------------------- | ------------------------------------------------------- | -| [Snapshot mismatch](invalid/snapshot-mismatch.ndjson) | Observed view differs from the model | -| [Unsupported snapshot field](invalid/unsupported-snapshot-field.ndjson) | Unsupported observation field | -| [Malformed append](invalid/malformed-append.ndjson) | Boolean append argument expected | -| [Ungrouped event](invalid/ungrouped-event.ndjson) | No reduction rule consumes the event | -| [Disabled append](invalid/disabled-append.ndjson) | Append attempted by a non-leader | -| [Missing packet](invalid/missing-packet.ndjson) | No queued model packet to receive | -| [Packet mismatch](invalid/packet-mismatch.ndjson) | Received index differs from the queued model payload | -| [Retirement on signature](invalid/retirement-signature.ndjson) | Retirement follows a signature `replicate_entry` | -| [Retirement seqno mismatch](invalid/retirement-seqno-mismatch.ndjson) | Retirement seqno differs from its `replicate_entry` | -| [Retirement node mismatch](invalid/retirement-node-mismatch.ndjson) | Retirement follows another node's `replicate_entry` | -| [Retirement non-adjacent](invalid/retirement-nonadjacent.ndjson) | An event separates `replicate_entry` and its retirement | -| [Orphan retirement](invalid/retirement-orphan.ndjson) | Retirement without a `replicate_entry` | -| [Uncommitted snapshot](invalid/uncommitted-snapshot.ndjson) | Joiner initializes at an uncommitted signature | -| [Bootstrap event](invalid/bootstrap-event.ndjson) | Non-tick event before genesis | -| [Bootstrap flush send](invalid/bootstrap-flush-send.ndjson) | Send from the genesis flush, which must send nothing | +| Fixture | Change | Expected failure | +| --------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------- | +| [State mismatch](invalid/state-mismatch.ndjson) | A `replicate_entry` snapshot's `last_idx` is one too high | `state.last_idx` differs from the model | +| [Commit mismatch](invalid/commit-mismatch.ndjson) | A `commit` event's `idx` is lowered | `idx` differs from the model | +| [Match index mismatch](invalid/match-idx-mismatch.ndjson) | A response's `match_idx` is raised | `match_idx` differs from the model | +| [Packet mismatch](invalid/packet-mismatch.ndjson) | A received AppendEntries has a different `prev_idx` | No node can step: the receive matches no published message | +| [Missing send](invalid/missing-send.ndjson) | A `send_append_entries_response` is deleted | The lock is released before the expected trace point | +| [Missing commit](invalid/missing-commit.ndjson) | A `commit` event is deleted | The lock is released before the expected trace point | +| [Unknown trace point](invalid/unknown-trace-point.ndjson) | `execute_append_entries_sync` is renamed | The model expects a different trace point | +| [Reordered events](invalid/reordered-events.ndjson) | Two events of one node are swapped | The model expects a different trace point | +| [Configuration mismatch](invalid/configuration-mismatch.ndjson) | An `add_configuration` hook omits a node | A later send is not explained by the open lock hold | +| [Missing field](invalid/missing-field.ndjson) | `become_leader` lacks its `votes_for_me` field | `votes_for_me` is absent | From `lean/consensus`, inspect a failure directly (exit status 1 is expected): ```sh -lake exe consensus-replay replay/fixtures/invalid/snapshot-mismatch.ndjson +lake exe consensus-replay replay/fixtures/invalid/state-mismatch.ndjson ``` diff --git a/lean/consensus/replay/fixtures/invalid/bootstrap-event.ndjson b/lean/consensus/replay/fixtures/invalid/bootstrap-event.ndjson deleted file mode 100644 index 7031c7c6ed12..000000000000 --- a/lean/consensus/replay/fixtures/invalid/bootstrap-event.ndjson +++ /dev/null @@ -1,13 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"become_follower","state":{"node_id":"0"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"},"seqno":1,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":1,"nodes":{"0":{}}}} -{"msg":{"function":"batch_flush","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} diff --git a/lean/consensus/replay/fixtures/invalid/bootstrap-flush-send.ndjson b/lean/consensus/replay/fixtures/invalid/bootstrap-flush-send.ndjson deleted file mode 100644 index c9bffa2a1357..000000000000 --- a/lean/consensus/replay/fixtures/invalid/bootstrap-flush-send.ndjson +++ /dev/null @@ -1,30 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"batch_flush","state":{"node_id":"0"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":0,"prev_term":0,"idx":1,"leader_commit_idx":0,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":4}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":4}}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":4}} diff --git a/lean/consensus/replay/fixtures/invalid/commit-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/commit-mismatch.ndjson new file mode 100644 index 000000000000..0b773c852b0f --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/commit-mismatch.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id":"3276455-1794853960018847360","h_ts":46,"msg":{"function":"commit","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader","membership_state":"Active","committable_indices":[4]},"idx":3,"configurations":[{"idx":1,"nodes":{"0":{"address":":"}},"rid":1},{"idx":3,"nodes":{"0":{"address":":"},"1":{"address":":"}},"rid":3}],"leader_id":"0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/configuration-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/configuration-mismatch.ndjson new file mode 100644 index 000000000000..5fbcf41fc6bd --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/configuration-mismatch.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id":"3276455-1794853960018847360","h_ts":17,"msg":{"function":"add_configuration","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader","membership_state":"Active","committable_indices":[]},"configurations":[{"idx":1,"nodes":{"0":{"address":":"}},"rid":1}],"idx":3,"nodes":{"0":{"address":":"}},"rid":3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/disabled-append.ndjson b/lean/consensus/replay/fixtures/invalid/disabled-append.ndjson deleted file mode 100644 index 0222cb7ec551..000000000000 --- a/lean/consensus/replay/fixtures/invalid/disabled-append.ndjson +++ /dev/null @@ -1,26 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"cmd":"replicate,2,follower-write"}} -{"msg":{"function":"replicate","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"seqno":5,"globally_committable":false}} diff --git a/lean/consensus/replay/fixtures/invalid/malformed-append.ndjson b/lean/consensus/replay/fixtures/invalid/malformed-append.ndjson deleted file mode 100644 index eee66cc11ffa..000000000000 --- a/lean/consensus/replay/fixtures/invalid/malformed-append.ndjson +++ /dev/null @@ -1,25 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"seqno":5,"globally_committable":"not-a-boolean"}} diff --git a/lean/consensus/replay/fixtures/invalid/match-idx-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/match-idx-mismatch.ndjson new file mode 100644 index 000000000000..ad4dfd27f17e --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/match-idx-mismatch.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id":"3276455-1794853960018847360","h_ts":45,"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader","membership_state":"Active","committable_indices":[4]},"packet":{"msg":"append_entries_response","term":2,"last_log_idx":4,"success":"OK"},"from_node_id":"1","match_idx":4,"sent_idx":4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/missing-commit.ndjson b/lean/consensus/replay/fixtures/invalid/missing-commit.ndjson new file mode 100644 index 000000000000..f24efc31c860 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/missing-commit.ndjson @@ -0,0 +1,63 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/missing-field.ndjson b/lean/consensus/replay/fixtures/invalid/missing-field.ndjson new file mode 100644 index 000000000000..569a1d45a13c --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/missing-field.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id":"3276455-1794853960018847360","h_ts":1,"msg":{"function":"become_leader","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader","membership_state":"Active","committable_indices":[]},"configurations":[],"leader_id":"0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/missing-packet.ndjson b/lean/consensus/replay/fixtures/invalid/missing-packet.ndjson deleted file mode 100644 index 2a6512bd7d88..000000000000 --- a/lean/consensus/replay/fixtures/invalid/missing-packet.ndjson +++ /dev/null @@ -1,24 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_request_vote","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"request_vote","term":3,"last_committable_idx":2,"term_of_last_committable_idx":2}}} diff --git a/lean/consensus/replay/fixtures/invalid/missing-send.ndjson b/lean/consensus/replay/fixtures/invalid/missing-send.ndjson new file mode 100644 index 000000000000..6955d1e8f879 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/missing-send.ndjson @@ -0,0 +1,63 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson index c1b813cec816..0157dc63bd68 100644 --- a/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson +++ b/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson @@ -1,24 +1,64 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":999,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id":"3276455-1794853960018847360","h_ts":41,"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Follower","membership_state":"Active","committable_indices":[]},"packet":{"msg":"append_entries","idx":4,"prev_idx":2,"term":2,"prev_term":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false},"from_node_id":"0","leader_id":"0","is_new_follower":true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/reordered-events.ndjson b/lean/consensus/replay/fixtures/invalid/reordered-events.ndjson new file mode 100644 index 000000000000..70c78ca3e1cc --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/reordered-events.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id":"3276455-1794853960018847360","h_ts":36,"msg":{"function":"commit","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":0,"leadership_state":"Follower","membership_state":"Active","committable_indices":[2]},"idx":2,"configurations":[{"idx":1,"nodes":{"0":{"address":":"}},"rid":1}],"leader_id":"0"}} +{"process_id":"3276455-1794853960018847360","h_ts":37,"msg":{"function":"execute_append_entries_sync","state":{"node_id":"1","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Follower","membership_state":"Active","committable_indices":[]},"from_node_id":"0","ticking":true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/retirement-node-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/retirement-node-mismatch.ndjson deleted file mode 100644 index 70c2d7a74246..000000000000 --- a/lean/consensus/replay/fixtures/invalid/retirement-node-mismatch.ndjson +++ /dev/null @@ -1,7 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","last_idx":1}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","last_idx":1},"seqno":2,"globally_committable":false}} -{"msg":{"function":"retired_committed_tx","node_id":"1","seqno":2,"retired_node_id":"0"}} diff --git a/lean/consensus/replay/fixtures/invalid/retirement-nonadjacent.ndjson b/lean/consensus/replay/fixtures/invalid/retirement-nonadjacent.ndjson deleted file mode 100644 index bf8f3004d6a8..000000000000 --- a/lean/consensus/replay/fixtures/invalid/retirement-nonadjacent.ndjson +++ /dev/null @@ -1,8 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","last_idx":1}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","last_idx":1},"seqno":2,"globally_committable":false}} -{"msg":{"function":"nomination","state":{"node_id":"0","last_idx":2}}} -{"msg":{"function":"retired_committed_tx","node_id":"0","seqno":2,"retired_node_id":"0"}} diff --git a/lean/consensus/replay/fixtures/invalid/retirement-orphan.ndjson b/lean/consensus/replay/fixtures/invalid/retirement-orphan.ndjson deleted file mode 100644 index cba1cf2128eb..000000000000 --- a/lean/consensus/replay/fixtures/invalid/retirement-orphan.ndjson +++ /dev/null @@ -1,6 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"nomination","state":{"node_id":"0","last_idx":1}}} -{"msg":{"function":"retired_committed_tx","node_id":"0","seqno":2,"retired_node_id":"0"}} diff --git a/lean/consensus/replay/fixtures/invalid/retirement-seqno-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/retirement-seqno-mismatch.ndjson deleted file mode 100644 index ce76404e9ef3..000000000000 --- a/lean/consensus/replay/fixtures/invalid/retirement-seqno-mismatch.ndjson +++ /dev/null @@ -1,7 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","last_idx":1}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","last_idx":1},"seqno":2,"globally_committable":false}} -{"msg":{"function":"retired_committed_tx","node_id":"0","seqno":3,"retired_node_id":"0"}} diff --git a/lean/consensus/replay/fixtures/invalid/retirement-signature.ndjson b/lean/consensus/replay/fixtures/invalid/retirement-signature.ndjson deleted file mode 100644 index a02b00c9cbad..000000000000 --- a/lean/consensus/replay/fixtures/invalid/retirement-signature.ndjson +++ /dev/null @@ -1,7 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","last_idx":1}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","last_idx":1},"seqno":2,"globally_committable":true}} -{"msg":{"function":"retired_committed_tx","node_id":"0","seqno":2,"retired_node_id":"0"}} diff --git a/lean/consensus/replay/fixtures/invalid/snapshot-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/snapshot-mismatch.ndjson deleted file mode 100644 index d43b426ffc3d..000000000000 --- a/lean/consensus/replay/fixtures/invalid/snapshot-mismatch.ndjson +++ /dev/null @@ -1,24 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":999,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} diff --git a/lean/consensus/replay/fixtures/invalid/state-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/state-mismatch.ndjson new file mode 100644 index 000000000000..cab846f8eb72 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/state-mismatch.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id":"3276455-1794853960018847360","h_ts":21,"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader","membership_state":"Active","committable_indices":[]},"view":2,"seqno":4,"globally_committable":true,"ticking":true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/uncommitted-snapshot.ndjson b/lean/consensus/replay/fixtures/invalid/uncommitted-snapshot.ndjson deleted file mode 100644 index 7795758d9cca..000000000000 --- a/lean/consensus/replay/fixtures/invalid/uncommitted-snapshot.ndjson +++ /dev/null @@ -1,18 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":4,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} diff --git a/lean/consensus/replay/fixtures/invalid/ungrouped-event.ndjson b/lean/consensus/replay/fixtures/invalid/ungrouped-event.ndjson deleted file mode 100644 index ebcaef1cd9f9..000000000000 --- a/lean/consensus/replay/fixtures/invalid/ungrouped-event.ndjson +++ /dev/null @@ -1,24 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"unsupported_event","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} diff --git a/lean/consensus/replay/fixtures/invalid/unknown-trace-point.ndjson b/lean/consensus/replay/fixtures/invalid/unknown-trace-point.ndjson new file mode 100644 index 000000000000..d39b306df6b1 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/unknown-trace-point.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id":"3276455-1794853960018847360","h_ts":34,"msg":{"function":"execute_append_entries","state":{"node_id":"1","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Follower","membership_state":"Active","committable_indices":[]},"from_node_id":"0","ticking":true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/unsupported-snapshot-field.ndjson b/lean/consensus/replay/fixtures/invalid/unsupported-snapshot-field.ndjson deleted file mode 100644 index 5b86f57dca6a..000000000000 --- a/lean/consensus/replay/fixtures/invalid/unsupported-snapshot-field.ndjson +++ /dev/null @@ -1,24 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower","unsupported_field":true},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} diff --git a/lean/consensus/replay/fixtures/valid/append.ndjson b/lean/consensus/replay/fixtures/valid/append.ndjson new file mode 100644 index 000000000000..e81fb3718fd3 --- /dev/null +++ b/lean/consensus/replay/fixtures/valid/append.ndjson @@ -0,0 +1,40 @@ +{"process_id": "3276124-1794853953554023250", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276124-1794853953554023250", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 12, "msg": {"cmd": "replicate,2,first transaction"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 13, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 14, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 15, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 16, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 17, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 18, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 19, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 20, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 21, "msg": {"cmd": "replicate,2,second transaction"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 22, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 23, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": false, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 24, "msg": {"cmd": "replicate,2,third transaction"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 25, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 26, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 6, "globally_committable": false, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 27, "msg": {"cmd": "replicate,2,fourth transaction"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 28, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 29, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 7, "globally_committable": false, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 30, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 31, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 32, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 7, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 33, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 7, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 8, "globally_committable": true, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 34, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 8, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [8]}, "idx": 8, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 35, "msg": {"cmd": "assert_commit_idx,0,8"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 36, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 8, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276124-1794853953554023250", "h_ts": 37, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 8, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 9, "globally_committable": true, "ticking": true}} +{"process_id": "3276124-1794853953554023250", "h_ts": 38, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 9, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [9]}, "idx": 9, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276124-1794853953554023250", "h_ts": 39, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 9, "commit_idx": 9, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} diff --git a/lean/consensus/replay/fixtures/valid/bootstrap.ndjson b/lean/consensus/replay/fixtures/valid/bootstrap.ndjson deleted file mode 100644 index 528aa350b97b..000000000000 --- a/lean/consensus/replay/fixtures/valid/bootstrap.ndjson +++ /dev/null @@ -1,12 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader"},"seqno":1,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":1,"nodes":{"0":{}}}} -{"msg":{"function":"batch_flush","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} diff --git a/lean/consensus/replay/fixtures/valid/reconfig_0_1.ndjson b/lean/consensus/replay/fixtures/valid/reconfig_0_1.ndjson new file mode 100644 index 000000000000..6c38fc2a0c97 --- /dev/null +++ b/lean/consensus/replay/fixtures/valid/reconfig_0_1.ndjson @@ -0,0 +1,94 @@ +{"process_id": "3276351-1794853957995099402", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276351-1794853957995099402", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 12, "msg": {"cmd": "swap_nodes,2,out,0,in,1"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276351-1794853957995099402", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276351-1794853957995099402", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276351-1794853957995099402", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Ordered", "retirement_idx": 3, "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276351-1794853957995099402", "h_ts": 19, "msg": {"cmd": "assert_detail,0,membership_state,Retired"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 20, "msg": {"cmd": "assert_detail,0,retirement_phase,Ordered"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 21, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 22, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Ordered", "retirement_idx": 3, "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 23, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Ordered", "retirement_idx": 3, "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 24, "msg": {"cmd": "assert_detail,0,membership_state,Retired"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 25, "msg": {"cmd": "assert_detail,0,retirement_phase,Signed"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 26, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 27, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 28, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 29, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 30, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Signed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276351-1794853957995099402", "h_ts": 31, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 32, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Signed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 33, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Signed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276351-1794853957995099402", "h_ts": 34, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 35, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 36, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 37, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 38, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276351-1794853957995099402", "h_ts": 39, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 40, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 41, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 42, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276351-1794853957995099402", "h_ts": 43, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 44, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Signed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276351-1794853957995099402", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Signed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 48, "msg": {"cmd": "cleanup_nodes,2,0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 49, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 50, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": false, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 51, "msg": {"function": "retired_committed_tx", "node_id": "0", "seqno": 5, "retired_node_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 52, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 53, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 54, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": []}, "view": 2, "seqno": 6, "globally_committable": true, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 55, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 56, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 57, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [6]}, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 58, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [6]}, "packet": {"msg": "append_entries", "idx": 6, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276351-1794853957995099402", "h_ts": 59, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 60, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 61, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 6, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 62, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 63, "msg": {"function": "retired_committed_tx", "node_id": "1", "seqno": 5, "retired_node_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 64, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 65, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 6, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 6]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 66, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [6]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 6, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 67, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [6]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 6, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 6}} +{"process_id": "3276351-1794853957995099402", "h_ts": 68, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "committable_indices": [6]}, "idx": 6, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 69, "msg": {"function": "step_down_and_nominate_successor", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 6, "leadership_state": "Leader", "membership_state": "Retired", "retirement_phase": "Completed", "retirement_idx": 3, "retirement_committable_idx": 4, "retired_committed_idx": 5, "committable_indices": []}, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "to_node_id": "1", "leader_id": "0"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 70, "msg": {"function": "recv_propose_request_vote", "state": {"node_id": "1", "current_view": 2, "last_idx": 6, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [6]}, "packet": {"msg": "propose_request_vote", "term": 2}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 71, "msg": {"function": "become_candidate", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Candidate", "membership_state": "Active", "committable_indices": [6]}, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "voted_for": "1", "votes_for_me": [{"idx": 3, "quorum": 1, "votes": []}], "leader_id": null}} +{"process_id": "3276351-1794853957995099402", "h_ts": 72, "msg": {"function": "become_leader", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "votes_for_me": [{"idx": 3, "quorum": 1, "votes": ["1"]}], "leader_id": "1"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 73, "msg": {"function": "send_append_entries", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}, "packet": {"msg": "append_entries", "idx": 6, "prev_idx": 6, "term": 3, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "0", "match_idx": 0, "sent_idx": 6}} +{"process_id": "3276351-1794853957995099402", "h_ts": 74, "msg": {"function": "recv_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 6, "commit_idx": 6, "leadership_state": "None", "membership_state": "Retired", "retirement_phase": "RetiredCommitted", "retirement_idx": 3, "retirement_committable_idx": 4, "retired_committed_idx": 5, "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 6, "prev_idx": 6, "term": 3, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "1", "leader_id": null, "is_new_follower": false}} +{"process_id": "3276351-1794853957995099402", "h_ts": 75, "msg": {"function": "become_follower", "state": {"node_id": "0", "current_view": 3, "last_idx": 6, "commit_idx": 6, "leadership_state": "Follower", "membership_state": "Retired", "retirement_phase": "RetiredCommitted", "retirement_idx": 3, "retirement_committable_idx": 4, "retired_committed_idx": 5, "committable_indices": []}, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "voted_for": null, "votes_for_me": [{"idx": 3, "quorum": 1, "votes": []}], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276351-1794853957995099402", "h_ts": 76, "msg": {"function": "send_append_entries_response", "state": {"node_id": "0", "current_view": 3, "last_idx": 6, "commit_idx": 6, "leadership_state": "Follower", "membership_state": "Retired", "retirement_phase": "RetiredCommitted", "retirement_idx": 3, "retirement_committable_idx": 4, "retired_committed_idx": 5, "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 3, "last_log_idx": 6, "success": "OK"}, "to_node_id": "1"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 77, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}, "packet": {"msg": "append_entries_response", "term": 3, "last_log_idx": 6, "success": "OK"}, "from_node_id": "0", "match_idx": 0, "sent_idx": 6}} +{"process_id": "3276351-1794853957995099402", "h_ts": 78, "msg": {"cmd": "assert_commit_idx,0,6"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 79, "msg": {"cmd": "assert_detail,0,membership_state,Retired"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 80, "msg": {"cmd": "assert_detail,0,retirement_phase,RetiredCommitted"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 81, "msg": {"cmd": "assert_detail,1,leadership_state,Leader"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 82, "msg": {"cmd": "replicate,3,some_tx"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 83, "msg": {"function": "replicate", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 84, "msg": {"function": "replicate_entry", "state": {"node_id": "1", "current_view": 3, "last_idx": 6, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}, "view": 3, "seqno": 7, "globally_committable": false, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 85, "msg": {"cmd": "replicate,3,$"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 86, "msg": {"function": "replicate", "state": {"node_id": "1", "current_view": 3, "last_idx": 7, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 87, "msg": {"function": "replicate_entry", "state": {"node_id": "1", "current_view": 3, "last_idx": 7, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6]}, "view": 3, "seqno": 8, "globally_committable": true, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 88, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 3, "last_idx": 8, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [6, 8]}, "idx": 8, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "leader_id": "1"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 89, "msg": {"cmd": "assert_commit_idx,1,8"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 90, "msg": {"function": "replicate", "state": {"node_id": "1", "current_view": 3, "last_idx": 8, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276351-1794853957995099402", "h_ts": 91, "msg": {"function": "replicate_entry", "state": {"node_id": "1", "current_view": 3, "last_idx": 8, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 3, "seqno": 9, "globally_committable": true, "ticking": true}} +{"process_id": "3276351-1794853957995099402", "h_ts": 92, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 3, "last_idx": 9, "commit_idx": 8, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [9]}, "idx": 9, "configurations": [{"idx": 3, "nodes": {"1": {"address": ":"}}, "rid": 3}], "leader_id": "1"}} +{"process_id": "3276351-1794853957995099402", "h_ts": 93, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 3, "last_idx": 9, "commit_idx": 9, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} diff --git a/lean/consensus/replay/fixtures/valid/rejected-replicate.ndjson b/lean/consensus/replay/fixtures/valid/rejected-replicate.ndjson deleted file mode 100644 index 70f45f6e96a4..000000000000 --- a/lean/consensus/replay/fixtures/valid/rejected-replicate.ndjson +++ /dev/null @@ -1,5 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} diff --git a/lean/consensus/replay/fixtures/valid/replication.ndjson b/lean/consensus/replay/fixtures/valid/replication.ndjson deleted file mode 100644 index e49403ddf49e..000000000000 --- a/lean/consensus/replay/fixtures/valid/replication.ndjson +++ /dev/null @@ -1,28 +0,0 @@ -{"msg":{"function":"become_leader","state":{"node_id":"0"}}} -{"msg":{"function":"replicate","state":{"node_id":"0"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0"},"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"nodes":{"0":{}}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":1,"commit_idx":0,"leadership_state":"Leader"},"seqno":2,"globally_committable":true}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":2}} -{"msg":{"cmd":"trust_nodes,2,1"}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader"},"seqno":3,"globally_committable":false}} -{"msg":{"function":"add_configuration","state":{"node_id":"0"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"replicate","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":3,"commit_idx":2,"leadership_state":"Leader"},"seqno":4,"globally_committable":true}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":2,"nodes":{"0":{}}}} -{"msg":{"function":"tick","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"}}} -{"msg":{"function":"init_as_backup","state":{"node_id":"1","current_view":0,"last_idx":0,"commit_idx":0,"leadership_state":"None"},"seqno":2,"view":2}} -{"msg":{"function":"become_follower","state":{"node_id":"1"}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":2}}} -{"msg":{"function":"tick","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"}}} -{"msg":{"function":"send_append_entries","state":{"node_id":"0"},"to_node_id":"1","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"recv_append_entries","state":{"node_id":"1","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Follower"},"from_node_id":"0","packet":{"msg":"append_entries","term":2,"prev_idx":2,"prev_term":2,"idx":4,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false}}} -{"msg":{"function":"add_configuration","state":{"node_id":"1"},"idx":3,"nodes":{"0":{},"1":{}}}} -{"msg":{"function":"send_append_entries_response","state":{"node_id":"1"},"to_node_id":"0","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":4}}} -{"msg":{"function":"recv_append_entries_response","state":{"node_id":"0","current_view":2,"last_idx":4,"commit_idx":2,"leadership_state":"Leader"},"from_node_id":"1","packet":{"msg":"append_entries_response","term":2,"success":"OK","last_log_idx":4}}} -{"msg":{"function":"commit","state":{"node_id":"0"},"idx":4}} diff --git a/lean/consensus/replay/fixtures/valid/startup_2nodes.ndjson b/lean/consensus/replay/fixtures/valid/startup_2nodes.ndjson new file mode 100644 index 000000000000..73b38373839f --- /dev/null +++ b/lean/consensus/replay/fixtures/valid/startup_2nodes.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} From 419a50b6f8ce117ce1968ea428c4a2f0340cc184 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:08:49 +0000 Subject: [PATCH 08/25] Add the refinement proof framework for trace validation The proof that accepted traces refine the clean model reduces to one obligation per cft.h handler. This adds the reduction: Hoare-style rules for M_tv's handler monad, the obligation statement (`HoldSound` over the proof relation `Rel`), the section-level simulation that discharges the framework side from the obligations, independence of the ghost ledger prefix below a snapshot base, and the validator's scheduling facts. It also adds the lemma libraries several handler proofs share (AppendEntries frames, lifecycle notes, vote counting, and `update_commit`). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 7 + .../Proofs/Handlers/AeHoare.lean | 194 ++ .../Proofs/Handlers/AeLemmas.lean | 418 +++++ .../Proofs/Handlers/LifeHoare.lean | 246 +++ .../Proofs/Handlers/ReplUpdateCommit.lean | 1643 +++++++++++++++++ .../Proofs/Handlers/VoteLemmas.lean | 689 +++++++ .../TraceValidation/Proofs/Monad.lean | 408 ++++ .../TraceValidation/Proofs/Obligation.lean | 240 +++ .../TraceValidation/Proofs/Section.lean | 494 +++++ .../TraceValidation/Proofs/Suffix.lean | 110 ++ .../TraceValidation/Proofs/Validator.lean | 144 ++ 11 files changed, 4593 insertions(+) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeHoare.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeLemmas.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeHoare.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteLemmas.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Section.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Suffix.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index e4ff7c14d2c3..be024661d108 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -5,3 +5,10 @@ public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks +import Consensus.TraceValidation.Proofs.Handlers.AeHoare +import Consensus.TraceValidation.Proofs.Handlers.AeLemmas +import Consensus.TraceValidation.Proofs.Handlers.LifeHoare +import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit +import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas +import Consensus.TraceValidation.Proofs.Section +import Consensus.TraceValidation.Proofs.Validator diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeHoare.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeHoare.lean new file mode 100644 index 000000000000..9c7c777aa117 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeHoare.lean @@ -0,0 +1,194 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Hoare triples over handler runs (not reviewed) + +`Hoare env P x Q`: every successful run of `x` from a declared state and outbox satisfying +`P` ends in a state and outbox satisfying `Q` of the result. A thin layer over `Spec` with +the rules the AppendEntries proof needs, including loops (`forIn` over lists). +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +def Hoare {α : Type} (env : Env) (P : State -> Outbox -> Prop) (x : M α) + (Q : α -> State -> Outbox -> Prop) + : Prop := + forall (c : Ctx) (a : α) (c' : Ctx), + c.env = env + -> P c.vars c.outbox + -> x.run c = .ok (a, c') + -> c'.env = env /\ Q a c'.vars c'.outbox + +namespace Hoare +variable {env : Env} + +theorem run {x : M Unit} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (h : Hoare env P x Q) {vars : State} + {queue : List Action} {final : Bool} {c : Ctx} (hp : P vars []) + (ran : Exec.run env vars queue final x = .ok c) + : Q () c.vars c.outbox := by + unfold Exec.run at ran + split at ran + · rename_i c'' found + cases ran + exact (h _ _ _ rfl hp found).2 + · cases ran + +theorem of_spec {α : Type} {x : M α} {R : State -> Outbox -> α -> State -> Outbox -> Prop} + (h : Spec env x R) {P : State -> Outbox -> Prop} {Q : α -> State -> Outbox -> Prop} + (imp : forall v o a v' o', P v o -> R v o a v' o' -> Q a v' o') + : Hoare env P x Q := by + intro c a c' envOk p ran + obtain ⟨e, r⟩ := h c a c' envOk ran + exact ⟨e, imp _ _ _ _ _ p r⟩ + +theorem bind {α β : Type} {x : M α} {f : α -> M β} {P : State -> Outbox -> Prop} + {R : α -> State -> Outbox -> Prop} {Q : β -> State -> Outbox -> Prop} + (hx : Hoare env P x R) (hf : forall a, Hoare env (R a) (f a) Q) + : Hoare env P (x >>= f) Q := by + intro c b c'' envOk p h + simp only [StateT.run, Bind.bind, StateT.bind, Except.bind] at h + split at h + · cases h + · rename_i r found + obtain ⟨a, c'⟩ := r + obtain ⟨envMid, q⟩ := hx c a c' envOk p found + exact hf a c' b c'' envMid q h + +theorem pre {α : Type} {x : M α} {P P' : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (h : Hoare env P' x Q) + (imp : forall v o, P v o -> P' v o) + : Hoare env P x Q := + fun c a c' e p r => h c a c' e (imp _ _ p) r + +theorem post {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q Q' : α -> State -> Outbox -> Prop} (h : Hoare env P x Q) + (imp : forall a v o, Q a v o -> Q' a v o) + : Hoare env P x Q' := + fun c a c' e p r => (h c a c' e p r).imp id (imp _ _ _) + +theorem false_pre {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (h : forall v o, Not (P v o)) + : Hoare env P x Q := + fun _ _ _ _ p _ => absurd p (h _ _) + +/-- Reason from one fixed starting state and outbox. -/ +theorem pin {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} + (h : forall v0 o0, P v0 o0 -> Hoare env (fun v o => v = v0 /\ o = o0) x Q) + : Hoare env P x Q := + fun c a c' e p r => h c.vars c.outbox p c a c' e ⟨rfl, rfl⟩ r + +/-- Move a pure fact out of the precondition. -/ +theorem lift {α : Type} {φ : Prop} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (h : φ -> Hoare env P x Q) + : Hoare env (fun v o => φ /\ P v o) x Q := + fun c a c' e p r => h p.1 c a c' e p.2 r + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (hx : b -> Hoare env P x Q) + (hy : Not b -> Hoare env P y Q) + : Hoare env P (if b then x else y) Q := by + by_cases hb : b + · simpa [hb] using hx hb + · simpa [hb] using hy hb + +theorem keeps {α : Type} {x : M α} (h : Spec.Keeps env x) {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (imp : forall v o a, P v o -> Q a v o) + : Hoare env P x Q := + of_spec h + fun v o a v' o' p e => by + rw [e.1, e.2] + exact imp v o a p + +theorem pure {α : Type} (a : α) {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (imp : forall v o, P v o -> Q a v o) + : Hoare env P (Pure.pure a : M α) Q := + of_spec (Spec.pure a) + fun v o b v' o' p e => by + rw [e.1, e.2.1, e.2.2] + exact imp v o p + +theorem fail {α : Type} (m : String) {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} + : Hoare env P (Exec.fail m : M α) Q := + of_spec (Spec.fail (P := fun _ _ _ _ _ => False) m) fun _ _ _ _ _ _ f => f.elim + +theorem getV {P : State -> Outbox -> Prop} {Q : State -> State -> Outbox -> Prop} + (imp : forall v o, P v o -> Q v v o) + : Hoare env P Exec.getV Q := + of_spec Spec.getV + fun v o a v' o' p e => by + rw [e.1, e.2.1, e.2.2] + exact imp v o p + +theorem getV_bind {β : Type} {k : State -> M β} {P : State -> Outbox -> Prop} + {Q : β -> State -> Outbox -> Prop} + (h : forall s, Hoare env (fun v o => P v o /\ v = s) (k s) Q) + : Hoare env P (Exec.getV >>= k) Q := + bind (getV (Q := fun s v o => P v o /\ v = s) fun _ _ p => ⟨p, rfl⟩) h + +theorem setV (f : State -> State) {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (imp : forall v o, P v o -> Q () (f v) o) + : Hoare env P (Exec.setV f) Q := + of_spec (Spec.setV f) + fun v o _ v' o' p e => by + rw [e.1, e.2] + exact imp v o p + +theorem send (dst : NodeId) (m : Message) {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} + (imp + : forall v o, + P v o + -> Q () v (o ++ [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id dst) m])) + : Hoare env P (Exec.send dst m) Q := + of_spec (Spec.send dst m) + fun v o _ v' o' p e => by + rw [e.1, e.2] + exact imp v o p + +/-- A loop over a list, with an invariant indexed by the processed prefix. -/ +theorem forIn_list {α β : Type} (l : List α) (init : β) (f : α -> β -> M (ForInStep β)) + (I : List α -> β -> State -> Outbox -> Prop) (Q : β -> State -> Outbox -> Prop) + (step + : forall pre a rest b, + l = pre ++ a :: rest + -> Hoare env (I pre b) (f a b) + fun r v o => + match r with + | .done b' => Q b' v o + | .yield b' => I (pre ++ [a]) b' v o) + (fin : forall b v o, I l b v o -> Q b v o) + : Hoare env (I [] init) (forIn l init f) Q := by + suffices h : forall rest pre, l = pre ++ rest -> forall b, + Hoare env (I pre b) (forIn rest b f) Q from + h l [] rfl init + intro rest + induction rest with + | nil => + intro pre hl b + simp only [List.append_nil] at hl + subst hl + exact pure b fun v o p => fin b v o p + | cons a rest ih => + intro pre hl b + rw [List.forIn_cons] + refine bind (step pre a rest b hl) fun r => ?_ + cases r with + | done b' => exact pure b' fun _ _ q => q + | yield b' => exact ih (pre ++ [a]) (by simp [hl]) b' + +end Hoare + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeLemmas.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeLemmas.lean new file mode 100644 index 000000000000..160de2029c5b --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeLemmas.lean @@ -0,0 +1,418 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Shared lemmas for the AppendEntries obligation (not reviewed) + +Copied from the vote group's lemma library (`Proofs.Vote`), which is on a sibling +branch; the two copies can be merged once both land. + +* `Det`: a handler that deterministically maps the declared state and appends sends. +* `bant`: what `become_aware_of_new_term` does to the declared state. +* Links between `inv` and the clean model: `getTerm_eq`, `isSignatureAt_abs`, + `termAt_abs`, `eq_maxCommittableIndex`, `inv_get` and the `inv_conj` tactic. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open CCF.Sections (LocalRun) + +/-- `x` deterministically maps the declared state by `f` and appends `g` to the outbox. -/ +def Det {α : Type} (env : Env) (x : M α) (f : State -> State) (g : State -> Outbox) + : Prop := + Spec env x fun v o _ v' o' => v' = f v /\ o' = o ++ g v + +namespace Det +variable {env : Env} + +theorem ofKeeps {α : Type} {x : M α} (h : Spec.Keeps env x) + : Det env x id (fun _ => []) := + Spec.weaken h fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, by simp [b]⟩ + +theorem bind {α β : Type} {x : M α} {k : α -> M β} {f f' : State -> State} + {g g' : State -> Outbox} (hx : Det env x f g) (hk : forall a, Det env (k a) f' g') + : Det env (x >>= k) (fun v => f' (f v)) (fun v => g v ++ g' (f v)) := + Spec.weaken (Spec.bind hx hk) + fun _ _ _ _ _ ⟨_, _, _, ⟨h1, h2⟩, h3, h4⟩ => by + subst h1 h2; exact ⟨h3, by simp [h4]⟩ + +theorem getV_bind {β : Type} {k : State -> M β} {f : State -> State -> State} + {g : State -> State -> Outbox} (hk : forall s, Det env (k s) (f s) (g s)) + : Det env (Exec.getV >>= k) (fun v => f v v) (fun v => g v v) := + Spec.weaken (Spec.bind Spec.getV hk) + fun _ _ _ _ _ ⟨_, _, _, ⟨h0, h1, h2⟩, h3, h4⟩ => by + subst h0 h1 h2; exact ⟨h3, h4⟩ + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} {f f' : State -> State} + {g g' : State -> Outbox} (hx : Det env x f g) (hy : Det env y f' g') + : Det env (if b then x else y) (fun v => if b then f v else f' v) + (fun v => if b then g v else g' v) := + Spec.weaken (Spec.ite hx hy) + fun _ _ _ _ _ ⟨p, q⟩ => by + by_cases hb : b + · simpa [hb] using p hb + · simpa [hb] using q hb + +theorem pure {α : Type} (a : α) : Det env (Pure.pure a : M α) id (fun _ => []) := + ofKeeps (Spec.Keeps.pure a) + +theorem setV (f : State -> State) : Det env (Exec.setV f) f (fun _ => []) := + Spec.weaken (Spec.setV f) fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, by simp [b]⟩ + +theorem send (dst : NodeId) (m : Message) + : Det env (Exec.send dst m) id + (fun v => [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id dst) m]) := + Spec.weaken (Spec.send dst m) fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, b⟩ + +theorem trace (fn : String) : Det env (Exec.trace fn) id (fun _ => []) := + ofKeeps (Spec.trace fn) + +theorem emit (k : String) (j : Lean.Json) : Det env (Exec.emit k j) id (fun _ => []) := + ofKeeps (Spec.emit k j) + +theorem emitStr (k s : String) : Det env (Exec.emitStr k s) id (fun _ => []) := + ofKeeps (Spec.emitStr k s) + +theorem congr {α : Type} {x : M α} {f f' : State -> State} {g g' : State -> Outbox} + (h : Det env x f g) (hf : forall v, f v = f' v) (hg : forall v, g v = g' v) + : Det env x f' g' := by + have e1 : f = f' := funext hf + have e2 : g = g' := funext hg + subst e1 e2; exact h + +theorem run {f : State -> State} {g : State -> Outbox} {x : M Unit} (h : Det env x f g) + {vars : State} {queue : List Action} {final : Bool} {c : Ctx} + (ran : Exec.run env vars queue final x = .ok c) + : c.vars = f vars /\ c.outbox = g vars := by + have := Spec.run h ran + simpa using this + +end Det + +/-- Decompose a handler built from `getV`, `setV`, `send` and trace points into `Det`. -/ +macro "ae_det" : tactic => + `(tactic| repeat' (first + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.pure _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.setV _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.send _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.trace _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.emit _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Det.emitStr _ _ + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Det.getV_bind + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Det.bind + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Det.ite + | with_reducible intro)) + +theorem det_traceRecv (env : Env) (fn : String) (from_ : NodeId) (m : Message) + : Det env (Exec.traceRecv fn from_ m) id (fun _ => []) := by + unfold Exec.traceRecv + apply Det.congr + · ae_det + all_goals intro v; simp + +def bant (t : Nat) (v : State) : State := + { + v with + votedFor := if v.currentView != t then none else v.votedFor + currentView := t + votesForMe := v.configurations.map fun c => (c.idx, [], State.quorum c.nodes.length) + leaderId := none + leadership := .follower + isNewFollower := true + } + +theorem det_becomeAware (env : Env) (t : Nat) + : Det env (Exec.becomeAwareOfNewTerm t) (bant t) (fun _ => []) := by + unfold Exec.becomeAwareOfNewTerm Exec.resetVotesForMe Exec.becomeFollower + apply Det.congr + · ae_det + all_goals intro v; simp [bant] + +theorem bant_lastCommittable (t : Nat) (v : State) + : (bant t v).lastCommittable = v.lastCommittable := + rfl + +@[simp] theorem bant_getTerm (t : Nat) (v : State) : (bant t v).getTerm = v.getTerm := rfl + +theorem eligiblePeers_congr {a b : NodeState} (hl : a.log = b.log) + (hc : a.commitIndex = b.commitIndex) (self : NodeID) + : eligiblePeers a self = eligiblePeers b self := by + unfold eligiblePeers NodeState.activeMembers NodeState.retirementCompletedNodes + NodeState.activeConfigurations NodeState.committedLog + rw [hl, hc] + +theorem foldMax_ge_start (p : Nat -> Bool) (l : List Nat) (b : Nat) + : b <= l.foldl (fun best i => if p i then max best i else best) b := by + induction l generalizing b with + | nil => exact Nat.le_refl _ + | cons x xs ih => + simp only [List.foldl_cons] + refine Nat.le_trans ?_ (ih _) + split <;> omega + +theorem foldMax_ge_mem (p : Nat -> Bool) (l : List Nat) (b i : Nat) (hi : i ∈ l) + (hp : p i = true) + : i <= l.foldl (fun best i => if p i then max best i else best) b := by + induction l generalizing b with + | nil => simp at hi + | cons x xs ih => + simp only [List.foldl_cons] + rcases List.mem_cons.mp hi with rfl | hi + · refine Nat.le_trans ?_ (foldMax_ge_start p xs _) + simp only [hp, ite_true]; omega + · exact ih _ hi + +theorem foldMax_cases (p : Nat -> Bool) (l : List Nat) (b : Nat) + : l.foldl (fun best i => if p i then max best i else best) b = b + ∨ p (l.foldl (fun best i => if p i then max best i else best) b) = true := by + induction l generalizing b with + | nil => exact Or.inl rfl + | cons x xs ih => + simp only [List.foldl_cons] + rcases ih (if p x then max b x else b) with h | h + · rw [h] + by_cases hx : p x + · simp only [hx, ite_true] + rcases Nat.le_total b x with hb | hb + · rw [Nat.max_eq_right hb]; exact Or.inr hx + · rw [Nat.max_eq_left hb]; exact Or.inl rfl + · simp [hx] + · exact Or.inr h + +theorem isSignatureAt_le_length {log : List Model.Node.Entry} {i : Nat} + (h : isSignatureAt log i = true) + : i <= log.length := by + unfold isSignatureAt entryAt? at h + split at h + · rename_i e he + split at he + · simp at he + · have := (List.getElem?_eq_some_iff.mp he).1 + omega + · simp at h + +theorem isSignatureAt_zero (log : List Model.Node.Entry) + : isSignatureAt log 0 = false := by + simp [isSignatureAt, entryAt?] + +theorem eq_maxCommittableIndex {log : List Model.Node.Entry} {m : Nat} + (h0 : m = 0 ∨ isSignatureAt log m = true) + (hall : forall i, isSignatureAt log i = true -> i <= m) + : maxCommittableIndex log = m := by + unfold maxCommittableIndex + apply Nat.le_antisymm + · rcases foldMax_cases (isSignatureAt log) (List.range (log.length + 1)) 0 with h | h + · rw [h]; exact Nat.zero_le _ + · exact hall _ h + · rcases h0 with h | h + · rw [h]; exact Nat.zero_le _ + · exact foldMax_ge_mem _ _ _ _ + (List.mem_range.mpr (Nat.lt_succ_of_le (isSignatureAt_le_length h))) h + +theorem le_of_getLast? + : forall {l : List Nat} {x : Nat}, + l.Pairwise (· < ·) -> l.getLast? = some x -> forall y, y ∈ l -> y <= x + | [], _, _, h, _, _ => by simp at h + | [a], _, _, h, _, hy => by simp at h hy; omega + | a :: b :: l, x, hp, h, y, hy => by + have hp' := List.pairwise_cons.mp hp + have h' : (b :: l).getLast? = some x := by simpa using h + have ih := le_of_getLast? hp'.2 h' + rcases List.mem_cons.mp hy with rfl | hy + · exact Nat.le_of_lt (Nat.lt_of_lt_of_le (hp'.1 b (by simp)) (ih b (by simp))) + · exact ih y hy + +theorem isSignatureAt_abs {names : Names} {d : State} (h : d.ledger.size = d.lastIdx) + (i : Nat) + : isSignatureAt (abs names d).log i = (i != 0 && d.ledger[i - 1]?.any (·.sig)) := by + have htake : d.ledger.toList.take d.lastIdx = d.ledger.toList := by + rw [← h, ← Array.length_toList, List.take_length] + simp only [abs, htake, isSignatureAt, entryAt?] + by_cases hi : i = 0 + · simp [hi] + · simp only [hi, ite_false, List.getElem?_map, Array.getElem?_toList] + cases d.ledger[i - 1]? with + | none => simp + | some e => cases hs : e.sig <;> simp [absEntry, hs, EntryContent.isSignature, hi] + +theorem termAt_abs {names : Names} {d : State} (h : d.ledger.size = d.lastIdx) (i : Nat) + : termAt (abs names d).log i + = if i = 0 then 0 else (d.ledger[i - 1]?.map (·.term)).getD 0 := by + have htake : d.ledger.toList.take d.lastIdx = d.ledger.toList := by + rw [← h, ← Array.length_toList, List.take_length] + simp only [abs, htake, termAt, entryAt?] + by_cases hi : i = 0 + · simp [hi] + · simp only [hi, ite_false, List.getElem?_map, Array.getElem?_toList] + cases d.ledger[i - 1]? <;> simp [absEntry] + +theorem inv_get {names : Names} {d : State} (h : inv names d = true) (n : String) + : ((invChecks names d).lookup n).getD true = true := by + unfold inv at h + generalize invChecks names d = l at h ⊢ + induction l with + | nil => rfl + | cons p ps ih => + obtain ⟨k, b⟩ := p + simp only [List.all_cons, Bool.and_eq_true] at h + simp only [List.lookup] + split + · simpa using h.1 + · exact ih h.2 + +/-- The conjunct of `inv` named `n`, from `h : inv names d = true`. -/ +macro "inv_conj " h:term:max n:str : tactic => + `(tactic| ( + have hc := Consensus.TraceValidation.Proofs.Ae.inv_get $h $n + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at hc + first | exact hc | simpa using hc)) + +theorem inv_parts {names : Names} {d : State} (h : inv names d = true) + : d.ledger.size = d.lastIdx + /\ d.commitIdx <= d.lastIdx + /\ d.committable = signaturesIn d d.commitIdx d.lastIdx + /\ (d.commitIdx = 0 \/ d.ledger[d.commitIdx - 1]?.any (·.sig) = true) + /\ (forall i, + 1 <= i -> i <= d.lastIdx -> d.ledger[i - 1]?.map (·.term) = some (d.viewAt i)) + /\ d.views.size <= d.currentView + /\ d.views.all (0 < ·) = true := by + refine ⟨ + by inv_conj h "ledger_size", + by inv_conj h "commit_le_last", + by inv_conj h "committable", + by inv_conj h "commit_at_signature", + ?_, + by inv_conj h "views_bounded", + by inv_conj h "views_positive" + ⟩ + intro i hi1 hi2 + have h5 : (List.range' 1 d.lastIdx).all + (fun i => d.ledger[i - 1]?.map (·.term) == some (d.viewAt i)) = true := by + inv_conj h "terms_are_views" + have := List.all_eq_true.mp h5 i (List.mem_range'.mpr ⟨i - 1, by omega, by omega⟩) + simpa using this + +theorem lastCommittable_eq {names : Names} {d : State} (h : inv names d = true) + : d.lastCommittable = maxCommittableIndex (abs names d).log := by + obtain ⟨h1, h2, h3, h4, -⟩ := inv_parts h + have hsig := isSignatureAt_abs (names := names) h1 + have hmem : forall x, x ∈ d.committable ↔ (d.commitIdx < x /\ x <= d.lastIdx + /\ d.ledger[x - 1]?.any (·.sig) = true) := by + intro x + rw [h3] + simp only [signaturesIn, List.mem_filter, List.mem_range'] + constructor + · rintro ⟨⟨k, hk, rfl⟩, hs⟩; exact ⟨by omega, by omega, hs⟩ + · rintro ⟨a, b, c⟩; exact ⟨⟨x - (d.commitIdx + 1), by omega, by omega⟩, c⟩ + have hsorted : d.committable.Pairwise (· < ·) := by + rw [h3]; exact (List.pairwise_lt_range' ..).filter _ + have hbound : forall i, d.ledger[i - 1]?.any (·.sig) = true -> i != 0 -> i <= d.lastIdx := by + intro i hs hi + cases he : d.ledger[i - 1]? with + | none => simp [he] at hs + | some e => + have := (Array.getElem?_eq_some_iff.mp he).1 + simp at hi; omega + symm + unfold State.lastCommittable + cases hl : d.committable.getLast? with + | none => + have hnil : d.committable = [] := List.getLast?_eq_none_iff.mp hl + simp only [Option.getD_none] + apply eq_maxCommittableIndex + · by_cases hc : d.commitIdx = 0 + · exact Or.inl hc + · right; rw [hsig] + have h4 := h4.resolve_left hc + simp only [h4, Bool.and_true]; simpa using hc + · intro i hi + rw [hsig] at hi + simp only [Bool.and_eq_true] at hi + refine Nat.le_of_not_lt fun hlt => ?_ + have := (hmem i).mpr ⟨hlt, hbound i hi.2 hi.1, hi.2⟩ + simp [hnil] at this + | some x => + simp only [Option.getD_some] + have hx := (hmem x).mp (List.mem_of_getLast? hl) + apply eq_maxCommittableIndex + · right; rw [hsig]; simp only [hx.2.2, Bool.and_true]; simp; omega + · intro i hi + rw [hsig] at hi + simp only [Bool.and_eq_true] at hi + by_cases hlt : d.commitIdx < i + · exact le_of_getLast? hsorted hl i ((hmem i).mpr ⟨hlt, hbound i hi.2 hi.1, hi.2⟩) + · omega + +theorem viewAt_zero {d : State} (h : d.views.all (0 < ·) = true) : d.viewAt 0 = 0 := by + simp only [State.viewAt, List.length_eq_zero_iff, List.filter_eq_nil_iff] + intro x hx + have := (Array.all_eq_true_iff_forall_mem.mp h) x (by simpa using hx) + simp at this ⊢; omega + +theorem getTerm_eq {names : Names} {d : State} (h : inv names d = true) (i : Nat) + : d.getTerm i = termAt (abs names d).log i := by + obtain ⟨h1, -, -, -, h5, -, h7⟩ := inv_parts h + rw [termAt_abs h1] + unfold State.getTerm + by_cases hi : i = 0 + · subst hi; simp [viewAt_zero h7] + · by_cases hl : i > d.lastIdx + · have : d.ledger[i - 1]? = none := by simp; omega + simp [hl, hi, this] + · simp only [hl, hi, ite_false] + rw [h5 i (by omega) (by omega)]; rfl + +theorem agrees_bant {names : Names} {c : NodeState} {d : State} (t : Nat) + (h : agrees names c d = true) + : agrees names (Model.Node.becomeAwareOfNewTerm c t) (bant t d) = true := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩, h11⟩ := h + simp only [abs, bant, Model.Node.becomeAwareOfNewTerm, trackedPeers, absRole] at * + rw [h2] + by_cases ht : d.currentView = t <;> simp [ht, h3, h4, h7, h11] <;> decide + +theorem updateTerm_of_lt {c : NodeState} {t : Nat} (h : c.currentTerm < t) + : updateTerm c t = Model.Node.becomeAwareOfNewTerm c t := by + simp [updateTerm, h] + +theorem updateTerm_of_ge {c : NodeState} {t : Nat} (h : ¬ c.currentTerm < t) + : updateTerm c t = c := by + simp [updateTerm, h] + +theorem agrees_term_log {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.currentTerm = d.currentView /\ c.log = (abs names d).log := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨-, h2⟩, h3⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩ := h + exact ⟨h2, h3⟩ + +theorem msgInv_source {names : Names} {e : CCF.Envelope NodeID Message} + (h : msgInv names e = true) + : names.id (names.name e.source) = e.source := by + simp only [msgInv, Bool.and_eq_true, beq_iff_eq] at h + exact h.1.1.1.1 + +theorem msgInv_reply {names : Names} {node source : NodeID} {m m' : Message} + (hn : names.id (names.name node) = node) (h : msgInv names ⟨source, node, m⟩ = true) + (hm' : forall r, m' ≠ .appendEntriesRequest r) + : msgInv names ⟨node, source, m'⟩ = true := by + simp only [msgInv, Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq] at h ⊢ + refine ⟨⟨⟨⟨hn, fun e => h.1.1.1.2 e.symm⟩, ?_⟩, ?_⟩, ?_⟩ <;> cases m' <;> simp_all + +theorem agrees_vote_parts {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.votedFor = d.votedFor.map names.id /\ c.primaryKnown = d.leaderId.isSome := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨-, -⟩, -⟩, -⟩, -⟩, -⟩, h7⟩, h8⟩, -⟩, -⟩, -⟩ := h + exact ⟨h7, h8⟩ + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeHoare.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeHoare.lean new file mode 100644 index 000000000000..bdb66a30cec8 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeHoare.lean @@ -0,0 +1,246 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Hoare triples over handler runs (not reviewed; lifecycle obligations) + +`Tri env P x Q`: every successful run of `x` from a context whose declared state and outbox +satisfy `P` ends in a declared state and outbox satisfying `Q` of its result. `Pres env I x` +is the invariant form `Tri env I x (fun _ => I)`. The rules mirror `Spec`'s, plus loops +(`forIn` over lists) and the reuse of every `Spec`/`Keeps` lemma of +`Consensus.TraceValidation.Proofs.Monad`. +-/ + +namespace Consensus.TraceValidation.Proofs.Life + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- A Hoare triple over handler runs. -/ +def Tri {α : Type} (env : Env) (P : State -> Outbox -> Prop) (x : M α) + (Q : α -> State -> Outbox -> Prop) + : Prop := + forall (c : Ctx) (a : α) (c' : Ctx), + c.env = env + -> P c.vars c.outbox + -> x.run c = .ok (a, c') + -> c'.env = env /\ Q a c'.vars c'.outbox + +/-- `x` preserves `I`. -/ +abbrev Pres {α : Type} (env : Env) (I : State -> Outbox -> Prop) (x : M α) : Prop := + Tri env I x fun _ => I + +namespace Tri + +variable {env : Env} {α β : Type} + +theorem ofSpec {x : M α} {S : State -> Outbox -> α -> State -> Outbox -> Prop} + {P : State -> Outbox -> Prop} {Q : α -> State -> Outbox -> Prop} (s : Spec env x S) + (h : forall v o a v' o', P v o -> S v o a v' o' -> Q a v' o') + : Tri env P x Q := by + intro c a c' e p r + obtain ⟨e', s'⟩ := s c a c' e r + exact ⟨e', h _ _ _ _ _ p s'⟩ + +theorem keeps {x : M α} {P : State -> Outbox -> Prop} (k : Spec.Keeps env x) + : Tri env P x fun _ => P := + ofSpec k fun _ _ _ _ _ p h => by obtain ⟨rfl, rfl⟩ := h; exact p + +theorem bind {x : M α} {f : α -> M β} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} {R : β -> State -> Outbox -> Prop} + (hx : Tri env P x Q) (hf : forall a, Tri env (Q a) (f a) R) + : Tri env P (x >>= f) R := by + intro c b c'' e p h + simp only [StateT.run, Bind.bind, StateT.bind, Except.bind] at h + split at h + · cases h + · rename_i r found + obtain ⟨a, c'⟩ := r + obtain ⟨e', q⟩ := hx c a c' e p found + exact hf a c' b c'' e' q h + +theorem pure' (a : α) {Q : α -> State -> Outbox -> Prop} + : Tri env (Q a) (Pure.pure a : M α) Q := + ofSpec (Spec.pure a) fun _ _ _ _ _ p h => by obtain ⟨rfl, rfl, rfl⟩ := h; exact p + +theorem conseq {x : M α} {P P' : State -> Outbox -> Prop} + {Q Q' : α -> State -> Outbox -> Prop} (t : Tri env P' x Q') + (pre : forall v o, P v o -> P' v o) (post : forall a v o, Q' a v o -> Q a v o) + : Tri env P x Q := by + intro c a c' e p r + obtain ⟨e', q⟩ := t c a c' e (pre _ _ p) r + exact ⟨e', post _ _ _ q⟩ + +theorem ite {b : Prop} [Decidable b] {x y : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (hx : b -> Tri env P x Q) + (hy : Not b -> Tri env P y Q) + : Tri env P (if b then x else y) Q := by + by_cases hb : b + · simpa [hb] using hx hb + · simpa [hb] using hy hb + +theorem throw_ {P : State -> Outbox -> Prop} {Q : α -> State -> Outbox -> Prop} + (stop : Stop) + : Tri env P (throw stop : M α) Q := + ofSpec (Spec.throw_ (P := fun _ _ _ _ _ => False) stop) fun _ _ _ _ _ _ f => f.elim + +theorem fail {P : State -> Outbox -> Prop} {Q : α -> State -> Outbox -> Prop} + (msg : String) + : Tri env P (Exec.fail msg : M α) Q := + throw_ _ + +theorem preFalse {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (h : forall v o, P v o -> False) + : Tri env P x Q := by + intro c a c' _ p _ + exact (h _ _ p).elim + +theorem fail_bind {f : α -> M β} {P : State -> Outbox -> Prop} + {Q : β -> State -> Outbox -> Prop} (msg : String) + : Tri env P (Exec.fail msg >>= f) Q := + bind (Q := fun _ _ _ => False) (fail msg) fun _ => preFalse fun _ _ f => f + +theorem getV_bind {f : State -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} + (h : forall v, Tri env (fun w o => P w o /\ w = v) (f v) R) + : Tri env P (Exec.getV >>= f) R := + bind + (ofSpec (Q := fun a w o => P w o /\ w = a) Spec.getV + fun _ _ _ _ _ p h => by obtain ⟨rfl, rfl, rfl⟩ := h; exact ⟨p, rfl⟩) + h + +theorem setV {f : State -> State} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (h : forall v o, P v o -> Q () (f v) o) + : Tri env P (Exec.setV f) Q := + ofSpec (Spec.setV f) fun _ _ _ _ _ p e => by obtain ⟨rfl, rfl⟩ := e; exact h _ _ p + +theorem send {dst : NodeId} {m : Message} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} + (h + : forall v o, + P v o + -> Q () v (o ++ [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id dst) m])) + : Tri env P (Exec.send dst m) Q := + ofSpec (Spec.send dst m) fun _ _ _ _ _ p e => by obtain ⟨rfl, rfl⟩ := e; exact h _ _ p + +theorem forIn_list {l : List α} {init : β} {f : α -> β -> M (ForInStep β)} + {I : State -> Outbox -> Prop} (h : forall a b, a ∈ l -> Pres env I (f a b)) + : Pres env I (forIn l init f) := by + induction l generalizing init with + | nil => + rw [List.forIn_nil] + exact pure' (Q := fun _ => I) init + | cons a rest ih => + rw [List.forIn_cons] + refine bind (h a init (List.mem_cons_self ..)) fun r => ?_ + cases r with + | done b => exact pure' (Q := fun _ => I) b + | yield b => exact ih (fun a' b' m => h a' b' (List.mem_cons_of_mem _ m)) + +theorem map {x : M α} {g : α -> β} {P : State -> Outbox -> Prop} + {Q : β -> State -> Outbox -> Prop} (t : Tri env P x fun a => Q (g a)) + : Tri env P (g <$> x) Q := by + rw [map_eq_pure_bind] + exact bind t fun a => pure' (Q := Q) (g a) + +theorem discard {x : M α} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (t : Tri env P x fun _ => Q ()) + : Tri env P (Functor.discard x) Q := by + simp only [Functor.discard] + exact map t + +end Tri + +namespace Pres + +variable {env : Env} {α β : Type} {I : State -> Outbox -> Prop} + +theorem bind {x : M α} {f : α -> M β} (hx : Pres env I x) + (hf : forall a, Pres env I (f a)) + : Pres env I (x >>= f) := + Tri.bind hx hf + +theorem pure (a : α) : Pres env I (Pure.pure a : M α) := Tri.pure' (Q := fun _ => I) a + +theorem fail (msg : String) : Pres env I (Exec.fail msg : M α) := Tri.fail msg + +theorem ite {b : Prop} [Decidable b] {x y : M α} (hx : b -> Pres env I x) + (hy : Not b -> Pres env I y) + : Pres env I (if b then x else y) := + Tri.ite hx hy + +theorem keeps {x : M α} (k : Spec.Keeps env x) : Pres env I x := Tri.keeps k + +theorem setV {f : State -> State} (h : forall v o, I v o -> I (f v) o) + : Pres env I (Exec.setV f) := + Tri.setV h + +theorem getV_bind {f : State -> M β} (h : forall v o, I v o -> Pres env I (f v)) + : Pres env I (Exec.getV >>= f) := + Tri.getV_bind + fun v => + fun c a c' e ⟨p, eq⟩ r => h v c.outbox (eq ▸ p) c a c' e p r + +end Pres + +/-- One structural step of a `Pres` proof: control first, then primitives. -/ +macro "pres_step" : tactic => + `(tactic| + first + | with_reducible exact Tri.fail_bind _ + | with_reducible refine Pres.bind ?_ (fun _ => ?_) + | with_reducible refine Pres.ite (fun _ => ?_) (fun _ => ?_) + | with_reducible refine Tri.forIn_list (fun _ _ _ => ?_) + | split + | with_reducible exact Pres.pure _ + | with_reducible exact Pres.fail _ + | with_reducible exact Pres.keeps (Spec.trace _) + | with_reducible exact Pres.keeps (Spec.emit _ _) + | with_reducible exact Pres.keeps (Spec.emitStr _ _) + | with_reducible exact Pres.keeps (Spec.emitNat _ _) + | with_reducible exact Pres.keeps Spec.look + | with_reducible exact Pres.keeps Spec.lookFn + | with_reducible exact Pres.keeps Spec.curLoc + | with_reducible exact Pres.keeps (Spec.liftE _) + | with_reducible exact Pres.keeps (Spec.use _) + | with_reducible exact Pres.keeps (Spec.inNat _) + | with_reducible exact Pres.keeps (Spec.inStr _) + | with_reducible exact Pres.keeps (Spec.inBool _) + | with_reducible exact Pres.keeps (Spec.note _) + | with_reducible exact Pres.keeps (Spec.weaken Spec.getV fun _ _ _ _ _ h => h.2) + | with_reducible exact Pres.keeps (Spec.weaken Spec.names fun _ _ _ _ _ h => h.2)) + +variable {env : Env} + +/-- Any run: what `Tri` says holds of a hold's result. -/ +theorem Tri.run {x : M Unit} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (t : Tri env P x Q) {vars : State} + {queue : List Action} {final : Bool} {c : Ctx} (pre : P vars []) + (h : Exec.run env vars queue final x = .ok c) + : Q () c.vars c.outbox := by + unfold Exec.run at h + split at h + · rename_i c'' found + cases h + exact (t _ _ _ rfl pre found).2 + · cases h + +/-- `highest_committable_idx` reads the state and fails or returns. -/ +theorem pres_highest {I : State -> Outbox -> Prop} (first : Nat) + : Pres env I (highestCommittableIdx first) := by + unfold highestCommittableIdx + repeat' (first | pres_step | dsimp only) + +theorem pres_otherNodesSorted {I : State -> Outbox -> Prop} + : Pres env I otherNodesSorted := by + unfold otherNodesSorted + repeat' pres_step + +end Consensus.TraceValidation.Proofs.Life diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean new file mode 100644 index 000000000000..ba2adadb5934 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean @@ -0,0 +1,1643 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Monad +public import Consensus.TraceValidation.Invariant +public import CCF.Proofs.Finset + +@[expose] public section + +/-! +# `update_commit` chooses the clean `highestCommittableIndex` (not reviewed) + +Shared by the `Repl` and `AeResp` handler proofs. M_tv's `update_commit` loop +(`Exec.updateCommitGo`, mirrored purely by `updateCommitOf`) walks the active +configurations in order and commits the highest index that every configuration's +majority has confirmed. On a declared state satisfying `inv`, the result is the clean +`highestCommittableIndex` of the abstracted state: + +* `updateCommitGo_spec`: the monadic loop reads the state, changes nothing and returns + `updateCommitOf`; +* `updateCommit_eq_of_inv`: `inv names v = true` and `updateCommitOf v 0 none fuel = .ok r` + give `highestCommittableIndex (abs names v) (names.id v.nodeId) = r.getD v.commitIdx` + (`none` means no index to commit, and the clean index is the current commit index). +-/ + +namespace Consensus.TraceValidation.Proofs.ReplUpdateCommit + +/-! ## The median of sorted match indexes -/ + +theorem sorted_le {s : List Nat} (sorted : s.Pairwise (· ≤ ·)) {i j : Nat} (ij : i ≤ j) + (hj : j < s.length) + : s[i]'(Nat.lt_of_le_of_lt ij hj) ≤ s[j] := by + rcases Nat.lt_or_eq_of_le ij with lt | rfl + · exact List.pairwise_iff_getElem.mp sorted i j _ hj lt + · exact Nat.le_refl _ + +/-- +In a sorted list, the element at `(n - 1) / 2` is the largest `t` that more than half of +the elements reach. +-/ +theorem sorted_median_iff {s : List Nat} (sorted : s.Pairwise (· ≤ ·)) {x : Nat} + (median : s[(s.length - 1) / 2]? = some x) (t : Nat) + : s.countP (fun m => decide (t ≤ m)) * 2 > s.length <-> t ≤ x := by + have hk : (s.length - 1) / 2 < s.length := by + rcases List.getElem?_eq_some_iff.mp median with ⟨h, _⟩ + exact h + have hx : s[(s.length - 1) / 2] = x := by + rcases List.getElem?_eq_some_iff.mp median with ⟨_, e⟩ + exact e + constructor + · intro many + apply Nat.le_of_not_lt + intro below + have low : (s.take ((s.length - 1) / 2 + 1)).countP (fun m => decide (t ≤ m)) = 0 := by + rw [List.countP_eq_zero] + intro y mem + rcases List.mem_iff_getElem.mp mem with ⟨i, hi, rfl⟩ + simp only [List.length_take] at hi + simp only [List.getElem_take, decide_eq_true_eq, Nat.not_le] + have : s[i] ≤ s[(s.length - 1) / 2] := sorted_le sorted (by omega) hk + omega + have high : + (s.drop ((s.length - 1) / 2 + 1)).countP (fun m => decide (t ≤ m)) + <= s.length - ((s.length - 1) / 2 + 1) := by + have := List.countP_le_length (p := fun m => decide (t ≤ m)) + (l := s.drop ((s.length - 1) / 2 + 1)) + simpa only [List.length_drop] using this + have split := List.take_append_drop ((s.length - 1) / 2 + 1) s + have total := congrArg (List.countP fun m => decide (t ≤ m)) split + rw [List.countP_append, low] at total + omega + · intro le + have high : + (s.drop ((s.length - 1) / 2)).countP (fun m => decide (t ≤ m)) + = s.length - (s.length - 1) / 2 := by + rw [List.countP_eq_length.mpr, List.length_drop] + intro y mem + rcases List.mem_iff_getElem.mp mem with ⟨i, hi, rfl⟩ + simp only [List.length_drop] at hi + simp only [List.getElem_drop, decide_eq_true_eq] + have : s[(s.length - 1) / 2] ≤ s[(s.length - 1) / 2 + i] := + sorted_le sorted (by omega) (by omega) + omega + have split := List.take_append_drop ((s.length - 1) / 2) s + have total := congrArg (List.countP fun m => decide (t ≤ m)) split + rw [List.countP_append, high] at total + omega + +/-- The median of the sorted match indexes, as `confirmedIdx` computes it. -/ +theorem median_iff {ms : List Nat} {x : Nat} + (median : (ms.mergeSort)[(ms.mergeSort.length - 1) / 2]? = some x) (t : Nat) + : ms.countP (fun m => decide (t ≤ m)) * 2 > ms.length <-> t ≤ x := by + have perm := List.mergeSort_perm ms (fun a b => decide (a ≤ b)) + have sorted : (ms.mergeSort).Pairwise (· ≤ ·) := by + have := List.pairwise_mergeSort (le := fun a b : Nat => decide (a ≤ b)) + (fun a b c ab bc => by simp only [decide_eq_true_eq] at *; omega) + (fun a b => by simp only [Bool.or_eq_true, decide_eq_true_eq]; omega) ms + simpa only [decide_eq_true_eq] using this + rw [← perm.countP_eq, ← perm.length_eq] + exact sorted_median_iff sorted median t + +/-! ## The loop of `highest_committable_idx` -/ + +open Consensus.TraceValidation.Exec (State Config) + +section Agreement + +variable (v : State) (L : Nat) (Q : Config -> Nat -> Prop) + +/-- Every configuration of `K` that `t` reaches has a majority at `t`. -/ +def AllReach (K : List Config) (t : Nat) : Prop := + forall c, c ∈ K -> c.idx <= t -> Q c t + +/-- Some configuration of `K` is at or before `t`, and each such has a majority at `t`. -/ +def Acc (K : List Config) (t : Nat) : Prop := + (exists c, c ∈ K /\ c.idx <= t) /\ AllReach Q K t + +variable {v L Q} + +theorem agreementGo_go + : forall (K : List Config) (l : Nat) (agr r : Option Nat) (h0 : Nat) + (A : Nat -> Prop), + (forall c, + c ∈ K + -> forall x, + Exec.confirmedIdx v c = .ok x -> forall t, t <= L -> (Q c t <-> t <= x)) + -> K.Pairwise (fun a b => a.idx < b.idx) + -> (forall c, c ∈ K -> 0 < c.idx) + -> Exec.agreementGo v (some l) K agr = .ok r + -> agr + = some + (match K.head? with + | some n => min l (n.idx - 1) + | none => l) + -> (forall t, t <= L -> (A t <-> h0 <= t /\ t <= l)) + -> forall t, + t <= L + -> (A t /\ AllReach Q K t <-> exists a, r = some a /\ h0 <= t /\ t <= a) + | [], l, agr, r, h0, A, _, _, _, run, hagr, hA, t, tL => by + simp only [Exec.agreementGo, Except.ok.injEq] at run + subst run + subst hagr + simp only [List.head?_nil, Option.some.injEq, exists_eq_left'] + rw [hA t tL] + simp [AllReach] + | c :: rest, l, agr, r, h0, A, hQ, sorted, pos, run, hagr, hA, t, tL => by + simp only [Exec.agreementGo] at run + cases hx : Exec.confirmedIdx v c with + | error e => simp [hx, bind, Except.bind] at run + | ok x => + simp only [hx, bind, Except.bind, pure, Except.pure] at run + have hc := hQ c List.mem_cons_self x hx + have restAbove : forall c', c' ∈ rest -> c.idx < c'.idx := by + intro c' mem + exact List.rel_of_pairwise_cons sorted mem + by_cases br : min l x < c.idx + · simp only [br, ite_true, Except.ok.injEq] at run + subst run + subst hagr + simp only [List.head?_cons, Option.some.injEq, exists_eq_left'] + have cpos := pos c List.mem_cons_self + constructor + · rintro ⟨at_, all⟩ + rw [hA t tL] at at_ + refine ⟨at_.1, ?_⟩ + have : t < c.idx := by + apply Nat.lt_of_not_le + intro reach + have := (hc t tL).mp (all c List.mem_cons_self reach) + omega + omega + · rintro ⟨h0t, tle⟩ + refine ⟨(hA t tL).mpr ⟨h0t, by omega⟩, ?_⟩ + intro c' mem reach + rcases List.mem_cons.mp mem with rfl | mem + · omega + · have := restAbove c' mem + omega + · simp only [br, ite_false] at run + have ih := + agreementGo_go rest (min l x) _ r h0 + (fun t => A t /\ (c.idx <= t -> Q c t)) + (fun c' mem => hQ c' (List.mem_cons_of_mem _ mem)) (List.Pairwise.of_cons sorted) + (fun c' mem => pos c' (List.mem_cons_of_mem _ mem)) run rfl + (by + intro t tL + rw [hA t tL] + constructor + · rintro ⟨⟨h0t, tl⟩, q⟩ + refine ⟨h0t, Nat.le_min.mpr ⟨tl, ?_⟩⟩ + by_cases reach : c.idx <= t + · exact (hc t tL).mp (q reach) + · omega + · rintro ⟨h0t, tle⟩ + have := Nat.le_min.mp tle + exact ⟨⟨h0t, this.1⟩, fun _ => (hc t tL).mpr this.2⟩) + t tL + rw [← ih] + simp only [AllReach, List.mem_cons, forall_eq_or_imp] + constructor + · rintro ⟨at_, q, all⟩ + exact ⟨⟨at_, q⟩, all⟩ + · rintro ⟨⟨at_, q⟩, all⟩ + exact ⟨at_, q, all⟩ + +/-- +`highest_committable_idx`'s loop over sorted configurations: an index within the ledger is +reached by a majority of every configuration it reaches, and reaches one, exactly when it +is at most the loop's result, and at least the first configuration's index. +-/ +theorem agreementGo_spec {K : List Config} + (hQ + : forall c, + c ∈ K + -> forall x, + Exec.confirmedIdx v c = .ok x -> forall t, t <= L -> (Q c t <-> t <= x)) + {r : Option Nat} (sorted : K.Pairwise (fun a b => a.idx < b.idx)) + (pos : forall c, c ∈ K -> 0 < c.idx) (run : Exec.agreementGo v none K none = .ok r) + : forall t, + t <= L + -> (Acc Q K t + <-> exists a c, r = some a /\ K.head? = some c /\ c.idx <= t /\ t <= a) := by + intro t tL + cases K with + | nil => + simp only [Exec.agreementGo, Except.ok.injEq] at run + subst run + simp [Acc] + | cons c rest => + simp only [Exec.agreementGo] at run + cases hx : Exec.confirmedIdx v c with + | error e => simp [hx, bind, Except.bind] at run + | ok x => + simp only [hx, bind, Except.bind, pure, Except.pure] at run + have hc := hQ c List.mem_cons_self x hx + have restAbove : forall c', c' ∈ rest -> c.idx < c'.idx := by + intro c' mem + exact List.rel_of_pairwise_cons sorted mem + have accIff : Acc Q (c :: rest) t <-> (c.idx <= t /\ (c.idx <= t -> Q c t)) + /\ AllReach Q rest t := by + simp only [Acc, AllReach, List.mem_cons, exists_eq_or_imp, forall_eq_or_imp] + constructor + · rintro ⟨ex, q, all⟩ + refine ⟨⟨?_, q⟩, all⟩ + rcases ex with reach | ⟨c', mem, reach⟩ + · exact reach + · have := restAbove c' mem + omega + · rintro ⟨⟨reach, q⟩, all⟩ + exact ⟨Or.inl reach, q, all⟩ + simp only [List.head?_cons, Option.some.injEq, exists_and_left, exists_eq_left'] + by_cases br : x < c.idx + · simp only [br, ite_true, Except.ok.injEq] at run + subst run + simp only [reduceCtorEq, false_and, exists_false, iff_false] + rw [accIff] + rintro ⟨⟨reach, q⟩, _⟩ + have := (hc t tL).mp (q reach) + omega + · simp only [br, ite_false] at run + rw [accIff] + have := agreementGo_go rest x _ r c.idx + (fun t => c.idx <= t /\ (c.idx <= t -> Q c t)) + (fun c' mem => hQ c' (List.mem_cons_of_mem _ mem)) (List.Pairwise.of_cons sorted) + (fun c' mem => pos c' (List.mem_cons_of_mem _ mem)) run rfl + (by + intro t tL + constructor + · rintro ⟨reach, q⟩ + exact ⟨reach, (hc t tL).mp (q reach)⟩ + · rintro ⟨reach, le⟩ + exact ⟨reach, fun _ => (hc t tL).mpr le⟩) + t tL + rw [this] + +end Agreement + +/-! ## The clean commit fold -/ + +section Fold + +/-- Commit indexes reachable from `ci` by steps `y` to `s` with `P y s`, within `L`. -/ +inductive Reach (P : Nat -> Nat -> Prop) (ci L : Nat) : Nat -> Prop + | base : Reach P ci L ci + | step {y s : Nat} : Reach P ci L y -> y < s -> s <= L -> P y s -> Reach P ci L s + +/-- No step leaves `c`. -/ +def Final (P : Nat -> Nat -> Prop) (L c : Nat) : Prop := + forall s, c < s -> s <= L -> Not (P c s) + +theorem Reach.ge {P : Nat -> Nat -> Prop} {ci L c : Nat} (h : Reach P ci L c) + : ci <= c := by + induction h with + | base => exact Nat.le_refl _ + | step _ ys _ _ ih => omega + +theorem Reach.le {P : Nat -> Nat -> Prop} {ci L c : Nat} (ciL : ci <= L) + (h : Reach P ci L c) + : c <= L := by + cases h with + | base => exact ciL + | step _ _ sL _ => exact sL + +/-- +When a step from `y` to `s` is also a step from any `c` between them, a reachable final +index is unique. +-/ +theorem reach_final_unique {P : Nat -> Nat -> Prop} {ci L : Nat} + (mono : forall y c s, y <= c -> c < s -> P y s -> P c s) {c1 c2 : Nat} + (r1 : Reach P ci L c1) (f1 : Final P L c1) (r2 : Reach P ci L c2) (f2 : Final P L c2) + : c1 = c2 := by + have below : forall {a b}, Reach P ci L a -> Final P L a -> Reach P ci L b -> Not (a < b) := by + intro a b ra fa rb + induction rb with + | base => + have := ra.ge + omega + | @step y s _ _ sL p ih => + intro lt + by_cases ya : y <= a + · exact fa s lt sL (mono y a s ya lt p) + · exact ih (by omega) + have := below r1 f1 r2 + have := below r2 f2 r1 + omega + +theorem foldl_reach {P : Nat -> Nat -> Prop} {ci L : Nat} (f : Nat -> Nat -> Nat) + (hf + : forall c s, (s > c /\ P c s -> f c s = s) /\ (Not (s > c /\ P c s) -> f c s = c)) + : forall (n k c : Nat), + k + n <= L + 1 + -> Reach P ci L c + -> (forall s, c < s -> s < k -> Not (P c s)) + -> Reach P ci L ((List.range' k n).foldl f c) + /\ forall s, + (List.range' k n).foldl f c < s + -> s < k + n + -> Not (P ((List.range' k n).foldl f c) s) + | 0, k, c, _, r, quiet => by simpa using And.intro r quiet + | n + 1, k, c, bound, r, quiet => by + rw [List.range'_succ, List.foldl_cons] + have ih := foldl_reach (P := P) (ci := ci) (L := L) f hf n (k + 1) (f c k) (by omega) + (by + by_cases go : k > c /\ P c k + · rw [(hf c k).1 go] + exact Reach.step r go.1 (by omega) go.2 + · rw [(hf c k).2 go] + exact r) + (by + intro s lt sk + by_cases go : k > c /\ P c k + · rw [(hf c k).1 go] at lt ⊢ + omega + · rw [(hf c k).2 go] at lt ⊢ + by_cases sk' : s < k + · exact quiet s lt sk' + · have : s = k := by omega + subst this + exact fun p => go ⟨lt, p⟩) + exact ⟨ih.1, fun s lt sk => ih.2 s lt (by omega)⟩ + +end Fold + +/-! ## Index-sorted lists -/ + +/-- In an index-sorted list, the positions within a bound are a prefix. -/ +theorem sorted_filter_prefix {α : Type} (idx : α -> Nat) + : forall {l : List α}, + l.Pairwise (fun a b => idx a < idx b) + -> forall (c i : Nat) (hi : i < l.length), + idx l[i] <= c <-> i < (l.filter fun a => decide (idx a <= c)).length + | [], _, _, _, hi => absurd hi (Nat.not_lt_zero _) + | x :: t, sorted, c, i, hi => by + have above : forall y, y ∈ t -> idx x < idx y := fun y mem => List.rel_of_pairwise_cons sorted mem + by_cases xc : idx x <= c + · rw [List.filter_cons_of_pos (by simpa using xc), List.length_cons] + cases i with + | zero => simpa using xc + | succ j => + simp only [List.getElem_cons_succ] + rw [sorted_filter_prefix idx (List.Pairwise.of_cons sorted) c j (by simpa using hi)] + omega + · rw [List.filter_cons_of_neg (by simpa using xc)] + have none : (t.filter fun a => decide (idx a <= c)) = [] := by + apply List.filter_eq_nil_iff.mpr + intro y mem + have := above y mem + simp only [decide_eq_true_eq] + omega + rw [none] + simp only [List.length_nil, Nat.not_lt_zero, iff_false] + cases i with + | zero => simpa using xc + | succ j => + simp only [List.getElem_cons_succ] + have := above _ (List.getElem_mem (l := t) (n := j) (by simpa using hi)) + omega + +/-! ## The clean step and its monotonicity -/ + +open Consensus.Model.Node + +/-- A step of the clean `highestCommittableIndex` fold from commit index `c` to `s`. -/ +def cleanP (state : NodeState) (self : NodeID) (c s : Nat) : Prop := + isSignatureAt state.log s = true + /\ termAt state.log s = state.currentTerm + /\ hasQuorum + ((activeConfigurations state.log c).filter + fun configuration => configuration.index <= s) + (state.activeMembers.filter fun node => node = self \/ state.matchIndex node >= s) + +theorem highestCommittableIndex_reach (state : NodeState) (self : NodeID) + : Reach (cleanP state self) state.commitIndex state.log.length + (highestCommittableIndex state self) + /\ Final (cleanP state self) state.log.length + (highestCommittableIndex state self) := by + unfold highestCommittableIndex + dsimp only + rw [List.range_eq_range'] + refine (fun this => ⟨this.1, fun s lt sL => this.2 s lt (by omega)⟩) + (foldl_reach + (P := cleanP state self) + (ci := state.commitIndex) + (L := state.log.length) + _ ?_ + (state.log.length + 1) + 0 state.commitIndex + (by omega) + .base + (by intro s _ lt; omega)) + intro c s + constructor + · intro h + unfold cleanP at h + split + · rfl + · contradiction + · intro h + unfold cleanP at h + split + · contradiction + · rfl + +theorem configurationHistory_sorted (log : List Entry) + : (configurationHistory log).Pairwise fun a b => a.index < b.index := by + have zipSorted : forall (l : List Entry) (start : Nat), + (l.zipIdx start).Pairwise fun a b => a.2 < b.2 := by + intro l + induction l with + | nil => simp + | cons head tail ih => + intro start + rw [List.zipIdx_cons, List.pairwise_cons] + exact ⟨fun pair member => (List.mem_zipIdx member).1, ih (start + 1)⟩ + unfold configurationHistory + refine List.Pairwise.filterMap _ (fun a b lt x xa y yb => ?_) (zipSorted log 1) + obtain ⟨_, _, rfl⟩ := Option.map_eq_some_iff.mp xa + obtain ⟨_, _, rfl⟩ := Option.map_eq_some_iff.mp yb + exact lt + +theorem activeConfigurations_mono (log : List Entry) {y c : Nat} (yc : y <= c) + : (forall x, x ∈ activeConfigurations log c -> x ∈ activeConfigurations log y) + /\ forall s, + c <= s + -> (exists x, x ∈ activeConfigurations log y /\ x.index <= s) + -> exists x, x ∈ activeConfigurations log c /\ x.index <= s := by + have eq : forall c, activeConfigurations log c + = (configurationHistory log).drop + (((configurationHistory log).filter fun x => decide (x.index <= c)).length - 1) := + fun _ => rfl + rw [eq c, eq y] + have sorted := configurationHistory_sorted log + generalize configurationHistory log = H at * + have ky : (H.filter fun x => decide (x.index <= y)).length + <= (H.filter fun x => decide (x.index <= c)).length := by + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro x _ h + simp only [decide_eq_true_eq] at h ⊢ + omega + refine ⟨fun x mem => ?_, fun s cs ex => ?_⟩ + · have : H.drop ((H.filter fun x => decide (x.index <= c)).length - 1) + = (H.drop ((H.filter fun x => decide (x.index <= y)).length - 1)).drop + ((H.filter fun x => decide (x.index <= c)).length - 1 + - ((H.filter fun x => decide (x.index <= y)).length - 1)) := by + rw [List.drop_drop] + congr 1 + omega + exact List.mem_of_mem_drop (this ▸ mem) + · by_cases kc : (H.filter fun x => decide (x.index <= c)).length = 0 + · have : (H.filter fun x => decide (x.index <= y)).length = 0 := by omega + rw [kc] + rw [this] at ex + exact ex + · have lt : (H.filter fun x => decide (x.index <= c)).length - 1 < H.length := by + have := List.length_filter_le (fun x => decide (x.index <= c)) H + omega + refine ⟨H[(H.filter fun x => decide (x.index <= c)).length - 1], ?_, ?_⟩ + · exact List.mem_iff_getElem.mpr ⟨0, by simp only [List.length_drop]; omega, by simp⟩ + · have := (sorted_filter_prefix Configuration.index sorted c _ lt).mpr (by omega) + omega + +theorem cleanP_mono (state : NodeState) (self : NodeID) + : forall y c s, + y <= c -> c < s -> cleanP state self y s -> cleanP state self c s := by + intro y c s yc cs ⟨sig, term, quorum⟩ + refine ⟨sig, term, ?_⟩ + obtain ⟨sub, ex⟩ := activeConfigurations_mono state.log yc + unfold hasQuorum at quorum ⊢ + obtain ⟨nonempty, all⟩ := quorum + obtain ⟨x, mem⟩ := List.exists_mem_of_ne_nil _ nonempty + rw [List.mem_filter] at mem + obtain ⟨x', mem', le'⟩ := ex s (by omega) ⟨x, mem.1, by simpa using mem.2⟩ + refine ⟨List.ne_nil_of_mem (List.mem_filter.mpr ⟨mem', by simpa using le'⟩), ?_⟩ + rw [List.all_eq_true] at all ⊢ + intro z memz + rw [List.mem_filter] at memz + exact all z (List.mem_filter.mpr ⟨sub z memz.1, memz.2⟩) + +/-! ## The declared ledger: entries, terms and committable indexes -/ + +section Declared + +open Consensus.TraceValidation (Names abs absEntry signaturesIn) + +/-- The declared ledger has a signature at one-based index `s`. -/ +abbrev SigAt (v : State) (s : Nat) : Prop := v.ledger[s - 1]?.any (·.sig) = true + +theorem abs_log_length {names : Names} {v : State} (size : v.ledger.size = v.lastIdx) + : (abs names v).log.length = v.lastIdx := by + simp [abs, size] + +theorem abs_entryAt {names : Names} {v : State} (size : v.ledger.size = v.lastIdx) + {s : Nat} (s1 : 1 <= s) (sL : s <= v.lastIdx) + : exists e, + v.ledger[s - 1]? = some e + /\ entryAt? (abs names v).log s = some (absEntry names e) := by + have lt : s - 1 < v.ledger.size := by omega + refine ⟨v.ledger[s - 1], by simp [lt], ?_⟩ + have ne : s ≠ 0 := by omega + simp [entryAt?, abs, ne, show s - 1 < v.lastIdx by omega, lt] + +theorem abs_isSignatureAt {names : Names} {v : State} (size : v.ledger.size = v.lastIdx) + {s : Nat} (s1 : 1 <= s) (sL : s <= v.lastIdx) + : isSignatureAt (abs names v).log s = true <-> SigAt v s := by + obtain ⟨e, he, entry⟩ := abs_entryAt (names := names) size s1 sL + unfold isSignatureAt SigAt + rw [entry, he] + cases hs : e.sig <;> simp [absEntry, hs, EntryContent.isSignature] + +theorem abs_termAt {names : Names} {v : State} (size : v.ledger.size = v.lastIdx) + {s : Nat} (s1 : 1 <= s) (sL : s <= v.lastIdx) + : exists e, v.ledger[s - 1]? = some e /\ termAt (abs names v).log s = e.term := by + obtain ⟨e, he, entry⟩ := abs_entryAt (names := names) size s1 sL + refine ⟨e, he, ?_⟩ + unfold termAt + rw [entry] + simp [absEntry] + +theorem isSignatureAt_zero (log : List Entry) : isSignatureAt log 0 = false := by + simp [isSignatureAt, entryAt?] + +theorem viewAt_mono (v : State) {i j : Nat} (ij : i <= j) : v.viewAt i <= v.viewAt j := by + unfold State.viewAt + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro x _ h + simp only [decide_eq_true_eq] at h ⊢ + omega + +theorem viewAt_le_size (v : State) (i : Nat) : v.viewAt i <= v.views.size := by + unfold State.viewAt + have := List.length_filter_le (fun x => decide (x <= i)) v.views.toList + simpa using this + +theorem sorted_getLast_max {l : List Nat} (sorted : l.Pairwise (· < ·)) {x : Nat} + (last : l.getLast? = some x) + : forall y, y ∈ l -> y <= x := by + obtain ⟨ys, rfl⟩ := List.getLast?_eq_some_iff.mp last + intro y mem + rcases List.mem_append.mp mem with mem | mem + · have := (List.pairwise_append.mp sorted).2.2 y mem x (List.mem_singleton_self _) + omega + · simp only [List.mem_singleton] at mem + omega + +theorem highestCommittableLe_none {v : State} + (committable : v.committable = signaturesIn v v.commitIdx v.lastIdx) {a : Nat} + (none_ : v.highestCommittableLe a = none) + : forall s, v.commitIdx < s -> s <= v.lastIdx -> s <= a -> Not (SigAt v s) := by + intro s lo hi sa sig + unfold State.highestCommittableLe at none_ + rw [committable, List.getLast?_eq_none_iff] at none_ + have : s ∈ ((signaturesIn v v.commitIdx v.lastIdx).filter fun i => decide (i <= a)) := by + simp only [signaturesIn, List.mem_filter, List.mem_range'_1, decide_eq_true_eq] + exact ⟨⟨⟨by omega, by omega⟩, sig⟩, sa⟩ + rw [none_] at this + cases this + +theorem highestCommittableLe_some {v : State} + (committable : v.committable = signaturesIn v v.commitIdx v.lastIdx) {a nc : Nat} + (some_ : v.highestCommittableLe a = some nc) + : v.commitIdx < nc + /\ nc <= v.lastIdx + /\ nc <= a + /\ SigAt v nc + /\ forall s, nc < s -> s <= v.lastIdx -> s <= a -> Not (SigAt v s) := by + unfold State.highestCommittableLe at some_ + rw [committable] at some_ + have sorted : ((signaturesIn v v.commitIdx v.lastIdx).filter fun i => decide (i <= a)).Pairwise + (· < ·) := by + unfold signaturesIn + exact ((List.pairwise_lt_range' (s := v.commitIdx + 1) (n := v.lastIdx - v.commitIdx)).filter _).filter _ + have mem : nc ∈ ((signaturesIn v v.commitIdx v.lastIdx).filter fun i => decide (i <= a)) := by + obtain ⟨ys, eq⟩ := List.getLast?_eq_some_iff.mp some_ + rw [eq] + exact List.mem_append_right _ (List.mem_singleton_self _) + have max := sorted_getLast_max sorted some_ + simp only [signaturesIn, List.mem_filter, List.mem_range'_1, decide_eq_true_eq] at mem + refine ⟨by omega, by omega, mem.2, mem.1.2, fun s lo hi sa sig => ?_⟩ + have := max s (by + simp only [signaturesIn, List.mem_filter, List.mem_range'_1, decide_eq_true_eq] + exact ⟨⟨⟨by omega, by omega⟩, sig⟩, sa⟩) + omega + +end Declared + +/-! ## Declared configurations and the clean active configurations -/ + +section Configs + +open Consensus.TraceValidation (Names abs) + +/-- The clean configuration a declared configuration stands for. -/ +def absConfig (names : Names) (c : Config) : Configuration := + { index := c.idx, nodes := names.set (c.nodes.map Prod.fst) } + +/-- +The position in `D` that `update_commit`'s `first` holds once the commit index is `c`: the +number of configurations after the first that `c` reaches. +-/ +def firstAt (D : List Config) (c : Nat) : Nat := + ((D.drop 1).filter fun x => decide (x.idx <= c)).length + +theorem filter_drop_length {α : Type} (idx : α -> Nat) + : forall {l : List α}, + l.Pairwise (fun a b => idx a < idx b) + -> forall (m c : Nat), + ((l.drop m).filter fun a => decide (idx a <= c)).length + = (l.filter fun a => decide (idx a <= c)).length - m + | [], _, m, c => by simp + | x :: t, _, 0, c => by simp + | x :: t, sorted, m + 1, c => by + rw [List.drop_succ_cons, filter_drop_length idx (List.Pairwise.of_cons sorted) m c] + by_cases xc : idx x <= c + · rw [List.filter_cons_of_pos (by simpa using xc), List.length_cons] + omega + · rw [List.filter_cons_of_neg (by simpa using xc)] + have : (t.filter fun a => decide (idx a <= c)) = [] := + List.filter_eq_nil_iff.mpr fun y mem => by + have := List.rel_of_pairwise_cons sorted mem + simp only [decide_eq_true_eq] + omega + rw [this] + simp + +theorem finset_eq_of_sort {s t : CCF.Finset NodeID} (h : s.sort = t.sort) : s = t := by + cases s + cases t + simp only [CCF.Finset.sort] at h + subst h + rfl + +theorem configs_of_map (names : Names) + : forall (D : List Config) (A : List Configuration), + D.map (fun c => (c.idx, (names.set (c.nodes.map Prod.fst)).sort)) + = A.map (fun c => (c.index, c.nodes.sort)) + -> A = D.map (absConfig names) + | [], [], _ => rfl + | [], _ :: _, h => by simp at h + | _ :: _, [], h => by simp at h + | x :: D, a :: A, h => by + simp only [List.map_cons, List.cons.injEq, Prod.mk.injEq] at h + obtain ⟨⟨hi, hn⟩, rest⟩ := h + rw [configs_of_map names D A rest] + congr 1 + cases a + simp only [absConfig] at hi hn ⊢ + rw [hi, finset_eq_of_sort hn] + +theorem configurationHistory_pos {log : List Entry} {x : Configuration} + (mem : x ∈ configurationHistory log) + : 0 < x.index := by + unfold configurationHistory at mem + obtain ⟨⟨e, i⟩, zmem, hx⟩ := List.mem_filterMap.mp mem + obtain ⟨_, _, rfl⟩ := Option.map_eq_some_iff.mp hx + have := (List.mem_zipIdx zmem).1 + simp only + omega + +theorem active_sorted (log : List Entry) (c : Nat) + : (activeConfigurations log c).Pairwise fun a b => a.index < b.index := + (configurationHistory_sorted log).sublist (List.drop_sublist _ _) + +theorem active_pos {log : List Entry} {c : Nat} {x : Configuration} + (mem : x ∈ activeConfigurations log c) + : 0 < x.index := + configurationHistory_pos (List.mem_of_mem_drop mem) + +theorem active_eq_drop (names : Names) (log : List Entry) {ci : Nat} {D : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) {c : Nat} (cic : ci <= c) + : activeConfigurations log c = (D.drop (firstAt D c)).map (absConfig names) := by + have eq : forall c, activeConfigurations log c + = (configurationHistory log).drop + (((configurationHistory log).filter fun x => decide (x.index <= c)).length - 1) := + fun _ => rfl + have g : firstAt D c + = (((activeConfigurations log ci).drop 1).filter fun x => decide (x.index <= c)).length := by + rw [hD] + unfold firstAt + rw [← List.map_drop, List.filter_map, List.length_map] + rfl + rw [List.map_drop, ← hD, g, eq c, eq ci] + have sorted := configurationHistory_sorted log + generalize configurationHistory log = H at * + simp only [List.drop_drop] + rw [filter_drop_length Configuration.index sorted] + have mono : (H.filter fun x => decide (x.index <= ci)).length + <= (H.filter fun x => decide (x.index <= c)).length := by + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro x _ h + simp only [decide_eq_true_eq] at h ⊢ + omega + congr 1 + omega + +theorem firstAt_self (names : Names) (log : List Entry) {ci : Nat} {D : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) + : firstAt D ci = 0 := by + have := active_eq_drop names log hD (Nat.le_refl ci) + have g : firstAt D ci + = (((D.map (absConfig names)).drop 1).filter fun x => decide (x.index <= ci)).length := by + unfold firstAt + rw [← List.map_drop, List.filter_map, List.length_map] + rfl + rw [g, ← hD] + unfold activeConfigurations + dsimp only + have sorted := configurationHistory_sorted log + generalize configurationHistory log = H at * + rw [List.drop_drop, filter_drop_length Configuration.index sorted] + omega + +theorem declared_sorted {names : Names} {log : List Entry} {ci : Nat} {D : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) + : D.Pairwise fun a b => a.idx < b.idx := by + have := active_sorted log ci + rw [hD, List.pairwise_map] at this + exact this + +theorem declared_pos {names : Names} {log : List Entry} {ci : Nat} {D : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) {x : Config} + (mem : x ∈ D) + : 0 < x.idx := by + have := active_pos (log := log) (c := ci) (x := absConfig names x) + (by rw [hD]; exact List.mem_map_of_mem mem) + simpa [absConfig] using this + +theorem step_iff {D : List Config} (sorted : D.Pairwise fun a b => a.idx < b.idx) + (i j : Nat) + : (D[j + 1]?.any fun x => decide (x.idx <= i)) = true <-> j < firstAt D i := by + unfold firstAt + by_cases hj : j < (D.drop 1).length + · have := sorted_filter_prefix Config.idx (sorted.sublist (List.drop_sublist 1 D)) i j hj + rw [← this] + have e : D[j + 1]? = (D.drop 1)[j]? := by + rw [List.getElem?_drop, Nat.add_comm] + rw [List.getElem?_eq_getElem hj] at e + rw [e] + simp + · have none_ : D[j + 1]? = none := by + apply List.getElem?_eq_none + simp only [List.length_drop] at hj + omega + rw [none_] + have := List.length_filter_le (fun x : Config => decide (x.idx <= i)) (D.drop 1) + simp only [Option.any_none, Bool.false_eq_true, false_iff] + omega + +theorem advanceFirst_eq {D : List Config} (sorted : D.Pairwise fun a b => a.idx < b.idx) + (i : Nat) + : forall fuel first, + first <= firstAt D i + -> firstAt D i - first <= fuel + -> Exec.advanceFirst D i first fuel = firstAt D i + | 0, first, le, fuel => by + simp only [Exec.advanceFirst] + omega + | fuel + 1, first, le, enough => by + simp only [Exec.advanceFirst] + split + · rename_i go + have := (step_iff sorted i first).mp go + exact advanceFirst_eq sorted i fuel (first + 1) (by omega) (by omega) + · rename_i go + have := mt (step_iff sorted i first).mpr go + omega + +theorem firstAt_le_length (D : List Config) (c : Nat) : firstAt D c <= D.length := by + unfold firstAt + have := List.length_filter_le (fun x : Config => decide (x.idx <= c)) (D.drop 1) + simp only [List.length_drop] at this + omega + +theorem mem_configurationMembers {cs : List Configuration} {x : Configuration} + {n : NodeID} (mem : x ∈ cs) (member : n ∈ x.nodes) + : n ∈ configurationMembers cs := by + unfold configurationMembers + have general : forall (cs : List Configuration) (acc : CCF.Finset NodeID), + (n ∈ acc \/ exists x, x ∈ cs /\ n ∈ x.nodes) + -> n ∈ cs.foldl (fun nodes configuration => nodes ∪ configuration.nodes) acc := by + intro cs + induction cs with + | nil => + intro acc h + rcases h with h | ⟨_, mem, _⟩ + · exact h + · cases mem + | cons y ys ih => + intro acc h + apply ih + rcases h with h | ⟨z, mem, inZ⟩ + · exact Or.inl (CCF.Finset.mem_union.mpr (Or.inl h)) + · rcases List.mem_cons.mp mem with rfl | mem + · exact Or.inl (CCF.Finset.mem_union.mpr (Or.inr inZ)) + · exact Or.inr ⟨z, mem, inZ⟩ + exact general cs ∅ (Or.inr ⟨x, mem, member⟩) + +/-- +`E` is `D` except that its first configuration may sit at a later index, both at or below +`ci`: a joiner's snapshot configuration (`inv`'s `configurations`). +-/ +def Shifted (ci : Nat) (D E : List Config) : Prop := + D = E + \/ exists x y rest, + D = x :: rest /\ E = y :: rest /\ x.nodes = y.nodes /\ x.idx <= y.idx /\ y.idx <= ci + +/-- The clean active configurations after the first are above the commit index. -/ +theorem active_tail_above (names : Names) (log : List Entry) {ci : Nat} {D : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) + : forall x, x ∈ D.drop 1 -> ci < x.idx := by + have zero := firstAt_self names log hD + unfold firstAt at zero + intro x mem + have := List.filter_eq_nil_iff.mp (List.eq_nil_of_length_eq_zero zero) x mem + simp only [decide_eq_true_eq] at this + omega + +theorem shifted_sorted {names : Names} {log : List Entry} {ci : Nat} {D E : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) (sh : Shifted ci D E) + : E.Pairwise fun a b => a.idx < b.idx := by + have sorted := declared_sorted hD + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, _, _, yc⟩ + · exact sorted + · have above := active_tail_above names log hD + simp only [List.drop_succ_cons, List.drop_zero] at above + refine List.pairwise_cons.mpr ⟨fun z mem => ?_, (List.pairwise_cons.mp sorted).2⟩ + have := above z mem + omega + +theorem shifted_pos {names : Names} {log : List Entry} {ci : Nat} {D E : List Config} + (hD : activeConfigurations log ci = D.map (absConfig names)) (sh : Shifted ci D E) + {x : Config} (mem : x ∈ E) + : 0 < x.idx := by + rcases sh with rfl | ⟨x', y, rest, rfl, rfl, _, xy, _⟩ + · exact declared_pos hD mem + · rcases List.mem_cons.mp mem with rfl | mem + · have := declared_pos hD List.mem_cons_self + omega + · exact declared_pos hD (List.mem_cons_of_mem _ mem) + +theorem shifted_firstAt {ci : Nat} {D E : List Config} (sh : Shifted ci D E) (c : Nat) + : firstAt E c = firstAt D c := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, _⟩ + · rfl + · rfl + +theorem shifted_mem {ci : Nat} {D E : List Config} (sh : Shifted ci D E) {y : Config} + (mem : y ∈ E) + : exists x, x ∈ D /\ x.nodes = y.nodes := by + rcases sh with rfl | ⟨x, y', rest, rfl, rfl, nodes, _⟩ + · exact ⟨y, mem, rfl⟩ + · rcases List.mem_cons.mp mem with rfl | mem + · exact ⟨x, List.mem_cons_self, nodes⟩ + · exact ⟨y, List.mem_cons_of_mem _ mem, rfl⟩ + +/-- Above `ci`, a shifted list of configurations has the same majorities. -/ +theorem shifted_acc {ci : Nat} {D E : List Config} (sh : Shifted ci D E) + {Q : Config -> Nat -> Prop} {t : Nat} + (same : forall x y, x.nodes = y.nodes -> (Q x t <-> Q y t)) (above : ci < t) (k : Nat) + : Acc Q (E.drop k) t <-> Acc Q (D.drop k) t := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, nodes, xy, yc⟩ + · exact Iff.rfl + · cases k with + | succ k => exact Iff.rfl + | zero => + simp only [List.drop_zero, Acc, AllReach, List.mem_cons, exists_eq_or_imp, + forall_eq_or_imp] + have q := same x y nodes + constructor + · rintro ⟨_, qy, all⟩ + exact ⟨Or.inl (by omega), fun _ => q.mpr (qy (by omega)), all⟩ + · rintro ⟨_, qx, all⟩ + exact ⟨Or.inl (by omega), fun _ => q.mp (qx (by omega)), all⟩ + +end Configs + +/-! ## Names, peers and the majority of one configuration -/ + +section Majority + +open Consensus.TraceValidation (Names abs) + +/-- An id that round-trips through the name table. -/ +abbrev Named (names : Names) (id : Exec.NodeId) : Prop := names.name (names.id id) = id + +theorem named_inj {names : Names} {x y : Exec.NodeId} (hx : Named names x) + (hy : Named names y) (same : names.id x = names.id y) + : x = y := by + rw [← hx, ← hy, same] + +theorem mapM_ok_nat {α : Type} {f : α -> Except String Nat} + : forall {l : List α} {ms : List Nat}, + l.mapM f = .ok ms + -> (forall a, a ∈ l -> exists b, f a = .ok b) + /\ ms = l.map fun a => (f a).toOption.getD 0 + | [], ms, h => by + simp only [List.mapM_nil, Pure.pure, Except.pure, Except.ok.injEq] at h + subst h + simp + | a :: l, ms, h => by + simp only [List.mapM_cons, Bind.bind, Except.bind, Pure.pure, Except.pure] at h + cases fa : f a with + | error e => simp [fa] at h + | ok b => + rw [fa] at h + cases fl : l.mapM f with + | error e => simp [fl] at h + | ok bs => + rw [fl] at h + simp only [Except.ok.injEq] at h + subst h + obtain ⟨all, eq⟩ := mapM_ok_nat fl + refine ⟨?_, ?_⟩ + · intro x mem + rcases List.mem_cons.mp mem with rfl | mem + · exact ⟨b, fa⟩ + · exact all x mem + · simp [fa, eq, Except.toOption] + +/-- The clean match index of a peer is its declared one. -/ +theorem abs_matchIndex {names : Names} {v : State} + (peersNamed : forall p, p ∈ v.allOtherNodes -> Named names p.1) {id : Exec.NodeId} + (named : Named names id) {p : Exec.Peer} (found : v.peer? id = some p) + : (abs names v).matchIndex (names.id id) = p.matchIdx := by + simp only [abs] + unfold State.peer? at found + generalize v.allOtherNodes = l at peersNamed found + induction l with + | nil => simp at found + | cons q l ih => + obtain ⟨k, pk⟩ := q + by_cases same : id = k + · subst same + simp only [List.lookup_cons, beq_self_eq_true, Option.some.injEq] at found + subst found + simp + · have ne : (names.id k == names.id id) = false := by + simp only [beq_eq_false_iff_ne] + intro eq + exact same (named_inj named (peersNamed (k, pk) (by simp)) eq.symm) + have ne' : (id == k) = false := by simpa using same + simp only [List.lookup_cons, ne'] at found + simp only [List.find?_cons, ne] + exact ih (fun p mem => peersNamed p (List.mem_cons_of_mem _ mem)) found + +/-- +A configuration's clean majority at index `t` (the members that are the leader or have +matched `t`) exists exactly when `t` is at most its declared confirmed index. +-/ +theorem majority_iff {names : Names} {v : State} (selfNamed : Named names v.nodeId) + (peersNamed : forall p, p ∈ v.allOtherNodes -> Named names p.1) {x : Config} + (membersNamed : forall a, a ∈ x.nodes -> Named names a.1) + (distinct : (x.nodes.map Prod.fst).Nodup) + (active : forall n, n ∈ (absConfig names x).nodes -> n ∈ (abs names v).activeMembers) + {m : Nat} (confirmed : Exec.confirmedIdx v x = .ok m) {t : Nat} (tL : t <= v.lastIdx) + : hasConfigurationMajority + ((abs names v).activeMembers.filter + fun n => n = names.id v.nodeId \/ (abs names v).matchIndex n >= t) + (absConfig names x) + <-> t <= m := by + unfold Exec.confirmedIdx at confirmed + cases hm : Exec.matchIdxs v x with + | error e => simp [hm, Bind.bind, Except.bind] at confirmed + | ok ms => + simp only [hm, Bind.bind, Except.bind] at confirmed + split at confirmed + · rename_i x' median + simp only [Except.ok.injEq] at confirmed + subst confirmed + obtain ⟨all, eq⟩ := mapM_ok_nat hm + have med := median_iff median t + rw [← med, eq, List.countP_map, List.length_map] + have nodupIds : ((x.nodes.map Prod.fst).map names.id).Nodup := by + unfold List.Nodup + rw [List.pairwise_map] + refine List.Pairwise.imp_of_mem ?_ distinct + intro a b ma mb ne same + obtain ⟨a', ma', rfl⟩ := List.mem_map.mp ma + obtain ⟨b', mb', rfl⟩ := List.mem_map.mp mb + exact ne (named_inj (membersNamed a' ma') (membersNamed b' mb') same) + unfold hasConfigurationMajority absConfig Names.set + dsimp only + rw [CCF.Finset.card_ofList_of_nodup nodupIds, List.length_map, List.length_map] + let P : NodeID -> Bool := + fun n => decide (n = names.id v.nodeId \/ (abs names v).matchIndex n >= t) + have card : (((abs names v).activeMembers.filter + fun n => n = names.id v.nodeId \/ (abs names v).matchIndex n >= t) + ∩ CCF.Finset.ofList ((x.nodes.map Prod.fst).map names.id)).card + = (((x.nodes.map Prod.fst).map names.id).filter P).length := by + apply CCF.Finset.length_eq_of_nodup_of_mem_iff + (CCF.Finset.nodup_of_sorted (CCF.Finset.sorted _)) (List.Pairwise.filter _ nodupIds) + intro n + rw [← CCF.Finset.mem_def, CCF.Finset.mem_inter, CCF.Finset.mem_filter, + CCF.Finset.mem_ofList, List.mem_filter] + constructor + · rintro ⟨⟨_, p⟩, mem⟩ + exact ⟨mem, by simpa [P] using p⟩ + · rintro ⟨mem, p⟩ + refine ⟨⟨active n ?_, by simpa [P] using p⟩, mem⟩ + simpa [absConfig, Names.set] using mem + rw [card, ← List.countP_eq_length_filter, List.countP_map, List.countP_map] + apply Iff.of_eq + congr 2 + apply List.countP_congr + intro a mem + obtain ⟨b, fb⟩ := all a mem + obtain ⟨id, tag⟩ := a + simp only [Function.comp_apply, fb, Except.toOption, Option.getD_some, P, + decide_eq_true_eq] + simp only at fb + split at fb + · rename_i isSelf + simp only [Except.ok.injEq] at fb + subst fb + simp only [beq_iff_eq] at isSelf + subst isSelf + simp only [true_or, true_iff] + exact tL + · rename_i notSelf + simp only [beq_iff_eq] at notSelf + have named := membersNamed (id, tag) mem + have ne : names.id id ≠ names.id v.nodeId := + fun same => notSelf (named_inj named selfNamed same) + split at fb + · rename_i p found + simp only [Except.ok.injEq] at fb + subst fb + rw [abs_matchIndex peersNamed named found] + simp [ne] + · cases fb + · simp at confirmed + +end Majority + +/-! ## One round of `highest_committable_idx` against the clean fold -/ + +section Round + +open Consensus.TraceValidation (Names abs signaturesIn) + +/-- What `update_commit` needs of the declared state; `Hyps.ofInv` derives it from `inv`. -/ +structure Hyps (names : Names) (v : State) : Prop where + size : v.ledger.size = v.lastIdx + commitLe : v.commitIdx <= v.lastIdx + committable : v.committable = signaturesIn v v.commitIdx v.lastIdx + terms + : forall i, + 1 <= i -> i <= v.lastIdx -> v.ledger[i - 1]?.map (·.term) = some (v.viewAt i) + viewsBounded : v.views.size <= v.currentView + configs + : 0 < v.lastIdx + -> exists D, + activeConfigurations (abs names v).log v.commitIdx = D.map (absConfig names) + /\ Shifted v.commitIdx D v.configurations + selfNamed : Named names v.nodeId + peersNamed : forall p, p ∈ v.allOtherNodes -> Named names p.1 + membersNamed + : forall x, x ∈ v.configurations -> forall a, a ∈ x.nodes -> Named names a.1 + distinct : forall x, x ∈ v.configurations -> (x.nodes.map Prod.fst).Nodup + +/-- The clean majority of a declared configuration at index `t`. -/ +def Qd (names : Names) (v : State) (x : Config) (t : Nat) : Prop := + hasConfigurationMajority + ((abs names v).activeMembers.filter + fun n => n = names.id v.nodeId \/ (abs names v).matchIndex n >= t) + (absConfig names x) + +variable {names : Names} {v : State} + +theorem Hyps.hQ (h : Hyps names v) (L0 : 0 < v.lastIdx) (K : List Config) + (sub : forall x, x ∈ K -> x ∈ v.configurations) + : forall x, + x ∈ K + -> forall m, + Exec.confirmedIdx v x = .ok m + -> forall t, t <= v.lastIdx -> (Qd names v x t <-> t <= m) := by + intro x mem m confirmed t tL + have memD := sub x mem + apply majority_iff h.selfNamed h.peersNamed (h.membersNamed x memD) (h.distinct x memD) + _ confirmed tL + intro n member + show n ∈ configurationMembers (activeConfigurations (abs names v).log v.commitIdx) + obtain ⟨D, hD, sh⟩ := h.configs L0 + obtain ⟨x', memD', nodes⟩ := shifted_mem sh memD + rw [hD] + exact mem_configurationMembers (List.mem_map_of_mem memD') + (by simpa [absConfig, nodes] using member) + +theorem Hyps.sorted (h : Hyps names v) (L0 : 0 < v.lastIdx) + : v.configurations.Pairwise fun a b => a.idx < b.idx := by + obtain ⟨_, hD, sh⟩ := h.configs L0 + exact shifted_sorted hD sh + +theorem Hyps.pos (h : Hyps names v) (L0 : 0 < v.lastIdx) {x : Config} + (mem : x ∈ v.configurations) + : 0 < x.idx := by + obtain ⟨_, hD, sh⟩ := h.configs L0 + exact shifted_pos hD sh mem + +theorem Hyps.firstAt_self (h : Hyps names v) (L0 : 0 < v.lastIdx) + : firstAt v.configurations v.commitIdx = 0 := by + obtain ⟨_, hD, sh⟩ := h.configs L0 + rw [shifted_firstAt sh] + exact ReplUpdateCommit.firstAt_self names _ hD + +theorem cleanP_iff (h : Hyps names v) (L0 : 0 < v.lastIdx) {c s : Nat} + (cic : v.commitIdx <= c) (cs : c < s) (sL : s <= v.lastIdx) + : cleanP (abs names v) (names.id v.nodeId) c s + <-> SigAt v s + /\ v.viewAt s = v.currentView + /\ Acc (Qd names v) (v.configurations.drop (firstAt v.configurations c)) s := by + have s1 : 1 <= s := by omega + obtain ⟨D, hD, sh⟩ := h.configs L0 + rw [shifted_firstAt sh, shifted_acc (Q := Qd names v) (t := s) sh + (fun x y nodes => by simp [Qd, absConfig, hasConfigurationMajority, nodes]) (by omega)] + unfold cleanP + rw [abs_isSignatureAt h.size s1 sL] + obtain ⟨e, he, ht⟩ := abs_termAt (names := names) h.size s1 sL + rw [ht] + have te := h.terms s s1 sL + rw [he] at te + simp only [Option.map_some, Option.some.injEq] at te + rw [te] + have cur : (abs names v).currentTerm = v.currentView := rfl + rw [cur, active_eq_drop names _ hD cic] + apply and_congr Iff.rfl + apply and_congr Iff.rfl + unfold hasQuorum Acc AllReach + constructor + · rintro ⟨ne, all⟩ + obtain ⟨y, memy⟩ := List.exists_mem_of_ne_nil _ ne + simp only [List.mem_filter, List.mem_map, decide_eq_true_eq] at memy + obtain ⟨⟨x, memx, rfl⟩, le⟩ := memy + refine ⟨⟨x, memx, by simpa [absConfig] using le⟩, ?_⟩ + intro z memz le' + rw [List.all_eq_true] at all + have := all (absConfig names z) + (List.mem_filter.mpr ⟨List.mem_map_of_mem memz, by simp [absConfig, le']⟩) + simpa [Qd] using this + · rintro ⟨⟨x, memx, le⟩, all⟩ + refine ⟨List.ne_nil_of_mem (a := absConfig names x) + (List.mem_filter.mpr ⟨List.mem_map_of_mem memx, by simp [absConfig, le]⟩), ?_⟩ + rw [List.all_eq_true] + intro y memy + simp only [List.mem_filter, List.mem_map, decide_eq_true_eq] at memy + obtain ⟨⟨z, memz, rfl⟩, le'⟩ := memy + have := all z memz (by simpa [absConfig] using le') + simpa [Qd] using this + +theorem round (h : Hyps names v) (L0 : 0 < v.lastIdx) {c : Nat} (cic : v.commitIdx <= c) + {r : Option Nat} + (run : Exec.highestCommittableIdxOf v (firstAt v.configurations c) = .ok r) + : (r = none -> Final (cleanP (abs names v) (names.id v.nodeId)) v.lastIdx c) + /\ forall i, + r = some i + -> v.commitIdx < i + /\ i <= v.lastIdx + /\ (forall s, + i < s + -> c < s + -> s <= v.lastIdx + -> Not (cleanP (abs names v) (names.id v.nodeId) c s)) + /\ (c < i -> cleanP (abs names v) (names.id v.nodeId) c i) := by + have sortedK := (h.sorted L0).sublist + (List.drop_sublist (firstAt v.configurations c) v.configurations) + have subK : forall x, x ∈ v.configurations.drop (firstAt v.configurations c) + -> x ∈ v.configurations := fun x m => List.mem_of_mem_drop m + have stepOf : forall s, c < s -> s <= v.lastIdx + -> cleanP (abs names v) (names.id v.nodeId) c s + -> SigAt v s /\ v.viewAt s = v.currentView + /\ Acc (Qd names v) (v.configurations.drop (firstAt v.configurations c)) s := + fun s cs sL p => (cleanP_iff h L0 cic cs sL).mp p + have stepTo : forall s, c < s -> s <= v.lastIdx + -> SigAt v s /\ v.viewAt s = v.currentView + /\ Acc (Qd names v) (v.configurations.drop (firstAt v.configurations c)) s + -> cleanP (abs names v) (names.id v.nodeId) c s := + fun s cs sL p => (cleanP_iff h L0 cic cs sL).mpr p + unfold Exec.highestCommittableIdxOf at run + generalize v.configurations.drop (firstAt v.configurations c) = K + at run sortedK subK stepOf stepTo + cases hag : Exec.agreementGo v none K none with + | error e => simp [hag, bind, Except.bind] at run + | ok r' => + have spec := agreementGo_spec (h.hQ L0 K subK) sortedK + (fun x m => h.pos L0 (subK x m)) hag + simp only [hag, bind, Except.bind] at run + have bound : forall s, c < s -> s <= v.lastIdx + -> cleanP (abs names v) (names.id v.nodeId) c s + -> SigAt v s /\ v.viewAt s = v.currentView + /\ exists a c0, r' = some a /\ K.head? = some c0 /\ c0.idx <= s /\ s <= a := by + intro s cs sL p + obtain ⟨sig, view, acc⟩ := stepOf s cs sL p + exact ⟨sig, view, (spec s sL).mp acc⟩ + cases r' with + | none => + simp only [pure, Except.pure, Except.ok.injEq] at run + subst run + refine ⟨fun _ s cs sL p => ?_, fun i no => by cases no⟩ + obtain ⟨_, _, a, c0, no, _⟩ := bound s cs sL p + cases no + | some ag => + have headK : exists c0, K.head? = some c0 := by + cases K with + | nil => simp [Exec.agreementGo] at hag + | cons c0 _ => exact ⟨c0, rfl⟩ + obtain ⟨c0, head⟩ := headK + simp only [head, Option.map_some, Option.getD_some] at run + by_cases big : ag > v.lastIdx + · simp [big, throw, throwThe, MonadExceptOf.throw] at run + simp only [big, ite_false] at run + cases hnc : v.highestCommittableLe ag with + | none => + simp only [hnc, pure, Except.pure, Except.ok.injEq] at run + subst run + refine ⟨fun _ s cs sL p => ?_, fun i no => by cases no⟩ + obtain ⟨sig, _, a, c1, same, _, _, sa⟩ := bound s cs sL p + cases same + exact highestCommittableLe_none h.committable hnc s (by omega) sL sa sig + | some nc => + obtain ⟨lo, hi, le, sigNc, above⟩ := + highestCommittableLe_some h.committable hnc + have below : forall s, c < s -> s <= v.lastIdx + -> cleanP (abs names v) (names.id v.nodeId) c s + -> SigAt v s /\ v.viewAt s = v.currentView /\ c0.idx <= s /\ s <= nc := by + intro s cs sL p + obtain ⟨sig, view, a, c1, same, head', le0, sa⟩ := bound s cs sL p + cases same + rw [head] at head' + cases head' + refine ⟨sig, view, le0, ?_⟩ + apply Classical.byContradiction + intro gt + exact above s (by omega) sL sa sig + have getTerm : v.getTerm nc = v.viewAt nc := by + unfold State.getTerm + split + · omega + · rfl + simp only [hnc] at run + by_cases early : nc < c0.idx + · simp only [early, ite_true, pure, Except.pure, Except.ok.injEq] at run + subst run + refine ⟨fun _ s cs sL p => ?_, fun i no => by cases no⟩ + have := below s cs sL p + omega + simp only [early, ite_false] at run + by_cases term : (v.getTerm nc != v.currentView) = true + · simp only [term, ite_true, pure, Except.pure, Except.ok.injEq] at run + subst run + refine ⟨fun _ s cs sL p => ?_, fun i no => by cases no⟩ + obtain ⟨_, view, _, snc⟩ := below s cs sL p + have m1 := viewAt_mono v snc + have m2 := viewAt_le_size v nc + have := h.viewsBounded + simp only [bne_iff_ne, ne_eq, getTerm] at term + omega + simp only [term, Bool.false_eq_true, ite_false, pure, Except.pure, Except.ok.injEq] at run + subst run + simp only [bne_iff_ne, ne_eq, getTerm, Decidable.not_not] at term + refine ⟨(fun no => by cases no), fun i same => ?_⟩ + cases same + refine ⟨lo, hi, fun s gt cs sL p => ?_, fun cnc => ?_⟩ + · have := below s cs sL p + omega + · apply stepTo nc (by omega) hi + refine ⟨sigNc, term, (spec nc hi).mpr ⟨ag, c0, rfl, head, by omega, le⟩⟩ + +end Round + +/-! ## The loop of `update_commit` -/ + +section Loop + +open Consensus.TraceValidation (Names abs signaturesIn) + +/-- `update_commit`'s outer loop as a function of the (unchanging) declared state. -/ +def updateCommitOf (v : State) (first : Nat) (newCommit : Option Nat) + : Nat -> Except String (Option Nat) + | 0 => .error "update_commit does not terminate" + | fuel + 1 => + match Exec.highestCommittableIdxOf v first with + | .error e => .error e + | .ok none => .ok newCommit + | .ok (some i) => + if newCommit.any (i <= ·) then + .ok newCommit + else + updateCommitOf v + (Exec.advanceFirst v.configurations i first v.configurations.length) + (some i) fuel + +variable {names : Names} {v : State} + +theorem firstAt_mono (D : List Config) {c i : Nat} (ci : c <= i) + : firstAt D c <= firstAt D i := by + unfold firstAt + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro x _ h + simp only [decide_eq_true_eq] at h ⊢ + omega + +theorem updateCommitOf_reach (h : Hyps names v) (L0 : 0 < v.lastIdx) + : forall fuel c newCommit r, + c = newCommit.getD v.commitIdx + -> v.commitIdx <= c + -> Reach (cleanP (abs names v) (names.id v.nodeId)) v.commitIdx v.lastIdx c + -> updateCommitOf v (firstAt v.configurations c) newCommit fuel = .ok r + -> Reach (cleanP (abs names v) (names.id v.nodeId)) v.commitIdx v.lastIdx + (r.getD v.commitIdx) + /\ Final (cleanP (abs names v) (names.id v.nodeId)) v.lastIdx + (r.getD v.commitIdx) + | 0, _, _, _, _, _, _, run => by simp [updateCommitOf] at run + | fuel + 1, c, newCommit, r, hc, cic, reach, run => by + simp only [updateCommitOf] at run + split at run + · cases run + · rename_i found + cases run + rw [← hc] + exact ⟨reach, (round h L0 cic found).1 rfl⟩ + · rename_i i found + obtain ⟨lo, hi, quiet, step⟩ := (round h L0 cic found).2 i rfl + split at run + · rename_i stop + cases run + rw [← hc] + refine ⟨reach, fun s cs sL p => ?_⟩ + cases newCommit with + | none => simp at stop + | some n => + simp only [Option.any_some, decide_eq_true_eq] at stop + simp only [Option.getD_some] at hc + exact quiet s (by omega) cs sL p + · rename_i go + have ci : c < i := by + cases newCommit with + | none => + simp only [Option.getD_none] at hc + omega + | some n => + simp only [Option.any_some, decide_eq_true_eq] at go + simp only [Option.getD_some] at hc + omega + have next := Reach.step reach ci hi (step ci) + rw [advanceFirst_eq (h.sorted L0) i _ _ (firstAt_mono _ (by omega)) + (by have := firstAt_le_length v.configurations i; omega)] at run + exact updateCommitOf_reach h L0 fuel i (some i) r rfl (by omega) next run + +theorem highestCommittableIdxOf_empty + (committable : v.committable = signaturesIn v v.commitIdx v.lastIdx) + (L0 : v.lastIdx = 0) {first : Nat} {r : Option Nat} + (run : Exec.highestCommittableIdxOf v first = .ok r) + : r = none := by + have none_ : forall a, v.highestCommittableLe a = none := by + intro a + have : v.committable = [] := by + rw [committable] + simp [signaturesIn, L0] + simp [State.highestCommittableLe, this] + unfold Exec.highestCommittableIdxOf at run + simp only [bind, Except.bind] at run + split at run + · cases run + · rename_i r' _ + cases r' with + | none => + simp only [pure, Except.pure, Except.ok.injEq] at run + exact run.symm + | some a => + simp only [none_] at run + by_cases big : a > v.lastIdx + · simp [big, throw, throwThe, MonadExceptOf.throw] at run + · simp only [big, ite_false, pure, Except.pure, Except.ok.injEq] at run + exact run.symm + +/-- +`update_commit` chooses the clean `highestCommittableIndex`: when its loop returns `r`, the +clean fold from the declared state ends at `r`, or at the commit index when `r` is `none`. +-/ +theorem updateCommit_eq (h : Hyps names v) {fuel : Nat} {r : Option Nat} + (run : updateCommitOf v 0 none fuel = .ok r) + : highestCommittableIndex (abs names v) (names.id v.nodeId) = r.getD v.commitIdx := by + obtain ⟨cleanReach, cleanFinal⟩ := highestCommittableIndex_reach (abs names v) (names.id v.nodeId) + have len : (abs names v).log.length = v.lastIdx := abs_log_length h.size + have ci : (abs names v).commitIndex = v.commitIdx := rfl + rw [len, ci] at cleanReach + rw [len] at cleanFinal + by_cases L0 : v.lastIdx = 0 + · have : r = none := by + cases fuel with + | zero => simp [updateCommitOf] at run + | succ fuel => + simp only [updateCommitOf] at run + split at run + · cases run + · cases run + rfl + · rename_i i found + cases highestCommittableIdxOf_empty h.committable L0 found + subst this + have := cleanReach.ge + have := cleanReach.le h.commitLe + simp only [Option.getD_none] + omega + · have L0 : 0 < v.lastIdx := by omega + have first : firstAt v.configurations v.commitIdx = 0 := h.firstAt_self L0 + rw [← first] at run + obtain ⟨r1, f1⟩ := updateCommitOf_reach h L0 fuel v.commitIdx none r rfl (Nat.le_refl _) + .base run + exact reach_final_unique (cleanP_mono _ _) cleanReach cleanFinal r1 f1 + +end Loop + +/-! ## The monadic loop -/ + +section Monadic + +open Consensus.TraceValidation.Proofs (Spec) + +theorem liftE_spec {env : Consensus.TraceValidation.Env} {α : Type} (x : Except String α) + : Spec env (Exec.liftE x) fun v o a v' o' => x = .ok a /\ v' = v /\ o' = o := by + unfold Exec.liftE + split + · refine Spec.weaken (Spec.pure _) ?_ + rintro _ _ _ _ _ ⟨rfl, rfl, rfl⟩ + exact ⟨rfl, rfl, rfl⟩ + · refine Spec.weaken + (Spec.bind Spec.curLoc fun _ => Spec.fail (P := fun _ _ _ _ _ => False) _) ?_ + rintro _ _ _ _ _ ⟨_, _, _, _, f⟩ + exact f.elim + +/-- The monadic loop computes `updateCommitOf` and changes neither state nor outbox. -/ +theorem updateCommitGo_spec {env : Consensus.TraceValidation.Env} + : forall fuel first newCommit, + Spec env (Exec.updateCommitGo first newCommit fuel) + fun v o r v' o' => + v' = v /\ o' = o /\ updateCommitOf v first newCommit fuel = .ok r + | 0, first, newCommit => by + simp only [Exec.updateCommitGo] + exact Spec.fail _ + | fuel + 1, first, newCommit => by + simp only [Exec.updateCommitGo, Exec.highestCommittableIdx] + refine Spec.weaken + (Spec.bind (Spec.bind Spec.getV fun v => liftE_spec _) + (Q := fun r v o res v' o' => + v' = v /\ o' = o + /\ match r with + | none => res = newCommit + | some i => + if (newCommit.any fun x => decide (i <= x)) = true then res = newCommit + else + updateCommitOf v + (Exec.advanceFirst v.configurations i first v.configurations.length) + (some i) fuel + = .ok res) + fun r => ?_) ?_ + · cases r with + | none => + refine Spec.weaken (Spec.pure _) ?_ + rintro _ _ _ _ _ ⟨rfl, rfl, rfl⟩ + exact ⟨rfl, rfl, rfl⟩ + | some i => + dsimp only + by_cases b : (newCommit.any fun x => decide (i <= x)) = true + · simp only [b, ite_true] + refine Spec.weaken (Spec.pure _) ?_ + rintro _ _ _ _ _ ⟨rfl, rfl, rfl⟩ + exact ⟨rfl, rfl, rfl⟩ + · simp only [b, Bool.false_eq_true, ite_false] + refine Spec.weaken + (Spec.bind Spec.getV fun w => updateCommitGo_spec fuel _ _) ?_ + rintro _ _ _ _ _ ⟨_, _, _, ⟨rfl, rfl, rfl⟩, rfl, rfl, loop⟩ + exact ⟨rfl, rfl, loop⟩ + · rintro v o r v'' o'' ⟨found, v', o', ⟨w, v1, o1, ⟨rfl, rfl, rfl⟩, run, rfl, rfl⟩, rfl, rfl, rest⟩ + refine ⟨rfl, rfl, ?_⟩ + simp only [updateCommitOf, run] + cases found with + | none => simpa using rest.symm + | some i => + by_cases b : (newCommit.any fun x => decide (i <= x)) = true + · simp only [b, ite_true] at rest ⊢ + rw [rest] + · simp only [b, Bool.false_eq_true, ite_false] at rest ⊢ + exact rest + +end Monadic + +/-! ## `Hyps` from the invariant -/ + +section OfInv + +open Consensus.TraceValidation (Names abs signaturesIn inv invChecks configurationsMatch) + +theorem nodup_eraseDups {α : Type} [BEq α] [LawfulBEq α] + : forall (n : Nat) (l : List α), l.length <= n -> l.eraseDups.Nodup + | _, [], _ => by simp + | 0, _ :: _, h => by simp at h + | n + 1, a :: as, h => by + rw [List.eraseDups_cons] + refine List.nodup_cons.mpr ⟨?_, ?_⟩ + · rw [List.mem_eraseDups, List.mem_filter] + simp + · apply nodup_eraseDups n + have := List.length_filter_le (fun b => !b == a) as + simp only [List.length_cons] at h + omega + +theorem nodup_of_eraseDups_eq {α : Type} [BEq α] [LawfulBEq α] {l : List α} + (h : l.eraseDups = l) + : l.Nodup := by + rw [← h] + exact nodup_eraseDups _ l (Nat.le_refl _) + +/-- A conjunct of `inv`, looked up by name. -/ +theorem inv_conjunct {names : Names} {v : State} (h : inv names v = true) (n : String) + : ((invChecks names v).lookup n).getD true = true := by + unfold inv at h + generalize invChecks names v = l at h + induction l with + | nil => rfl + | cons x l ih => + obtain ⟨k, b⟩ := x + simp only [List.all_cons, Bool.and_eq_true] at h + simp only [List.lookup_cons] + split + · exact h.1 + · exact ih h.2 + +theorem configurationsMatch_spec {ci : Nat} + : forall {ds cs : List (Nat × List NodeID)}, + configurationsMatch ci ds cs = true + -> ds = cs + \/ exists i j n rest, + ds = (i, n) :: rest /\ cs = (j, n) :: rest /\ j <= i /\ i <= ci + | [], [], _ => Or.inl rfl + | [], _ :: _, h => by simp [configurationsMatch] at h + | _ :: _, [], h => by simp [configurationsMatch] at h + | (i, n) :: ds, (j, m) :: cs, h => by + simp only [configurationsMatch, Bool.and_eq_true, beq_iff_eq, Bool.or_eq_true, + decide_eq_true_eq] at h + obtain ⟨⟨rfl, ij⟩, rfl⟩ := h + rcases ij with rfl | ⟨ji, ic⟩ + · exact Or.inl rfl + · exact Or.inr ⟨i, j, n, ds, rfl, rfl, ji, ic⟩ + +theorem Hyps.ofInv {names : Names} {v : State} (h : inv names v = true) + : Hyps names v := by + have c1 := inv_conjunct h "ledger_size" + have c2 := inv_conjunct h "commit_le_last" + have c3 := inv_conjunct h "committable" + have c4 := inv_conjunct h "terms_are_views" + have c5 := inv_conjunct h "views_bounded" + have c6 := inv_conjunct h "configurations" + have c7 := inv_conjunct h "self_named" + have c8 := inv_conjunct h "names_round_trip" + have c9 := inv_conjunct h "configuration_members_distinct" + simp only [invChecks, List.lookup_cons, List.lookup_nil] at c1 c2 c3 c4 c5 c6 c7 c8 c9 + simp only [String.reduceBEq, Option.getD_some, beq_iff_eq, decide_eq_true_eq, Bool.or_eq_true, + List.all_eq_true] at c1 c2 c3 c4 c5 c6 c7 c8 c9 + refine ⟨c1, c2, c3, ?_, c5, ?_, c7, ?_, ?_, ?_⟩ + · intro i i1 iL + exact c4 i (List.mem_range'_1.mpr ⟨i1, by omega⟩) + · intro L0 + rcases c6 with zero | matched + · omega + rcases configurationsMatch_spec matched with same | ⟨i, j, n, rest, hd, hc, ji, ic⟩ + · exact ⟨_, configs_of_map names _ _ same, Or.inl rfl⟩ + obtain ⟨y, E, hE, hy, hE'⟩ := List.map_eq_cons_iff.mp hd + obtain ⟨a, A, hA, ha, hA'⟩ := List.map_eq_cons_iff.mp hc + simp only [Prod.mk.injEq] at hy ha + have yi := hy.1 + have aj := ha.1 + have ac : (abs names v).commitIndex = v.commitIdx := rfl + rw [ac] at hA + refine ⟨{ y with idx := j } :: E, configs_of_map names _ _ ?_, Or.inr + ⟨{ y with idx := j }, y, E, rfl, hE, rfl, by simp only; omega, by omega⟩⟩ + rw [hA] + simp only [List.map_cons, hE', hA', ha.1, ha.2, hy.2] + · intro p mem + exact c8 p.1 (List.mem_append_right _ (List.mem_map_of_mem mem)) + · intro x mem a member + exact c8 a.1 (List.mem_append_left _ + (List.mem_flatMap.mpr ⟨x, mem, List.mem_map_of_mem member⟩)) + · intro x mem + exact nodup_of_eraseDups_eq (c9 x mem) + +/-- +`update_commit` on a declared state that satisfies `inv` chooses the clean +`highestCommittableIndex`. +-/ +theorem updateCommit_eq_of_inv {names : Names} {v : State} (h : inv names v = true) + {fuel : Nat} {r : Option Nat} (run : updateCommitOf v 0 none fuel = .ok r) + : highestCommittableIndex (abs names v) (names.id v.nodeId) = r.getD v.commitIdx := + updateCommit_eq (Hyps.ofInv h) run + +end OfInv + +end Consensus.TraceValidation.Proofs.ReplUpdateCommit diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteLemmas.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteLemmas.lean new file mode 100644 index 000000000000..1bdbd0778ef4 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteLemmas.lean @@ -0,0 +1,689 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Lemmas for the vote obligations (not reviewed) + +Shared by `RequestVote` and `RequestPreVote`: + +* `Det`: a handler that deterministically maps the declared state and appends sends, with + combinators and the `vote_det` tactic; `det_recvRequestVote` computes `recv_request_vote` + as the functions `rvVars` and `rvOut`. +* Links between `inv` and the clean model: `lastCommittable_eq` and `getTerm_eq` relate + M_tv's `lastCommittable` and `getTerm` to clean `maxCommittableIndex` and `termAt`; + `votedFor_link` relates `voted_for` to the clean `votedFor` through the name table. +* `inv_get` and the `inv_conj` tactic: one named conjunct of `inv`. +* The clean receive steps `clean_preVote` and `clean_vote`, and `agrees` after them. +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open CCF.Sections (LocalRun) + +/-- `x` deterministically maps the declared state by `f` and appends `g` to the outbox. -/ +def Det {α : Type} (env : Env) (x : M α) (f : State -> State) (g : State -> Outbox) + : Prop := + Spec env x fun v o _ v' o' => v' = f v /\ o' = o ++ g v + +namespace Det +variable {env : Env} + +theorem ofKeeps {α : Type} {x : M α} (h : Spec.Keeps env x) + : Det env x id (fun _ => []) := + Spec.weaken h fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, by simp [b]⟩ + +theorem bind {α β : Type} {x : M α} {k : α -> M β} {f f' : State -> State} + {g g' : State -> Outbox} (hx : Det env x f g) (hk : forall a, Det env (k a) f' g') + : Det env (x >>= k) (fun v => f' (f v)) (fun v => g v ++ g' (f v)) := + Spec.weaken (Spec.bind hx hk) + fun _ _ _ _ _ ⟨_, _, _, ⟨h1, h2⟩, h3, h4⟩ => by + subst h1 h2; exact ⟨h3, by simp [h4]⟩ + +theorem getV_bind {β : Type} {k : State -> M β} {f : State -> State -> State} + {g : State -> State -> Outbox} (hk : forall s, Det env (k s) (f s) (g s)) + : Det env (Exec.getV >>= k) (fun v => f v v) (fun v => g v v) := + Spec.weaken (Spec.bind Spec.getV hk) + fun _ _ _ _ _ ⟨_, _, _, ⟨h0, h1, h2⟩, h3, h4⟩ => by + subst h0 h1 h2; exact ⟨h3, h4⟩ + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} {f f' : State -> State} + {g g' : State -> Outbox} (hx : Det env x f g) (hy : Det env y f' g') + : Det env (if b then x else y) (fun v => if b then f v else f' v) + (fun v => if b then g v else g' v) := + Spec.weaken (Spec.ite hx hy) + fun _ _ _ _ _ ⟨p, q⟩ => by + by_cases hb : b + · simpa [hb] using p hb + · simpa [hb] using q hb + +theorem pure {α : Type} (a : α) : Det env (Pure.pure a : M α) id (fun _ => []) := + ofKeeps (Spec.Keeps.pure a) + +theorem setV (f : State -> State) : Det env (Exec.setV f) f (fun _ => []) := + Spec.weaken (Spec.setV f) fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, by simp [b]⟩ + +theorem send (dst : NodeId) (m : Message) + : Det env (Exec.send dst m) id + (fun v => [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id dst) m]) := + Spec.weaken (Spec.send dst m) fun _ _ _ _ _ ⟨a, b⟩ => ⟨a, b⟩ + +theorem trace (fn : String) : Det env (Exec.trace fn) id (fun _ => []) := + ofKeeps (Spec.trace fn) + +theorem emit (k : String) (j : Lean.Json) : Det env (Exec.emit k j) id (fun _ => []) := + ofKeeps (Spec.emit k j) + +theorem emitStr (k s : String) : Det env (Exec.emitStr k s) id (fun _ => []) := + ofKeeps (Spec.emitStr k s) + +theorem congr {α : Type} {x : M α} {f f' : State -> State} {g g' : State -> Outbox} + (h : Det env x f g) (hf : forall v, f v = f' v) (hg : forall v, g v = g' v) + : Det env x f' g' := by + have e1 : f = f' := funext hf + have e2 : g = g' := funext hg + subst e1 e2; exact h + +theorem run {f : State -> State} {g : State -> Outbox} {x : M Unit} (h : Det env x f g) + {vars : State} {queue : List Action} {final : Bool} {c : Ctx} + (ran : Exec.run env vars queue final x = .ok c) + : c.vars = f vars /\ c.outbox = g vars := by + have := Spec.run h ran + simpa using this + +end Det + +/-- Decompose a handler built from `getV`, `setV`, `send` and trace points into `Det`. -/ +macro "vote_det" : tactic => + `(tactic| repeat' (first + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.pure _ + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.setV _ + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.send _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.trace _ + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.emit _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Vote.Det.emitStr _ _ + | with_reducible apply Consensus.TraceValidation.Proofs.Vote.Det.getV_bind + | with_reducible apply Consensus.TraceValidation.Proofs.Vote.Det.bind + | with_reducible apply Consensus.TraceValidation.Proofs.Vote.Det.ite + | with_reducible intro)) + +theorem det_traceRecv (env : Env) (fn : String) (from_ : NodeId) (m : Message) + : Det env (Exec.traceRecv fn from_ m) id (fun _ => []) := by + unfold Exec.traceRecv + apply Det.congr + · vote_det + all_goals intro v; simp + +def bant (t : Nat) (v : State) : State := + { + v with + votedFor := if v.currentView != t then none else v.votedFor + currentView := t + votesForMe := v.configurations.map fun c => (c.idx, [], State.quorum c.nodes.length) + leaderId := none + leadership := .follower + isNewFollower := true + } + +theorem det_becomeAware (env : Env) (t : Nat) + : Det env (Exec.becomeAwareOfNewTerm t) (bant t) (fun _ => []) := by + unfold Exec.becomeAwareOfNewTerm Exec.resetVotesForMe Exec.becomeFollower + apply Det.congr + · vote_det + all_goals intro v; simp [bant] + +def rvGrant (pre : Bool) (from_ : NodeId) (r : RequestVoteRequest) (v : State) : Bool := + !(!pre && v.leaderId.isSome) + && !(!pre && v.votedFor.any (· != from_)) + && (decide (r.lastCommittableTerm > v.getTerm v.lastCommittable) + || r.lastCommittableTerm == v.getTerm v.lastCommittable + && decide (r.lastCommittableIndex >= v.lastCommittable)) + +def rvMid (r : RequestVoteRequest) (v : State) : State := + if v.currentView < r.term then bant r.term v else v + +def rvVars (pre : Bool) (from_ : NodeId) (r : RequestVoteRequest) (v : State) : State := + if v.currentView > r.term then + v + else if rvGrant pre from_ r (rvMid r v) && !pre then + { rvMid r v with leaderId := none, votedFor := some from_ } + else + rvMid r v + +def rvResp (pre : Bool) (t : Nat) (g : Bool) : Message := + if pre then + .requestPreVoteResponse { term := t, voteGranted := g } + else + .requestVoteResponse { term := t, voteGranted := g } + +def rvOut (env : Env) (pre : Bool) (from_ : NodeId) (r : RequestVoteRequest) (v : State) + : Outbox := + [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id from_) + (if v.currentView > r.term then + rvResp pre v.currentView false + else + rvResp pre (rvMid r v).currentView (rvGrant pre from_ r (rvMid r v)))] + +@[simp] +theorem bant_lastCommittable (t : Nat) (v : State) + : (bant t v).lastCommittable = v.lastCommittable := + rfl + +@[simp] theorem bant_getTerm (t : Nat) (v : State) : (bant t v).getTerm = v.getTerm := rfl + +theorem det_recvRequestVote (env : Env) (from_ : NodeId) (pre : Bool) + (r : RequestVoteRequest) + : Det env (Exec.recvRequestVote from_ pre r) (rvVars pre from_ r) + (rvOut env pre from_ r) := by + unfold Exec.recvRequestVote + unfold Exec.traceRecv Exec.becomeAwareOfNewTerm Exec.resetVotesForMe Exec.becomeFollower + dsimp only + apply Det.congr + · vote_det + all_goals + intro v + simp only [rvVars, rvOut, rvMid, rvGrant, rvResp] + by_cases h1 : v.currentView > r.term + · simp [h1] + · by_cases h2 : v.currentView < r.term <;> cases pre <;> simp [h1, h2, bant, State.lastCommittable, State.getTerm] <;> (repeat' split) <;> simp_all <;> (cases hl : v.leaderId <;> simp_all) + +theorem eligiblePeers_congr {a b : NodeState} (hl : a.log = b.log) + (hc : a.commitIndex = b.commitIndex) (self : NodeID) + : eligiblePeers a self = eligiblePeers b self := by + unfold eligiblePeers NodeState.activeMembers NodeState.retirementCompletedNodes + NodeState.activeConfigurations NodeState.committedLog + rw [hl, hc] + +theorem foldMax_ge_start (p : Nat -> Bool) (l : List Nat) (b : Nat) + : b <= l.foldl (fun best i => if p i then max best i else best) b := by + induction l generalizing b with + | nil => exact Nat.le_refl _ + | cons x xs ih => + simp only [List.foldl_cons] + refine Nat.le_trans ?_ (ih _) + split <;> omega + +theorem foldMax_ge_mem (p : Nat -> Bool) (l : List Nat) (b i : Nat) (hi : i ∈ l) + (hp : p i = true) + : i <= l.foldl (fun best i => if p i then max best i else best) b := by + induction l generalizing b with + | nil => simp at hi + | cons x xs ih => + simp only [List.foldl_cons] + rcases List.mem_cons.mp hi with rfl | hi + · refine Nat.le_trans ?_ (foldMax_ge_start p xs _) + simp only [hp, ite_true]; omega + · exact ih _ hi + +theorem foldMax_cases (p : Nat -> Bool) (l : List Nat) (b : Nat) + : l.foldl (fun best i => if p i then max best i else best) b = b + ∨ p (l.foldl (fun best i => if p i then max best i else best) b) = true := by + induction l generalizing b with + | nil => exact Or.inl rfl + | cons x xs ih => + simp only [List.foldl_cons] + rcases ih (if p x then max b x else b) with h | h + · rw [h] + by_cases hx : p x + · simp only [hx, ite_true] + rcases Nat.le_total b x with hb | hb + · rw [Nat.max_eq_right hb]; exact Or.inr hx + · rw [Nat.max_eq_left hb]; exact Or.inl rfl + · simp [hx] + · exact Or.inr h + +theorem isSignatureAt_le_length {log : List Model.Node.Entry} {i : Nat} + (h : isSignatureAt log i = true) + : i <= log.length := by + unfold isSignatureAt entryAt? at h + split at h + · rename_i e he + split at he + · simp at he + · have := (List.getElem?_eq_some_iff.mp he).1 + omega + · simp at h + +theorem isSignatureAt_zero (log : List Model.Node.Entry) + : isSignatureAt log 0 = false := by + simp [isSignatureAt, entryAt?] + +theorem eq_maxCommittableIndex {log : List Model.Node.Entry} {m : Nat} + (h0 : m = 0 ∨ isSignatureAt log m = true) + (hall : forall i, isSignatureAt log i = true -> i <= m) + : maxCommittableIndex log = m := by + unfold maxCommittableIndex + apply Nat.le_antisymm + · rcases foldMax_cases (isSignatureAt log) (List.range (log.length + 1)) 0 with h | h + · rw [h]; exact Nat.zero_le _ + · exact hall _ h + · rcases h0 with h | h + · rw [h]; exact Nat.zero_le _ + · exact foldMax_ge_mem _ _ _ _ + (List.mem_range.mpr (Nat.lt_succ_of_le (isSignatureAt_le_length h))) h + +theorem le_of_getLast? + : forall {l : List Nat} {x : Nat}, + l.Pairwise (· < ·) -> l.getLast? = some x -> forall y, y ∈ l -> y <= x + | [], _, _, h, _, _ => by simp at h + | [a], _, _, h, _, hy => by simp at h hy; omega + | a :: b :: l, x, hp, h, y, hy => by + have hp' := List.pairwise_cons.mp hp + have h' : (b :: l).getLast? = some x := by simpa using h + have ih := le_of_getLast? hp'.2 h' + rcases List.mem_cons.mp hy with rfl | hy + · exact Nat.le_of_lt (Nat.lt_of_lt_of_le (hp'.1 b (by simp)) (ih b (by simp))) + · exact ih y hy + +theorem isSignatureAt_abs {names : Names} {d : State} (h : d.ledger.size = d.lastIdx) + (i : Nat) + : isSignatureAt (abs names d).log i = (i != 0 && d.ledger[i - 1]?.any (·.sig)) := by + have htake : d.ledger.toList.take d.lastIdx = d.ledger.toList := by + rw [← h, ← Array.length_toList, List.take_length] + simp only [abs, htake, isSignatureAt, entryAt?] + by_cases hi : i = 0 + · simp [hi] + · simp only [hi, ite_false, List.getElem?_map, Array.getElem?_toList] + cases d.ledger[i - 1]? with + | none => simp + | some e => cases hs : e.sig <;> simp [absEntry, hs, EntryContent.isSignature, hi] + +theorem termAt_abs {names : Names} {d : State} (h : d.ledger.size = d.lastIdx) (i : Nat) + : termAt (abs names d).log i + = if i = 0 then 0 else (d.ledger[i - 1]?.map (·.term)).getD 0 := by + have htake : d.ledger.toList.take d.lastIdx = d.ledger.toList := by + rw [← h, ← Array.length_toList, List.take_length] + simp only [abs, htake, termAt, entryAt?] + by_cases hi : i = 0 + · simp [hi] + · simp only [hi, ite_false, List.getElem?_map, Array.getElem?_toList] + cases d.ledger[i - 1]? <;> simp [absEntry] + +theorem inv_get {names : Names} {d : State} (h : inv names d = true) (n : String) + : ((invChecks names d).lookup n).getD true = true := by + unfold inv at h + generalize invChecks names d = l at h ⊢ + induction l with + | nil => rfl + | cons p ps ih => + obtain ⟨k, b⟩ := p + simp only [List.all_cons, Bool.and_eq_true] at h + simp only [List.lookup] + split + · simpa using h.1 + · exact ih h.2 + +/-- The conjunct of `inv` named `n`, from `h : inv names d = true`. -/ +macro "inv_conj " h:term:max n:str : tactic => + `(tactic| ( + have hc := Consensus.TraceValidation.Proofs.Vote.inv_get $h $n + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at hc + first | exact hc | simpa using hc)) + +theorem inv_parts {names : Names} {d : State} (h : inv names d = true) + : d.ledger.size = d.lastIdx + /\ d.commitIdx <= d.lastIdx + /\ d.committable = signaturesIn d d.commitIdx d.lastIdx + /\ (d.commitIdx = 0 \/ d.ledger[d.commitIdx - 1]?.any (·.sig) = true) + /\ (forall i, + 1 <= i -> i <= d.lastIdx -> d.ledger[i - 1]?.map (·.term) = some (d.viewAt i)) + /\ d.views.size <= d.currentView + /\ d.views.all (0 < ·) = true := by + refine ⟨ + by inv_conj h "ledger_size", + by inv_conj h "commit_le_last", + by inv_conj h "committable", + by inv_conj h "commit_at_signature", + ?_, + by inv_conj h "views_bounded", + by inv_conj h "views_positive" + ⟩ + intro i hi1 hi2 + have h5 : (List.range' 1 d.lastIdx).all + (fun i => d.ledger[i - 1]?.map (·.term) == some (d.viewAt i)) = true := by + inv_conj h "terms_are_views" + have := List.all_eq_true.mp h5 i (List.mem_range'.mpr ⟨i - 1, by omega, by omega⟩) + simpa using this + +theorem lastCommittable_eq_of {names : Names} {d : State} (h1 : d.ledger.size = d.lastIdx) + (h3 : d.committable = signaturesIn d d.commitIdx d.lastIdx) + (h4 : d.commitIdx = 0 \/ d.ledger[d.commitIdx - 1]?.any (·.sig) = true) + : d.lastCommittable = maxCommittableIndex (abs names d).log := by + have hsig := isSignatureAt_abs (names := names) h1 + have hmem : forall x, x ∈ d.committable ↔ (d.commitIdx < x /\ x <= d.lastIdx + /\ d.ledger[x - 1]?.any (·.sig) = true) := by + intro x + rw [h3] + simp only [signaturesIn, List.mem_filter, List.mem_range'] + constructor + · rintro ⟨⟨k, hk, rfl⟩, hs⟩; exact ⟨by omega, by omega, hs⟩ + · rintro ⟨a, b, c⟩; exact ⟨⟨x - (d.commitIdx + 1), by omega, by omega⟩, c⟩ + have hsorted : d.committable.Pairwise (· < ·) := by + rw [h3]; exact (List.pairwise_lt_range' ..).filter _ + have hbound : forall i, d.ledger[i - 1]?.any (·.sig) = true -> i != 0 -> i <= d.lastIdx := by + intro i hs hi + cases he : d.ledger[i - 1]? with + | none => simp [he] at hs + | some e => + have := (Array.getElem?_eq_some_iff.mp he).1 + simp at hi; omega + symm + unfold State.lastCommittable + cases hl : d.committable.getLast? with + | none => + have hnil : d.committable = [] := List.getLast?_eq_none_iff.mp hl + simp only [Option.getD_none] + apply eq_maxCommittableIndex + · by_cases hc : d.commitIdx = 0 + · exact Or.inl hc + · right; rw [hsig] + have h4 := h4.resolve_left hc + simp only [h4, Bool.and_true]; simpa using hc + · intro i hi + rw [hsig] at hi + simp only [Bool.and_eq_true] at hi + refine Nat.le_of_not_lt fun hlt => ?_ + have := (hmem i).mpr ⟨hlt, hbound i hi.2 hi.1, hi.2⟩ + simp [hnil] at this + | some x => + simp only [Option.getD_some] + have hx := (hmem x).mp (List.mem_of_getLast? hl) + apply eq_maxCommittableIndex + · right; rw [hsig]; simp only [hx.2.2, Bool.and_true]; simp; omega + · intro i hi + rw [hsig] at hi + simp only [Bool.and_eq_true] at hi + by_cases hlt : d.commitIdx < i + · exact le_of_getLast? hsorted hl i ((hmem i).mpr ⟨hlt, hbound i hi.2 hi.1, hi.2⟩) + · omega + +theorem lastCommittable_eq {names : Names} {d : State} (h : inv names d = true) + : d.lastCommittable = maxCommittableIndex (abs names d).log := by + obtain ⟨h1, -, h3, h4, -⟩ := inv_parts h + exact lastCommittable_eq_of h1 h3 h4 + +theorem viewAt_zero {d : State} (h : d.views.all (0 < ·) = true) : d.viewAt 0 = 0 := by + simp only [State.viewAt, List.length_eq_zero_iff, List.filter_eq_nil_iff] + intro x hx + have := (Array.all_eq_true_iff_forall_mem.mp h) x (by simpa using hx) + simp at this ⊢; omega + +theorem getTerm_eq {names : Names} {d : State} (h : inv names d = true) (i : Nat) + : d.getTerm i = termAt (abs names d).log i := by + obtain ⟨h1, -, -, -, h5, -, h7⟩ := inv_parts h + rw [termAt_abs h1] + unfold State.getTerm + by_cases hi : i = 0 + · subst hi; simp [viewAt_zero h7] + · by_cases hl : i > d.lastIdx + · have : d.ledger[i - 1]? = none := by simp; omega + simp [hl, hi, this] + · simp only [hl, hi, ite_false] + rw [h5 i (by omega) (by omega)]; rfl + +/-- `voteLogUpToDate`, as the clean step computes it. -/ +def cleanLogOk (s : NodeState) (r : RequestVoteRequest) : Bool := + decide (maxCommittableTerm s.log < r.lastCommittableTerm) + || decide (maxCommittableTerm s.log = r.lastCommittableTerm) + && decide (maxCommittableIndex s.log <= r.lastCommittableIndex) + +theorem decide_preVote (s : NodeState) (r : RequestVoteRequest) (t : Nat) + : decide (t = s.currentTerm ∧ voteLogUpToDate s r) + = (decide (t = s.currentTerm) && cleanLogOk s r) := by + rw [Bool.eq_iff_iff, decide_eq_true_iff] + simp [cleanLogOk, voteLogUpToDate, CCF.TxID.le] + +theorem clean_preVote (node source : NodeID) (clean : NodeState) (r : RequestVoteRequest) + : (Consensus.Model.Node.step (CCF.Capabilities.record node) node clean + (.receive source (.requestPreVoteRequest r))).run + {} + = some + ( + updateTerm clean r.term, + { + outgoing := + [⟨ + node, + source, + .requestPreVoteResponse + { + term := (updateTerm clean r.term).currentTerm, + voteGranted := + decide (r.term = (updateTerm clean r.term).currentTerm) + && cleanLogOk (updateTerm clean r.term) r + } + ⟩] + } + ) := by + simp [Consensus.Model.Node.step, Model.Node.receive, handleRequestPreVoteRequest, + CCF.Capabilities.record, observeTerm, Message.term] + exact decide_preVote _ _ _ + +theorem agrees_bant {names : Names} {c : NodeState} {d : State} (t : Nat) + (h : agrees names c d = true) + : agrees names (Model.Node.becomeAwareOfNewTerm c t) (bant t d) = true := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, h10⟩, h11⟩ := h + simp only [abs, bant, Model.Node.becomeAwareOfNewTerm, trackedPeers, absRole] at * + rw [h2] + by_cases ht : d.currentView = t <;> simp [ht, h3, h4, h7, h11] <;> decide + +theorem logOk_eq {names : Names} {c : NodeState} {d : State} (h : inv names d = true) + (hlog : c.log = (abs names d).log) (r : RequestVoteRequest) + : (decide (r.lastCommittableTerm > d.getTerm d.lastCommittable) + || r.lastCommittableTerm == d.getTerm d.lastCommittable + && decide (r.lastCommittableIndex >= d.lastCommittable)) + = cleanLogOk c r := by + rw [lastCommittable_eq h, getTerm_eq h, ← hlog] + simp only [cleanLogOk, maxCommittableTerm] + by_cases a : termAt c.log (maxCommittableIndex c.log) < r.lastCommittableTerm <;> + by_cases b : termAt c.log (maxCommittableIndex c.log) = r.lastCommittableTerm <;> + by_cases e : maxCommittableIndex c.log <= r.lastCommittableIndex <;> + simp [a, b, e] <;> omega + +theorem inv_named {names : Names} {d : State} (h : inv names d = true) + : d.votedFor.all (fun x => names.name (names.id x) == x) = true + /\ (d.leadership ≠ .leader ∨ d.leaderId = some d.nodeId) := by + have h7 : (d.leadership != .leader || d.leaderId == some d.nodeId) = true := by + inv_conj h "leader_knows_itself" + refine ⟨by inv_conj h "voted_for_named", ?_⟩ + by_cases hl : d.leadership = .leader + · right; simpa [hl] using h7 + · exact Or.inl hl + +theorem rvVars_nodeId (pre : Bool) (from_ : NodeId) (r : RequestVoteRequest) (v : State) + : (rvVars pre from_ r v).nodeId = v.nodeId := by + have hm : (rvMid r v).nodeId = v.nodeId := by unfold rvMid; split <;> rfl + unfold rvVars + split + · rfl + · split + · exact hm + · exact hm + +theorem updateTerm_of_lt {c : NodeState} {t : Nat} (h : c.currentTerm < t) + : updateTerm c t = Model.Node.becomeAwareOfNewTerm c t := by + simp [updateTerm, h] + +theorem updateTerm_of_ge {c : NodeState} {t : Nat} (h : ¬ c.currentTerm < t) + : updateTerm c t = c := by + simp [updateTerm, h] + +theorem agrees_term_log {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.currentTerm = d.currentView /\ c.log = (abs names d).log := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨-, h2⟩, h3⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩, -⟩ := h + exact ⟨h2, h3⟩ + +theorem msgInv_source {names : Names} {e : CCF.Envelope NodeID Message} + (h : msgInv names e = true) + : names.id (names.name e.source) = e.source := by + simp only [msgInv, Bool.and_eq_true, beq_iff_eq] at h + exact h.1.1.1.1 + +theorem msgInv_reply {names : Names} {node source : NodeID} {m m' : Message} + (hn : names.id (names.name node) = node) (h : msgInv names ⟨source, node, m⟩ = true) + (hm' : forall r, m' ≠ .appendEntriesRequest r) + : msgInv names ⟨node, source, m'⟩ = true := by + simp only [msgInv, Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq] at h ⊢ + refine ⟨⟨⟨⟨hn, fun e => h.1.1.1.2 e.symm⟩, ?_⟩, ?_⟩, ?_⟩ <;> cases m' <;> simp_all + +theorem agrees_vote_parts {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.votedFor = d.votedFor.map names.id /\ c.primaryKnown = d.leaderId.isSome := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨-, -⟩, -⟩, -⟩, -⟩, -⟩, h7⟩, h8⟩, -⟩, -⟩, -⟩ := h + exact ⟨h7, h8⟩ + +def cleanGrant (s : NodeState) (r : RequestVoteRequest) (source : NodeID) : Bool := + decide (r.term = s.currentTerm) + && cleanLogOk s r + && !s.primaryKnown + && decide (s.votedFor = none ∨ s.votedFor = some source) + +theorem decide_vote (s : NodeState) (r : RequestVoteRequest) (source : NodeID) + : decide + (r.term = s.currentTerm + ∧ voteLogUpToDate s r + ∧ (!s.primaryKnown) = true + ∧ (s.votedFor = none ∨ s.votedFor = some source)) + = cleanGrant s r source := by + rw [Bool.eq_iff_iff, decide_eq_true_iff] + simp [cleanGrant, cleanLogOk, voteLogUpToDate, CCF.TxID.le, and_assoc] + +theorem clean_vote (node source : NodeID) (clean : NodeState) (r : RequestVoteRequest) + : (Consensus.Model.Node.step (CCF.Capabilities.record node) node clean + (.receive source (.requestVoteRequest r))).run + {} + = some + ( + if cleanGrant (updateTerm clean r.term) r source then + { updateTerm clean r.term with votedFor := some source } + else + updateTerm clean r.term, + { + outgoing := + [⟨ + node, + source, + .requestVoteResponse + { + term := (updateTerm clean r.term).currentTerm, + voteGranted := cleanGrant (updateTerm clean r.term) r source + } + ⟩] + } + ) := by + simp [Consensus.Model.Node.step, Model.Node.receive, handleRequestVoteRequest, + CCF.Capabilities.record, observeTerm, Message.term] + rw [← decide_vote] + simp + +theorem votedFor_link {names : Names} {x : Option NodeId} {src : NodeID} + (hx : x.all (fun y => names.name (names.id y) == y) = true) + (hs : names.id (names.name src) = src) + : (!x.any (· != names.name src)) + = decide (x.map names.id = none ∨ x.map names.id = some src) := by + cases x with + | none => simp + | some y => + simp only [Option.all_some, beq_iff_eq] at hx + simp only [Option.any_some, Option.map_some, reduceCtorEq, Option.some.injEq, false_or] + by_cases hy : y = names.name src + · subst hy; simp [hs] + · have : names.id y ≠ src := fun e => hy (by rw [← hx, e]) + simp [hy, this] + +theorem agrees_vote {names : Names} {c : NodeState} {d : State} {src : NodeID} + (h : agrees names c d = true) (hl : d.leaderId = none) + (hs : names.id (names.name src) = src) + : agrees names { c with votedFor := some src } + { d with leaderId := none, votedFor := some (names.name src) } + = true := by + have ha : abs names { d with leaderId := none, votedFor := some (names.name src) } + = { abs names d with votedFor := some src } := by + simp [abs, hl, hs] + have ht : trackedPeers names { d with leaderId := none, votedFor := some (names.name src) } + = trackedPeers names d := rfl + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + rw [ha, ht] + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, -⟩, h8⟩, h9⟩, h10⟩, h11⟩ := h + exact ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, rfl⟩, h8⟩, h9⟩, h10⟩, h11⟩ + +theorem rvMid_frame {names : Names} (r : RequestVoteRequest) (d : State) + : (rvMid r d).lastCommittable = d.lastCommittable + /\ (rvMid r d).getTerm = d.getTerm + /\ (abs names (rvMid r d)).log = (abs names d).log + /\ ((rvMid r d).votedFor = none \/ (rvMid r d).votedFor = d.votedFor) := by + unfold rvMid + split + · refine ⟨rfl, rfl, rfl, ?_⟩ + simp only [bant]; split <;> simp + · exact ⟨rfl, rfl, rfl, Or.inr rfl⟩ + +theorem rvGrant_eq {names : Names} {s : NodeState} {d : State} {r : RequestVoteRequest} + {source : NodeID} (hd : inv names d = true) (ha : agrees names s (rvMid r d) = true) + (ht : (rvMid r d).currentView = r.term) (hs : names.id (names.name source) = source) + : rvGrant false (names.name source) r (rvMid r d) = cleanGrant s r source := by + obtain ⟨hterm, hlog⟩ := agrees_term_log ha + obtain ⟨hvf, hpk⟩ := agrees_vote_parts ha + obtain ⟨hlc, hgt, hal, hvd⟩ := rvMid_frame (names := names) r d + rw [hal] at hlog + have hok := logOk_eq hd hlog r + have hnamed : (rvMid r d).votedFor.all (fun x => names.name (names.id x) == x) = true := by + rcases hvd with h | h + · rw [h]; rfl + · rw [h]; exact (inv_named hd).1 + have hl := votedFor_link hnamed hs + simp only [rvGrant, cleanGrant, Bool.not_false, Bool.true_and, hlc, hgt] + rw [hok, hvf, ← hl, hpk, hterm, ht] + simp only [decide_true, Bool.true_and] + generalize cleanLogOk s r = a + generalize (rvMid r d).leaderId.isSome = b + generalize (!(rvMid r d).votedFor.any (· != names.name source)) = e + cases a <;> cases b <;> cases e <;> rfl + +theorem rvMid_agrees {names : Names} {clean : NodeState} {d : State} + {r : RequestVoteRequest} (h : agrees names clean d = true) + (hgt : ¬ d.currentView > r.term) + : agrees names (updateTerm clean r.term) (rvMid r d) = true + /\ (rvMid r d).currentView = r.term := by + obtain ⟨hterm, -⟩ := agrees_term_log h + by_cases hlt : d.currentView < r.term + · have hu : updateTerm clean r.term = Model.Node.becomeAwareOfNewTerm clean r.term := updateTerm_of_lt (by omega) + simp only [rvMid, hlt, ite_true, hu] + exact ⟨agrees_bant _ h, rfl⟩ + · have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + simp only [rvMid, hlt, ite_false, hu] + exact ⟨h, by omega⟩ + +/-- `UnnamedUnmatched` reads only the role, the log and the match indexes of a primary. -/ +theorem unmatched_frame {node : NodeID} {c c' : NodeState} (h : UnnamedUnmatched node c) + (keeps + : c'.role = .primary + -> c.role = .primary /\ c'.log = c.log /\ c'.matchIndex = c.matchIndex) + : UnnamedUnmatched node c' := by + intro primary n ne notNamed + obtain ⟨p, hl, hm⟩ := keeps primary + rw [hm] + exact h p n ne (hl ▸ notNamed) + +theorem unmatched_updateTerm {node : NodeID} {c : NodeState} (t : Nat) + (h : UnnamedUnmatched node c) + : UnnamedUnmatched node (updateTerm c t) := by + refine unmatched_frame h fun p => ?_ + by_cases lt : c.currentTerm < t + · simp [updateTerm, lt, Model.Node.becomeAwareOfNewTerm] at p + · simp only [updateTerm, lt, ite_false] at p ⊢ + exact ⟨p, trivial, trivial⟩ + +end Consensus.TraceValidation.Proofs.Vote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean new file mode 100644 index 000000000000..ecd9548c5344 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean @@ -0,0 +1,408 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Handler + +@[expose] public section + +/-! +# Reasoning about handler runs (not reviewed) + +A handler run (`Exec.run`) threads the declared state, the outbox and the bookkeeping of +the trace points it consumes. `Spec env x P` says: whenever `x` returns `a` from a context +with declared state `v` and outbox `o`, ending with `v'` and `o'`, then `P v o a v' o'`. +The bookkeeping (queue, labels, current action) is forgotten, so a handler's `Spec` is the +relation between declared states and sends that the obligations talk about. + +The `Spec` of a handler is built by the `spec` tactic from the rules below: one per monad +primitive and per control construct. Only `look` and the trace-point inputs (`use`) leave +their result unconstrained: they depend on the trace, not on the declared state. + +`unfold_run [defs] at h` instead unfolds the monad directly, for handlers small enough to +compute. +-/ + +set_option linter.unusedSimpArgs false + +/-- Unfold the handler monad and its primitives at a hypothesis. -/ +syntax "unfold_run" (" [" Lean.Parser.Tactic.simpLemma,* "]")? " at " ident : tactic + +macro_rules + | `(tactic| unfold_run at $h:ident) => + `(tactic| + simp [Consensus.TraceValidation.Exec.run, Consensus.TraceValidation.Exec.trace, + Consensus.TraceValidation.Exec.yieldAtPoint, Consensus.TraceValidation.Exec.fail, + Consensus.TraceValidation.Exec.emitStr, Consensus.TraceValidation.Exec.emitNat, + Consensus.TraceValidation.Exec.emit, Consensus.TraceValidation.Exec.getV, + Consensus.TraceValidation.Exec.setV, Consensus.TraceValidation.Exec.look, + Consensus.TraceValidation.Exec.send, Consensus.TraceValidation.Exec.note, + Consensus.TraceValidation.Exec.names, Consensus.TraceValidation.Exec.use, + Consensus.TraceValidation.Exec.liftE, Consensus.TraceValidation.Exec.curLoc, bind, + StateT.bind, StateT.run, get, getThe, MonadStateOf.get, StateT.get, set, StateT.set, + MonadStateOf.set, modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, pure, + StateT.pure, Except.pure, throw, throwThe, MonadExceptOf.throw, StateT.lift, + Except.bind] at $h:ident) + | `(tactic| unfold_run [$extra,*] at $h:ident) => + `(tactic| + simp [$extra,*, Consensus.TraceValidation.Exec.run, Consensus.TraceValidation.Exec.trace, + Consensus.TraceValidation.Exec.yieldAtPoint, Consensus.TraceValidation.Exec.fail, + Consensus.TraceValidation.Exec.emitStr, Consensus.TraceValidation.Exec.emitNat, + Consensus.TraceValidation.Exec.emit, Consensus.TraceValidation.Exec.getV, + Consensus.TraceValidation.Exec.setV, Consensus.TraceValidation.Exec.look, + Consensus.TraceValidation.Exec.send, Consensus.TraceValidation.Exec.note, + Consensus.TraceValidation.Exec.names, Consensus.TraceValidation.Exec.use, + Consensus.TraceValidation.Exec.liftE, Consensus.TraceValidation.Exec.curLoc, bind, + StateT.bind, StateT.run, get, getThe, MonadStateOf.get, StateT.get, set, StateT.set, + MonadStateOf.set, modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, pure, + StateT.pure, Except.pure, throw, throwThe, MonadExceptOf.throw, StateT.lift, + Except.bind] at $h:ident) + +namespace Consensus.TraceValidation.Proofs + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- The sends of a hold. -/ +abbrev Outbox := List (CCF.Envelope NodeID Message) + +/-- What every successful run of `x` does to the declared state and the outbox. -/ +def Spec {α : Type} (env : Env) (x : M α) + (P : State -> Outbox -> α -> State -> Outbox -> Prop) + : Prop := + forall (c : Ctx) (a : α) (c' : Ctx), + c.env = env + -> x.run c = .ok (a, c') + -> c'.env = env /\ P c.vars c.outbox a c'.vars c'.outbox + +namespace Spec + +variable {env : Env} + +theorem run {x : M Unit} {P : State -> Outbox -> Unit -> State -> Outbox -> Prop} + (spec : Spec env x P) {vars : State} {queue : List Action} {final : Bool} {c : Ctx} + (h : Exec.run env vars queue final x = .ok c) + : P vars [] () c.vars c.outbox := by + unfold Exec.run at h + split at h + · rename_i c'' found + cases h + exact (spec _ _ _ rfl found).2 + · cases h + +theorem pure {α : Type} (a : α) + : Spec env (Pure.pure a : M α) + fun v o b v' o' => + b = a /\ v' = v /\ o' = o := by + intro c b c' envOk h + simp only [Pure.pure, StateT.run, StateT.pure, Except.pure, Except.ok.injEq, + Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact ⟨envOk, rfl, rfl, rfl⟩ + +theorem bind {α β : Type} {x : M α} {f : α -> M β} + {P : State -> Outbox -> α -> State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> β -> State -> Outbox -> Prop} (first : Spec env x P) + (rest : forall a, Spec env (f a) (Q a)) + : Spec env (x >>= f) + fun v o b v'' o'' => + exists a v' o', P v o a v' o' /\ Q a v' o' b v'' o'' := by + intro c b c'' envOk h + simp only [StateT.run, Bind.bind, StateT.bind, Except.bind] at h + split at h + · cases h + · rename_i r found + obtain ⟨a, c'⟩ := r + obtain ⟨envMid, p⟩ := first c a c' envOk found + obtain ⟨envEnd, q⟩ := rest a c' b c'' envMid h + exact ⟨envEnd, a, c'.vars, c'.outbox, p, q⟩ + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} + {P Q : State -> Outbox -> α -> State -> Outbox -> Prop} + (yes : Spec env x P) (no : Spec env y Q) + : Spec env (if b then x else y) + fun v o a v' o' => + (b -> P v o a v' o') /\ (Not b -> Q v o a v' o') := by + intro c a c' envOk h + by_cases holds : b + · simp only [holds, ite_true] at h + obtain ⟨envEnd, p⟩ := yes c a c' envOk h + exact ⟨envEnd, fun _ => p, fun no => absurd holds no⟩ + · simp only [holds, ite_false] at h + obtain ⟨envEnd, q⟩ := no c a c' envOk h + exact ⟨envEnd, fun yes => absurd yes holds, fun _ => q⟩ + +theorem option {α β : Type} {o : Option α} {x : M β} {f : α -> M β} + {P : State -> Outbox -> β -> State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> β -> State -> Outbox -> Prop} + (none_ : Spec env x P) (some_ : forall a, Spec env (f a) (Q a)) + : Spec env + (match o with + | none => x + | some a => f a) + fun v ob r v' ob' => + (o = none -> P v ob r v' ob') + /\ (forall a, o = some a -> Q a v ob r v' ob') := by + intro c r c' envOk h + cases o with + | none => + obtain ⟨envEnd, p⟩ := none_ c r c' envOk h + refine ⟨envEnd, fun _ => p, ?_⟩ + intro _ found + cases found + | some a => + obtain ⟨envEnd, q⟩ := some_ a c r c' envOk h + refine ⟨envEnd, ?_, ?_⟩ + · intro found + cases found + · intro a' found + cases found + exact q + +theorem weaken {α : Type} {x : M α} + {P Q : State -> Outbox -> α -> State -> Outbox -> Prop} (spec : Spec env x P) + (implies : forall v o a v' o', P v o a v' o' -> Q v o a v' o') + : Spec env x Q := by + intro c a c' envOk h + obtain ⟨envEnd, p⟩ := spec c a c' envOk h + exact ⟨envEnd, implies _ _ _ _ _ p⟩ + +theorem throw_ {α : Type} (stop : Stop) + {P : State -> Outbox -> α -> State -> Outbox -> Prop} + : Spec env (throw stop : M α) P := by + intro c a c' _ h + simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, StateT.run, Bind.bind, + Except.bind] at h + +theorem fail {α : Type} (message : String) + {P : State -> Outbox -> α -> State -> Outbox -> Prop} + : Spec env (Exec.fail message : M α) P := + throw_ _ + +theorem list {α β : Type} {l : List α} {x : M β} {f : α -> List α -> M β} + {P : State -> Outbox -> β -> State -> Outbox -> Prop} + {Q : α -> List α -> State -> Outbox -> β -> State -> Outbox -> Prop} + (cons_ : forall a rest, Spec env (f a rest) (Q a rest)) (nil_ : Spec env x P) + : Spec env + (match l with + | a :: rest => f a rest + | [] => x) + fun v ob r v' ob' => + (l = [] -> P v ob r v' ob') + /\ (forall a rest, l = a :: rest -> Q a rest v ob r v' ob') := by + intro c r c' envOk h + cases l with + | nil => + obtain ⟨envEnd, p⟩ := nil_ c r c' envOk h + refine ⟨envEnd, fun _ => p, ?_⟩ + intro _ _ found + cases found + | cons a rest => + obtain ⟨envEnd, q⟩ := cons_ a rest c r c' envOk h + refine ⟨envEnd, ?_, ?_⟩ + · intro found + cases found + · intro a' rest' found + cases found + exact q + +theorem get + : Spec env (MonadState.get : M Ctx) + fun v o a v' o' => + a.vars = v /\ a.outbox = o /\ a.env = env /\ v' = v /\ o' = o := by + intro c a c' envOk h + simp only [MonadState.get, getThe, MonadStateOf.get, StateT.get, StateT.run, Pure.pure, + Except.pure, Except.ok.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact ⟨envOk, rfl, rfl, envOk, rfl, rfl⟩ + +theorem modify_ (f : Ctx -> Ctx) (keepsEnv : forall c, (f c).env = c.env) + : Spec env (modify f : M Unit) + fun v o _ v' o' => + exists c : Ctx, + c.vars = v /\ c.outbox = o /\ (f c).vars = v' /\ (f c).outbox = o' := by + intro c a c' envOk h + simp only [modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, StateT.run, + Pure.pure, Except.pure, Except.ok.injEq, Prod.mk.injEq] at h + obtain ⟨_, rfl⟩ := h + exact ⟨(keepsEnv c).trans envOk, c, rfl, rfl, rfl, rfl⟩ + +/-- Run a primitive on a concrete context: unfold the monad and split its branches. -/ +macro "prim_cases" : tactic => + `(tactic| + (try simp only [Bind.bind, StateT.bind, StateT.run, MonadState.get, getThe, MonadStateOf.get, + StateT.get, MonadStateOf.set, StateT.set, MonadStateOf.modifyGet, StateT.modifyGet, + Pure.pure, StateT.pure, Except.pure, Function.comp, Except.bind] at * + repeat' split at * + all_goals + first + | (simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, StateT.bind, Except.bind, + Bind.bind, Except.pure, StateT.set, StateT.pure, Pure.pure, Exec.fail, Functor.map, + Except.map] at *; done) + | (simp only [StateT.set, StateT.pure, Except.ok.injEq, Prod.mk.injEq] at *) + | skip)) + +/-- `x` leaves the declared state and the outbox alone. -/ +abbrev Keeps {α : Type} (env : Env) (x : M α) : Prop := + Spec env x fun v o _ v' o' => v' = v /\ o' = o + +theorem Keeps.bind {α β : Type} {x : M α} {f : α -> M β} (hx : Keeps env x) + (hf : forall a, Keeps env (f a)) + : Keeps env (x >>= f) := + weaken (Spec.bind hx hf) + fun _ _ _ _ _ ⟨_, _, _, ⟨h1, h2⟩, h3, h4⟩ => ⟨h3.trans h1, h4.trans h2⟩ + +theorem Keeps.pure {α : Type} (a : α) : Keeps env (Pure.pure a : M α) := + weaken (Spec.pure a) fun _ _ _ _ _ h => h.2 + +theorem Keeps.fail {α : Type} (message : String) : Keeps env (Exec.fail message : M α) := + Spec.fail message + +theorem Keeps.ite {α : Type} {b : Prop} [Decidable b] {x y : M α} (hx : Keeps env x) + (hy : Keeps env y) + : Keeps env (if b then x else y) := by + by_cases hb : b + · simpa [hb] using hx + · simpa [hb] using hy + +theorem Keeps.get : Keeps env (MonadState.get : M Ctx) := + weaken Spec.get fun _ _ _ _ _ h => h.2.2.2 + +theorem yieldAtPoint : Keeps env Exec.yieldAtPoint := by + intro c a c' envOk h + simp only [Exec.yieldAtPoint] at h + prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem trace (fn : String) : Keeps env (Exec.trace fn) := by + refine Keeps.bind yieldAtPoint fun _ => ?_ + intro c a c' envOk h + prim_cases + rcases hq : c.queue with _ | ⟨x, rest⟩ <;> simp only [hq] at h <;> prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem getV : Spec env Exec.getV fun v o a v' o' => a = v /\ v' = v /\ o' = o := by + intro c a c' envOk h + simp only [Exec.getV] at h + prim_cases + obtain ⟨rfl, rfl⟩ := h + exact ⟨envOk, rfl, rfl, rfl⟩ + +theorem setV (f : State -> State) + : Spec env (Exec.setV f) fun v o _ v' o' => v' = f v /\ o' = o := by + have rest : Spec env (modify fun c => { c with vars := f c.vars } : M Unit) + fun v o _ v' o' => v' = f v /\ o' = o := by + intro c a c' envOk h + simp only [_root_.modify, modifyGet] at h + prim_cases + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + refine weaken (Spec.bind yieldAtPoint fun _ => rest) ?_ + intro v o _ v' o' ⟨_, _, _, ⟨h1, h2⟩, h3, h4⟩ + subst h1 h2 + exact ⟨h3, h4⟩ + +theorem emit (k : String) (j : Lean.Json) : Keeps env (Exec.emit k j) := by + intro c a c' envOk h + simp only [Exec.emit] at h + prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem emitStr (k s : String) : Keeps env (Exec.emitStr k s) := emit _ _ + +theorem emitNat (k : String) (n : Nat) : Keeps env (Exec.emitNat k n) := emit _ _ + +theorem look : Keeps env Exec.look := by + refine Keeps.bind yieldAtPoint fun _ => ?_ + intro c a c' envOk h + prim_cases + rcases hq : c.queue with _ | ⟨x, rest⟩ <;> simp only [hq] at h <;> prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem lookFn : Keeps env Exec.lookFn := by + refine Keeps.bind look fun _ => ?_ + exact Keeps.pure _ + +theorem curLoc : Keeps env Exec.curLoc := by + intro c a c' envOk h + simp only [Exec.curLoc] at h + prim_cases + rcases hq : c.cur with _ | x <;> simp only [hq] at h <;> prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem liftE {α : Type} (x : Except String α) : Keeps env (Exec.liftE x) := by + unfold Exec.liftE + split + · exact Keeps.pure _ + · exact Keeps.bind curLoc fun _ => Keeps.fail _ + +theorem use (k : String) : Keeps env (Exec.use k) := by + intro c a c' envOk h + simp only [Exec.use] at h + prim_cases + generalize c.cur = cur at h + cases cur with + | none => + simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, Exec.fail, Functor.map, Except.map] at h + | some act => + simp only at h + generalize List.lookup k act.inputs = found at h + cases found with + | none => + simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, Exec.fail, Functor.map, Except.map] at h + | some j => + simp only [StateT.pure, Except.ok.injEq, Prod.mk.injEq] at h + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem inNat (k : String) : Keeps env (Exec.inNat k) := + Keeps.bind (use k) fun _ => liftE _ + +theorem inStr (k : String) : Keeps env (Exec.inStr k) := + Keeps.bind (use k) fun _ => liftE _ + +theorem inBool (k : String) : Keeps env (Exec.inBool k) := + Keeps.bind (use k) fun _ => liftE _ + +theorem note (n : Note) : Keeps env (Exec.note n) := by + intro c a c' envOk h + simp only [Exec.note, _root_.modify, modifyGet] at h + prim_cases + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, rfl⟩ + +theorem names + : Spec env Exec.names fun v o a v' o' => a = env.names /\ v' = v /\ o' = o := by + intro c a c' envOk h + simp only [Exec.names] at h + prim_cases + obtain ⟨rfl, rfl⟩ := h + exact ⟨envOk, by rw [envOk], rfl, rfl⟩ + +theorem send (dst : NodeId) (m : Message) + : Spec env (Exec.send dst m) + fun v o _ v' o' => + v' = v + /\ o' + = o ++ [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id dst) m] := by + intro c a c' envOk h + simp only [Exec.send, _root_.modify, modifyGet] at h + prim_cases + obtain ⟨_, rfl⟩ := h + subst envOk + exact ⟨rfl, rfl, rfl⟩ + +end Spec + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean new file mode 100644 index 000000000000..25d8f88c7d5f --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean @@ -0,0 +1,240 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Invariant +public import Consensus.TraceValidation.Machine + +@[expose] public section + +/-! +# Per-handler obligations (not reviewed) + +The refinement proof (`Consensus.TraceValidation.Proofs.Section`) reduces every lock hold to +one obligation about the `cft.h` handler the hold runs, `HoldSound`: run to completion from a +declared state `saved` satisfying the invariant, on any actions, the handler + +* assuming the declared state at release satisfies `inv` (the machine rejects the trace + at release otherwise), keeps the node id; +* if `saved` is not the pristine genesis primary (whose holds `genesisOk` restricts) and a + clean state agrees with it and satisfies `UnnamedUnmatched`, the clean state is matched by + the clean receive of the delivered message, if any, then admitted clean internal inputs, + reaching a clean state that agrees with the released declared state and satisfies + `UnnamedUnmatched`, with exactly the hold's sends, each satisfying `msgInv`. + +`Obligations env` lists one obligation per handler, keyed by message type for deliveries. +Each is an independent proposition (`AppendEntriesSound` and so on), proved in its own file +under `Consensus.TraceValidation.Proofs.Handlers`, importing only this file and lemma +libraries. +-/ + +namespace Consensus.TraceValidation + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) + +/-- +A clean primary `node` has match index 0 for every other node that no configuration in its +log names. + +`agrees` (reviewed) relates match indexes only for the declared peers, so without this a +clean state related to a primary may hold a stale match index for a node outside its +configurations; when a configuration then adds that node, cft.h creates the peer with +`match_idx = 0` while the clean `appendEntry` keeps the stale value, and `ReplicateSound` +fails. It holds of every clean initial state (all match indexes are 0) and is kept by every +clean step: `becomePrimary` resets every match index, a primary's log only grows (so the +named nodes only grow), and a primary raises a match index only on a response from a peer, +which M_tv only accepts from a declared peer, whom the `peers` conjunct of `inv` puts in a +configuration of the log. A clean state that is not primary is unconstrained. + +This is the weakest of the forms considered. Under `inv` (`peers`), the nodes outside the +declared peers and outside `removedNodes` are the unnamed nodes and possibly the node +itself, whose match index the clean model never reads, so this is implied by "a clean +primary has match index 0 outside its declared peers and `removedNodes`". Being about the +clean state alone, it needs no reasoning about peers erased at retirement. +-/ +def UnnamedUnmatched (node : NodeID) (c : NodeState) : Prop := + c.role = .primary + -> forall n, + n ≠ node + -> n ∉ configurationMembers (configurationHistory c.log) + -> c.matchIndex n = 0 + +/-- +`Rel env node c d`: the clean state `c` of `node` stands for the declared state `d`, which +satisfies the local invariant: `c` agrees with `d`, or, if `d` is the pristine genesis +primary (`pristine`), `c` is still the clean initial state; and `c` has no stale match +index for a node outside its configurations (`UnnamedUnmatched`). +-/ +def Rel (env : Env) (node : NodeID) (c : NodeState) (d : State) : Prop := + d.nodeId = env.names.name node + /\ env.names.id d.nodeId = node + /\ inv env.names d = true + /\ (pristine env d = false /\ agrees env.names c d = true + \/ pristine env d = true /\ c = Consensus.Model.initialNodeState env.genesis node) + /\ UnnamedUnmatched node c + +/-- +Admits an internal input given the other nodes' clean states: a node initializes only from +a prefix that some other node has committed (`Model.networkStep`'s guard). +-/ +def admit (others : List (NodeID × NodeState)) (_node : NodeID) : Input -> Bool + | .initAsBackup entries => + others.any + fun (_, c) => + entries.length <= c.commitIndex && c.log.take entries.length == entries + | _ => true + +end Consensus.TraceValidation + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun Keyed) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State Ctx Action) + +/-- A hold's clean local actions: the receive of its message, if any, then internal inputs. -/ +def cleanActions (env : Env) (recv : Option (NodeID × Message)) (inputs : List Input) + : List Event := + (recv.map fun (source, message) => (protocol env).receive source message).toList + ++ inputs.map (protocol env).internal + +/-- The declared state at release of every hold but a joiner's: the handler's. -/ +def plainFinish (_others : List (NodeID × Local)) (c : Ctx) : Except String State := + .ok c.vars + +/-- The declared state at release of `init_as_backup`: the snapshot prefix from a donor. -/ +def joinFinish (others : List (NodeID × Local)) (c : Ctx) : Except String State := + match snapshotOf c with + | some (index, term) => fillSnapshot others index term c.vars + | none => .ok c.vars + +/-- +The obligation of a hold of handler `h` on `node`, delivering `recv`, from the declared +state `saved`, released by `finish`. +-/ +def HoldSound (env : Env) (node : NodeID) (recv : Option (NodeID × Message)) + (h : Exec.M Unit) (saved : State) + (finish : List (NodeID × Local) -> Ctx -> Except String State) + : Prop := + forall (actions : List Action) (c : Ctx) (vars : State) (others : List (NodeID × Local)) + (cleanOthers : List (NodeID × NodeState)), + saved.nodeId = env.names.name node + -> env.names.id saved.nodeId = node + -> inv env.names saved = true + -> (forall source message, + recv = some (source, message) + -> msgInv env.names ⟨source, node, message⟩ = true) + -> Keyed (fun other local_ cleanOther => Rel env other cleanOther local_.vars) others + cleanOthers + -> Exec.run env saved actions true h = .ok c + -> c.queue = [] + -> finish others c = .ok vars + -> inv env.names vars = true + -> vars.nodeId = saved.nodeId + /\ forall clean, + pristine env saved = false + -> agrees env.names clean saved = true + -> UnnamedUnmatched node clean + -> exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node clean (cleanActions env recv inputs) clean' + c.outbox + /\ agrees env.names clean' vars = true + /\ UnnamedUnmatched node clean' + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall envelope, + envelope ∈ c.outbox -> msgInv env.names envelope = true + +/-! ## Deliveries, by message type -/ + +abbrev AppendEntriesSound (env : Env) : Prop := + forall node source request saved, + HoldSound env node (some (source, .appendEntriesRequest request)) + (Exec.recvAppendEntries (env.names.name source) request) saved plainFinish + +abbrev AppendEntriesResponseSound (env : Env) : Prop := + forall node source response saved, + HoldSound env node (some (source, .appendEntriesResponse response)) + (Exec.recvAppendEntriesResponse (env.names.name source) response) saved plainFinish + +abbrev RequestVoteSound (env : Env) : Prop := + forall node source request saved, + HoldSound env node (some (source, .requestVoteRequest request)) + (Exec.recvRequestVote (env.names.name source) false request) saved plainFinish + +abbrev RequestPreVoteSound (env : Env) : Prop := + forall node source request saved, + HoldSound env node (some (source, .requestPreVoteRequest request)) + (Exec.recvRequestVote (env.names.name source) true request) saved plainFinish + +abbrev RequestVoteResponseSound (env : Env) : Prop := + forall node source response saved, + initialised saved = true + -> HoldSound env node (some (source, .requestVoteResponse response)) + (Exec.recvRequestVoteResponse (env.names.name source) false response) saved + plainFinish + +abbrev RequestPreVoteResponseSound (env : Env) : Prop := + forall node source response saved, + initialised saved = true + -> HoldSound env node (some (source, .requestPreVoteResponse response)) + (Exec.recvRequestVoteResponse (env.names.name source) true response) saved + plainFinish + +abbrev ProposeRequestVoteSound (env : Env) : Prop := + forall node source term saved, + initialised saved = true + -> HoldSound env node (some (source, .proposeRequestVoteRequest term)) + (Exec.recvProposeRequestVote (env.names.name source) term) saved plainFinish + +/-! ## Local heads -/ + +abbrev TickSound (env : Env) : Prop := + forall node saved, HoldSound env node none Exec.periodic saved plainFinish + +abbrev ReplicateSound (env : Env) : Prop := + forall node saved, HoldSound env node none Exec.replicate saved plainFinish + +abbrev NominationSound (env : Env) : Prop := + forall node saved, HoldSound env node none Exec.nominateSuccessor saved plainFinish + +abbrev InitAsBackupSound (env : Env) : Prop := + forall node saved, HoldSound env node none Exec.initAsBackup saved joinFinish + +/-- The snapshot's configuration hooks, outside the lock, before `init_as_backup`. -/ +abbrev OutOfLockHookSound (env : Env) : Prop := + forall node saved, + saved.leadership = .none + -> saved.currentView = 0 + -> HoldSound env node none Exec.outOfLockHook saved plainFinish + +/-- `force_become_primary`, untraced, opened by its `become_leader`. -/ +abbrev ForceBecomePrimarySound (env : Env) : Prop := + forall node saved, + saved.currentView = 0 + -> saved.leadership = .none + -> pristine env saved = true + -> HoldSound env node none Exec.forceBecomePrimary saved plainFinish + +abbrev DropPendingToSound (env : Env) : Prop := + forall node saved, HoldSound env node none Exec.dropPendingTo saved plainFinish + +/-- Every handler's obligation. -/ +structure Obligations (env : Env) : Prop where + appendEntries : AppendEntriesSound env + appendEntriesResponse : AppendEntriesResponseSound env + requestVote : RequestVoteSound env + requestPreVote : RequestPreVoteSound env + requestVoteResponse : RequestVoteResponseSound env + requestPreVoteResponse : RequestPreVoteResponseSound env + proposeRequestVote : ProposeRequestVoteSound env + tick : TickSound env + replicate : ReplicateSound env + nomination : NominationSound env + initAsBackup : InitAsBackupSound env + outOfLockHook : OutOfLockHookSound env + forceBecomePrimary : ForceBecomePrimarySound env + dropPendingTo : DropPendingToSound env + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Section.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Section.lean new file mode 100644 index 000000000000..49dd6a707b44 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Section.lean @@ -0,0 +1,494 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Suffix +public import CCF.Proofs.Finset + +@[expose] public section + +/-! +# M_tv is a `CCF.Sections.Refinement` of the clean node, given the obligations (not reviewed) + +A section's events only extend the open hold: its head, delivered message and saved +declared state stay those of its first event, and the declared state at the last release +is unchanged. A release reruns the head's handler to completion from the saved state +(`runHold`), so the section is one hold of one handler, dispatched by the head's trace +point and, for deliveries, the message type (`dispatch`); `HoldSound` for that handler +(an `Obligations` field) gives its clean counterpart, given `inv` of the declared state +at release, which the release checks. Holds from the pristine genesis +primary have none: `genesisOk` makes them silent and keeps the clean initial state. +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State Ev Ctx Action) + +theorem toOption_ok {ε α : Type} {x : Except ε α} {a : α} (h : x.toOption = some a) + : x = .ok a := by + cases x <;> simp_all [Except.toOption] + +theorem decide_sound {p : Prop} (d : Decidable p) (h : @decide p d = true) : p := by + cases d <;> simp_all + +theorem sameVars_eq {a b : State} (h : sameVars a b = true) : a = b := by + unfold sameVars at h + exact decide_sound _ h + +/-- Opening a hold records the head, the delivery and the saved declared state. -/ +theorem stepE_idle {env : Env} {l l' : Local} {recv : Option (NodeID × Message)} {e : Ev} + (idle : l.sec = none) (h : stepE env l recv e = .ok l') + : exists a c, + l' + = { + l with + sec := some { head := e, recv, saved := l.vars, actions := [a], ctx := c } + } + /\ (opens e = true -> c.vars = l.vars) := by + unfold stepE at h + split at h + · cases h + · rename_i a _ + simp only [idle] at h + split at h + · cases h + · rename_i c _ + split at h + · cases h + · split at h + · cases h + · rename_i keeps + cases h + refine ⟨a, c, rfl, fun hopens => ?_⟩ + simp only [hopens, Bool.true_and, Bool.not_eq_true'] at keeps + exact sameVars_eq (by simpa using keeps) + +/-- A later event of a hold only appends its action and moves the context. -/ +theorem stepE_busy {env : Env} {l l' : Local} {s : Sec} {e : Ev} + (busy : l.sec = some s) (h : stepE env l none e = .ok l') + : exists a c, + l' = { l with sec := some { s with actions := s.actions ++ [a], ctx := c } } := by + unfold stepE at h + split at h + · cases h + · rename_i a _ + simp only [busy] at h + split at h + · cases h + · rename_i c _ + split at h + · cases h + · cases h + exact ⟨a, c, rfl⟩ + +theorem steps_keep {env : Env} {node : NodeID} + : forall {l f : Local} {events : List Ev} {s : Sec}, + Steps (machine env) node l events f + -> l.sec = some s + -> f.vars = l.vars + /\ exists s', + f.sec = some s' + /\ s'.head = s.head + /\ s'.recv = s.recv + /\ s'.saved = s.saved + | _, _, _, s, .nil _, busy => ⟨rfl, s, busy, rfl, rfl, rfl⟩ + | _, _, _, _, .cons step rest, busy => by + obtain ⟨_, _, hm⟩ := stepE_busy busy (toOption_ok step) + obtain ⟨hv, s', hs, h1, h2, h3⟩ := steps_keep rest (by rw [hm]) + refine ⟨by rw [hv, hm], s', hs, ?_, ?_, ?_⟩ <;> simp_all + +theorem keepsInv_inv {names : Names} {saved vars : State} + (saved_ : inv names saved = true) (h : keepsInv names saved vars = true) + : inv names vars = true := by + unfold keepsInv at h + rcases Bool.or_eq_true_iff.mp h with same | holds + · rw [sameVars_eq same]; exact saved_ + · exact holds + +/-- What a successful release establishes. -/ +theorem closeX_ok {env : Env} {others : List (NodeID × Local)} {l finish : Local} + {sends : List (CCF.Envelope NodeID Message)} {c : Ctx} + (h : closeX env others l = .ok (finish, sends, c)) + : exists s vars, + l.sec = some s + /\ runHold env s.saved s.recv s.head s.actions true = .ok c + /\ closeVars others s.head c = .ok vars + /\ genesisOk env s c vars = true + /\ keepsInv env.names s.saved vars = true + /\ baseOk vars = true + /\ ghostFree env s c = true + /\ finish = { vars } + /\ sends = c.outbox := by + unfold closeX at h + split at h + · cases h + · rename_i s found + dsimp only at h + split at h + · cases h + · rename_i c' run + split at h + · cases h + · rename_i vars cv + split at h + · rename_i ok + split at h + · rename_i holds + split at h + · rename_i based + split at h + · rename_i free + simp only [Except.ok.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl, rfl⟩ := h + exact ⟨s, vars, found, run, cv, ok, holds, based, free, rfl, rfl⟩ + · cases h + · cases h + · cases h + · cases h + +theorem expand_declared {d : State} (zero : d.base = 0) : d.declared.expand = d := by + cases d + simp only at zero + subst zero + simp [State.declared, Exec.Declared.expand] + +/-- +A released hold's outcome is a function of the saved declared state: rerun from it, with +placeholders up to the snapshot base, it releases the same declared state and sends. +-/ +theorem release_ghostFree {env : Env} {others : List (NodeID × Local)} {l finish : Local} + {sends : List (CCF.Envelope NodeID Message)} {c : Ctx} + (h : closeX env others l = .ok (finish, sends, c)) + : exists s c', + l.sec = some s + /\ runHold env s.saved.declared.expand s.recv s.head s.actions true = .ok c' + /\ c'.vars.declared = c.vars.declared + /\ c'.outbox = sends := by + obtain ⟨s, _, found, run, _, _, _, _, free, _, rfl⟩ := closeX_ok h + refine ⟨s, ?_⟩ + unfold ghostFree at free + by_cases zero : s.saved.base = 0 + · exact ⟨c, found, by rw [expand_declared zero]; exact run, rfl, rfl⟩ + · have nonzero : (s.saved.base == 0) = false := by simpa using zero + rw [nonzero, Bool.false_or] at free + split at free + · rename_i c' rerun + simp only [Bool.and_eq_true, beq_iff_eq] at free + exact ⟨c', found, rerun, free.1, free.2⟩ + · cases free + +theorem close_ok {env : Env} {others : List (NodeID × Local)} {node : NodeID} + {l finish : Local} {sends : List (CCF.Envelope NodeID Message)} + (h : (machine env).close others node l = some (finish, sends)) + : exists c, closeX env others l = .ok (finish, sends, c) := by + simp only [machine, Option.map_eq_some_iff] at h + obtain ⟨⟨l', sends', c⟩, found, eq⟩ := h + simp only [Prod.mk.injEq] at eq + obtain ⟨rfl, rfl⟩ := eq + exact ⟨c, toOption_ok found⟩ + +/-- A hold run to completion is one run of the head's handler. -/ +theorem runHold_ok {env : Env} {saved : State} {recv : Option (NodeID × Message)} + {head : Ev} {actions : List Action} {c : Ctx} + (h : runHold env saved recv head actions true = .ok c) + : isHead env saved head = true + /\ exists hd, + Exec.handlerFor head.function (recv.map fun (n, m) => (env.names.name n, m)) + = some hd + /\ Exec.run env saved actions true hd = .ok c + /\ c.queue = [] := by + unfold runHold at h + split at h + · cases h + · rename_i isHd + simp only [Bool.not_eq_true', Bool.not_eq_false] at isHd + refine ⟨by simpa using isHd, ?_⟩ + split at h + · cases h + · rename_i hd found + split at h + · rename_i c' run + split at h + · rename_i empty + cases h + exact ⟨hd, found, run, List.isEmpty_iff.mp empty⟩ + · cases h + · cases h + · cases h + +theorem closeVars_plain {others : List (NodeID × Local)} {head : Ev} + (other : head.function ≠ "init_as_backup") + : (fun c => closeVars others head c) = plainFinish others := by + funext c + unfold closeVars plainFinish + split + · simp [other] + · rfl + +theorem closeVars_join {others : List (NodeID × Local)} {head : Ev} + (join : head.function = "init_as_backup") + : (fun c => closeVars others head c) = joinFinish others := by + funext c + unfold closeVars joinFinish + split <;> simp_all + +/-- `HoldSound` with the release's own `finish`. -/ +def HoldSoundAt (env : Env) (node : NodeID) (recv : Option (NodeID × Message)) + (h : Exec.M Unit) (saved : State) (head : Ev) + : Prop := + HoldSound env node recv h saved fun others c => closeVars others head c + +theorem holdSoundAt {env : Env} {node : NodeID} {recv : Option (NodeID × Message)} + {h : Exec.M Unit} {saved : State} {head : Ev} + {finish : List (NodeID × Local) -> Ctx -> Except String State} + (same : forall others, (fun c => closeVars others head c) = finish others) + (sound : HoldSound env node recv h saved finish) + : HoldSoundAt env node recv h saved head := by + have : (fun others c => closeVars others head c) = finish := by + funext others c + exact congrFun (same others) c + unfold HoldSoundAt + rw [this] + exact sound + +/-- Every hold is one handler's hold, which its obligation covers. -/ +theorem dispatch {env : Env} (ob : Obligations env) {node : NodeID} {saved : State} + {recv : Option (NodeID × Message)} {head : Ev} {hd : Exec.M Unit} + (isHd : isHead env saved head = true) + (found + : Exec.handlerFor head.function (recv.map fun (n, m) => (env.names.name n, m)) + = some hd) + : HoldSoundAt env node recv hd saved head := by + cases recv with + | some p => + obtain ⟨source, message⟩ := p + simp only [Option.map_some, Exec.handlerFor] at found + split at found + · rename_i isRecv + cases found + have other : head.function ≠ "init_as_backup" := by + intro eq + simp [eq, Exec.recvHeads] at isRecv + apply holdSoundAt (fun others => closeVars_plain (others := others) other) + have init : initialised saved = true := by + simp only [isHead, Bool.and_eq_true, Bool.or_eq_true] at isHd + rcases isHd.1 with init | allowed + · exact init + · simp [Exec.recvHeads] at isRecv + rcases isRecv with eq | eq | eq | eq | eq <;> simp [eq, uninitialisedHeads] at allowed + cases message with + | appendEntriesRequest r => exact ob.appendEntries node source r saved + | appendEntriesResponse r => exact ob.appendEntriesResponse node source r saved + | requestVoteRequest r => exact ob.requestVote node source r saved + | requestPreVoteRequest r => exact ob.requestPreVote node source r saved + | requestVoteResponse r => exact ob.requestVoteResponse node source r saved init + | requestPreVoteResponse r => + exact ob.requestPreVoteResponse node source r saved init + | proposeRequestVoteRequest t => + exact ob.proposeRequestVote node source t saved init + · cases found + | none => + simp only [Option.map_none, Exec.handlerFor] at found + split at found + all_goals first + | (cases found; done) + | skip + all_goals (cases found) + · exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.dropPendingTo node saved) + · exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.tick node saved) + · exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.replicate node saved) + · exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.nomination node saved) + · exact holdSoundAt (fun others => closeVars_join (others := others) (by simp_all)) + (ob.initAsBackup node saved) + · rename_i fn + simp [isHead, uninitialisedHeads, opens, Exec.outOfLock, Exec.heads, Exec.recvHeads, fn] at isHd + exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.outOfLockHook node saved isHd.1 isHd.2) + · rename_i fn + simp [isHead, uninitialisedHeads, opens, Exec.outOfLock, Exec.heads, Exec.recvHeads, fn] at isHd + exact holdSoundAt (fun others => closeVars_plain (others := others) (by simp_all)) + (ob.forceBecomePrimary node saved isHd.1.1 isHd.1.2 isHd.2) + +/-! ## The refinement -/ + +/-- +A node's declared state at its last release, related to its clean state, and its snapshot +base checked (`baseOk`). +-/ +def rel (env : Env) (node : NodeID) (c : NodeState) (l : Local) : Prop := + Rel env node c l.vars /\ baseOk l.vars = true + +theorem inv_initial (names : Names) (nodeId : Exec.NodeId) (ticking : Bool) + (named : names.name (names.id nodeId) = nodeId) + : inv names { nodeId, ticking } = true := by + simp [inv, invChecks, named, signaturesIn, State.isRetiredCommitted, + Consensus.Model.Node.NodeState.isRetiredCommitted, Consensus.Model.Node.NodeState.retirement, + Consensus.Model.Node.retirementIndexInLog, abs, Consensus.Model.Node.configurationHistory, + Consensus.Model.Node.firstLogIndexAfter] + +theorem agrees_initial {env : Env} {node : NodeID} {nodeId : Exec.NodeId} {ticking : Bool} + (outside : node ∉ env.genesis) + : agrees env.names (Consensus.Model.initialNodeState env.genesis node) + { nodeId, ticking } + = true := by + have notMin : env.genesis.min? ≠ some node := by + intro isMin + exact outside (CCF.Finset.min?_mem isMin) + simp [agrees, abs, absRole, trackedPeers, Consensus.Model.initialNodeState, outside, notMin] + +theorem unnamedUnmatched_initial {genesis : CCF.Finset NodeID} {node : NodeID} + : UnnamedUnmatched node (Consensus.Model.initialNodeState genesis node) := by + intro _ _ _ _ + rfl + +theorem keyed_rel {env : Env} + : forall {others : List (NodeID × Local)} {cleanOthers : List (NodeID × NodeState)}, + Keyed (fun other local_ cleanOther => rel env other cleanOther local_) others + cleanOthers + -> Keyed (fun other local_ cleanOther => Rel env other cleanOther local_.vars) + others cleanOthers + | [], [], _ => .nil + | _ :: _, _ :: _, .cons holds rest => .cons holds.1 (keyed_rel rest) + +theorem section_sound {env : Env} (ob : Obligations env) (node : NodeID) (start : Local) + (received : Option (NodeID × Message)) (events : List Ev) (middle finish : Local) + (sends : List (CCF.Envelope NodeID Message)) (clean : NodeState) + (others : List (NodeID × Local)) (cleanOthers : List (NodeID × NodeState)) + (idle : (machine env).idle start = true) (related_ : rel env node clean start) + (recvInv + : forall source message, + received = some (source, message) + -> msgInv env.names ⟨source, node, message⟩ = true) + (run : SectionRun (machine env) node start received events middle) + (closed : (machine env).close others node middle = some (finish, sends)) + (keyed + : Keyed (fun other local_ cleanOther => rel env other cleanOther local_) others + cleanOthers) + : exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node clean (cleanActions env received inputs) clean' sends + /\ rel env node clean' finish + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall envelope, envelope ∈ sends -> msgInv env.names envelope = true := by + obtain ⟨first, rest, mid0, rfl, firstStep, later⟩ := run + have startIdle : start.sec = none := by simpa [machine, Local.idle] using idle + obtain ⟨a, c0, hmid, _⟩ := stepE_idle startIdle (toOption_ok firstStep) + obtain ⟨_, s, found, hhead, hrecv, hsaved⟩ := steps_keep later (by rw [hmid]) + simp only at hhead hrecv hsaved + obtain ⟨c, closedX⟩ := close_ok closed + obtain ⟨s', vars, found', ran, cv, genesis, inv', based, _, rfl, rfl⟩ := closeX_ok closedX + rw [found] at found' + cases found' + obtain ⟨isHd, hd, hfound, hrun, hq⟩ := runHold_ok ran + have sound := dispatch ob (node := node) isHd hfound + obtain ⟨⟨rid, rid2, rinv, rdisj, unmatched⟩, _⟩ := related_ + rw [hsaved, hrecv] at sound + rw [hsaved] at hrun + have inv' : inv env.names vars = true := keepsInv_inv (by rw [hsaved]; exact rinv) inv' + obtain ⟨nid, cond⟩ := + sound s.actions c vars others cleanOthers rid rid2 rinv recvInv + (keyed_rel keyed) hrun hq cv inv' + have vid : vars.nodeId = env.names.name node := nid.trans rid + have vid2 : env.names.id vars.nodeId = node := by rw [nid]; exact rid2 + rcases rdisj with ⟨notPristine, agreed⟩ | ⟨isPristine, rfl⟩ + · have stays : pristine env vars = false := by + have notPristine' : pristine env s.saved = false := by rw [hsaved]; exact notPristine + simpa [genesisOk, notPristine'] using genesis + obtain ⟨inputs, clean', lr, agreed', unmatched', admitted, sent⟩ := + cond clean notPristine agreed unmatched + exact ⟨ + inputs, + clean', + lr, + ⟨⟨vid, vid2, inv', Or.inl ⟨stays, agreed'⟩, unmatched'⟩, based⟩, + admitted, + sent + ⟩ + · have pristineSaved : pristine env s.saved = true := by rw [hsaved]; exact isPristine + simp only [genesisOk, pristineSaved, ite_true, Bool.and_eq_true, + Option.isNone_iff_eq_none, List.isEmpty_iff, Bool.or_eq_true] at genesis + obtain ⟨⟨noRecv, silent⟩, after⟩ := genesis + rw [hrecv] at noRecv + subst noRecv + refine ⟨ + [], + Consensus.Model.initialNodeState env.genesis node, + ?_, + ⟨⟨vid, vid2, inv', ?_, unmatched⟩, based⟩, + by intro _ member; simp at member, + ?_ + ⟩ + · rw [silent] + exact LocalRun.nil _ + · by_cases still : pristine env vars = true + · exact Or.inr ⟨still, rfl⟩ + · rcases after with stays | agreed + · exact absurd stays still + · rw [vid2] at agreed + exact Or.inl ⟨by simpa using still, agreed⟩ + · rw [silent] + intro _ member + simp at member + +/-- M_tv refines the clean node, section by section, given every handler's obligation. -/ +def refinement (env : Env) (ob : Obligations env) + : Refinement (machine env) (protocol env) admit where + msgInv envelope := msgInv env.names envelope = true + rel := rel env + init_sound node l initial := by + obtain ⟨roundTrip, genesisMin, ticking, rfl⟩ := initial + refine ⟨ + rfl, + _, + rfl, + ⟨ + rfl, + roundTrip, + inv_initial _ _ _ (by rw [roundTrip]), + ?_, + unnamedUnmatched_initial + ⟩, + rfl + ⟩ + by_cases isMin : env.genesis.min? = some node + · refine Or.inr ⟨?_, rfl⟩ + simp [pristine, initialLocal, isMin, roundTrip] + · have outside : node ∉ env.genesis := fun member => isMin (genesisMin member) + refine Or.inl ⟨?_, agrees_initial outside⟩ + simp [pristine, initialLocal, isMin, roundTrip] + section_sound := by + intro node start received events middle finish sends clean others cleanOthers idle related_ + recvInv run closed _ keyed + exact section_sound ob node start received events middle finish sends clean others + cleanOthers idle related_ recvInv run closed keyed + +/-- Idle states are `related`, as `declare` sees them. -/ +theorem factors (env : Env) (node : NodeID) (c : NodeState) (l : Local) + (h : rel env node c l) (idle : (machine env).idle l = true) + : related env.names node c (declare l).1 = true := by + have none_ : l.sec = none := by simpa [machine, Local.idle] using idle + have : (declare l).1 = l.vars.declared := by simp [declare, none_] + rw [this] + exact related_declared h.1 h.2 + +/-- A lock-taking event leaves the declared state as it was at release. -/ +theorem frame (env : Env) (node : NodeID) (l : Local) + (received : Option (NodeID × Message)) (e : Ev) (l' : Local) + (idle : (machine env).idle l = true) + (h : (machine env).step node l received e = some l') + (hopens : (machine env).opens e = true) + : forall c, + related env.names node c (declare l).1 = true + -> related env.names node c (declare l').1 = true := by + have none_ : l.sec = none := by simpa [machine, Local.idle] using idle + obtain ⟨_, _, rfl, keeps⟩ := stepE_idle none_ (toOption_ok h) + intro c hc + simpa [declare, none_, keeps hopens] using hc + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Suffix.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Suffix.lean new file mode 100644 index 000000000000..f25a5b2dcd08 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Suffix.lean @@ -0,0 +1,110 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation + +@[expose] public section + +/-! +# The declared state holds a suffix (proof, not reviewed) + +M_tv's handlers run on the whole ledger (`Exec.State`); the reviewed declared state +(`Exec.Declared`) holds the entries after the snapshot base. Given `inv` and the release +check `baseOk`, the proof relation's `agrees` on the whole ledger gives the reviewed +`Exec.Declared.agrees` of the projection `State.declared`. +-/ + +namespace Consensus.TraceValidation.Proofs + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) + +private theorem inv_lookup {names : Names} {v : State} (h : inv names v = true) + (n : String) + : ((invChecks names v).lookup n).getD true = true := by + unfold inv at h + generalize invChecks names v = l at h + induction l with + | nil => rfl + | cons x l ih => + obtain ⟨k, b⟩ := x + simp only [List.all_cons, Bool.and_eq_true] at h + simp only [List.lookup_cons] + split + · exact h.1 + · exact ih h.2 + +theorem inv_ledger {names : Names} {d : State} (h : inv names d = true) + : d.ledger.size = d.lastIdx /\ d.commitIdx <= d.lastIdx := by + have c1 := inv_lookup h "ledger_size" + have c2 := inv_lookup h "commit_le_last" + simp only [invChecks, List.lookup_cons, List.lookup_nil] at c1 c2 + simp only [String.reduceBEq, Option.getD_some, beq_iff_eq, decide_eq_true_eq] at c1 c2 + exact ⟨c1, c2⟩ + +/-- The whole clean log, after the base, is the held entries. -/ +theorem held_log {names : Names} {d : State} + : (abs names d).log.drop d.base = (d.declared.abs names).log := by + simp only [abs, Exec.Declared.abs, State.declared, Array.toList_extract, + List.extract_eq_take_drop, ← List.map_drop, List.drop_take, List.take_take] + congr 1 + rw [List.take_eq_take_iff] + simp only [List.length_drop, Array.length_toList] + omega + +theorem agrees_declared {names : Names} {c : NodeState} {d : State} + (agreed : agrees names c d = true) (size : d.ledger.size = d.lastIdx) + (ok : baseOk d = true) + : d.declared.agrees names c = true := by + simp only [baseOk, Bool.and_eq_true, decide_eq_true_eq, Bool.or_eq_true, beq_iff_eq] at ok + obtain ⟨bc, bsig⟩ := ok + have log : c.log = (abs names d).log := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at agreed + exact agreed.1.1.1.1.1.1.1.1.2 + have sig : (d.declared.base == 0 + || c.log[d.declared.base - 1]? == some { term := d.declared.baseView, content := .signature }) + = true := by + show (d.base == 0 + || c.log[d.base - 1]? == some { term := d.baseView, content := .signature }) = true + rcases bsig with zero | at_ + · simp [zero] + cases found : d.ledger[d.base - 1]? with + | none => simp [found] at at_ + | some e => + simp only [found, Option.any_some, Bool.and_eq_true, beq_iff_eq] at at_ + have lt : d.base - 1 < d.ledger.size := by + rcases Array.getElem?_eq_some_iff.mp found with ⟨lt, _⟩ + exact lt + rw [log] + simp [abs, show d.base - 1 < d.lastIdx by omega, found, absEntry, at_.1, at_.2] + have drop : (c.log.drop d.declared.base == (d.declared.abs names).log) + = (c.log == (abs names d).log) := by + rw [log, beq_self_eq_true, show d.declared.base = d.base from rfl, held_log, + beq_self_eq_true] + unfold Exec.Declared.agrees + simp only + rw [sig, drop, Bool.true_and] + have bc' : decide (d.declared.base <= d.declared.commitIdx) = true := by + simp only [decide_eq_true_eq]; exact bc + rw [bc', Bool.true_and] + exact agreed + +/-- The proof relation, with the release check `baseOk`, gives the reviewed `related`. -/ +theorem related_declared {env : Env} {node : NodeID} {c : NodeState} {d : State} + (h : Rel env node c d) (ok : baseOk d = true) + : related env.names node c d.declared = true := by + obtain ⟨_, rid, rinv, disj, _⟩ := h + obtain ⟨size, le⟩ := inv_ledger rinv + simp only [related, Bool.and_eq_true, beq_iff_eq, Bool.or_eq_true] + refine ⟨rid, ?_⟩ + rcases disj with ⟨_, agreed⟩ | ⟨isPristine, rfl⟩ + · exact Or.inl (agrees_declared agreed size ok) + · simp only [pristine, Bool.and_eq_true, beq_iff_eq] at isPristine + simp only [baseOk, Bool.and_eq_true, decide_eq_true_eq] at ok + refine Or.inr ⟨⟨isPristine.2, ?_⟩, rfl⟩ + show d.base = 0 + omega + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean new file mode 100644 index 000000000000..3fa76bcfb6b6 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean @@ -0,0 +1,144 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Validator + +@[expose] public section + +/-! +# T1: the executable validator decides the acceptance predicate (unreviewed proof) + +`certify` replays the scheduled actions with the framework's `next`; whatever the +scheduler did, a successful `validate` is a run of the event-granular network from an +initial state over the stream nodes, emitting the observations, with every lock released. +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections +open CCF.MultiNodeTransitionSystem (nodeState) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Ev) + +theorem emitsCheck_sound {env : Env} + : forall {s : GState} {actions : List GAction} {f : GState} {obs : List Obs}, + emitsCheck env s actions = some (f, obs) + -> Emits (machine env) declare s actions f obs + | s, [], f, obs, h => by + simp only [emitsCheck, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .nil s + | s, .event node e :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · rename_i s' step + split at h + · cases h + · rename_i slot found + split at h + · cases h + · rename_i f' os tail + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .event step found (emitsCheck_sound tail) + | s, .deliver x e :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · rename_i s' step + split at h + · cases h + · rename_i slot found + split at h + · cases h + · rename_i f' os tail + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .deliver step found (emitsCheck_sound tail) + | s, .release node :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · rename_i s' step + exact .release step (emitsCheck_sound h) + +theorem start_init {env : Env} {keys : List NodeID} {ticking : NodeID -> Bool} + (distinct : keys.Nodup) (initial : keys.all (initOk env) = true) + : (lift (machine env)).init (start env keys ticking) + /\ (start env keys ticking).nodes.map Prod.fst = keys := by + have hkeys : (start env keys ticking).nodes.map Prod.fst = keys := by + simp [start, List.map_map, Function.comp_def] + refine ⟨⟨by rw [hkeys]; exact distinct, rfl, ?_⟩, hkeys⟩ + intro entry member + simp only [start, List.mem_map] at member + obtain ⟨k, mem, rfl⟩ := member + have ok := List.all_eq_true.mp initial k mem + simp only [initOk, Bool.and_eq_true, beq_iff_eq, Bool.or_eq_true, Bool.not_eq_true', + decide_eq_false_iff_not] at ok + refine ⟨rfl, rfl, ok.1, fun member => ?_, ticking k, rfl⟩ + rcases ok.2 with notMember | isMin + · exact absurd member notMember + · exact isMin + +theorem certify_sound {env : Env} {keys : List NodeID} {ticking : NodeID -> Bool} + {actions : List GAction} {obs : List Obs} + (h : certify env keys ticking actions = some obs) + : Accepts (machine env) declare keys obs + /\ env.genesis.Nonempty + /\ (forall o, o ∈ obs -> Exec.consistent o.event o.declared = true) := by + unfold certify at h + split at h + · rename_i guards + obtain ⟨distinct, initial, nonempty⟩ := guards + split at h + · rename_i f os run + split at h + · rename_i released + simp only [Option.some.injEq] at h + subst h + simp only [Bool.and_eq_true] at released + obtain ⟨init, hkeys⟩ := start_init distinct initial + refine ⟨⟨start env keys ticking, actions, f, init, hkeys, emitsCheck_sound run, ?_⟩, nonempty, + fun o member => List.all_eq_true.mp released.2 o member⟩ + intro entry member + have := List.all_eq_true.mp released.1 entry member + simpa using this + · cases h + · cases h + · cases h + +/-- +**T1.** If the validator accepts, the acceptance predicate holds of its observations: a +run of M_tv's event-granular network over exactly the stream nodes, from an initial state, +emits them and releases every lock; each node's observed events are its stream, in order; +and the genesis configuration is nonempty. +-/ +theorem validate_sound {env : Env} {streams : List (NodeID × List Ev)} {v : Verdict} + (h : validate env streams = .ok v) + : Accepts (machine env) declare v.keys v.observations + /\ v.keys = streams.map Prod.fst + /\ streamsMatch streams v.observations = true + /\ env.genesis.Nonempty + /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) := by + unfold validate at h + dsimp only at h + split at h + · cases h + · rename_i w _ + unfold conclude at h + dsimp only at h + split at h + · cases h + · rename_i obs certified + split at h + · rename_i matches_ + simp only [Except.ok.injEq] at h + subst h + obtain ⟨accepts, nonempty, consistent⟩ := certify_sound certified + exact ⟨accepts, rfl, matches_, nonempty, consistent⟩ + · cases h + +end Consensus.TraceValidation.Proofs From d1f37a075a513f9d2b03388a76c77676458cfd32 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:08:57 +0000 Subject: [PATCH 09/25] Prove the lifecycle and drop obligations `init_as_backup`, `force_become_primary`, the out-of-lock snapshot hook and dropping pending messages each refine zero or one clean step. For a snapshot joiner, the ghost prefix taken from a donor's committed log satisfies the clean network's guard on `initAsBackup`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 5 +- .../Proofs/Handlers/DropPendingTo.lean | 48 ++++ .../Proofs/Handlers/ForceBecomePrimary.lean | 157 ++++++++++ .../Proofs/Handlers/InitAsBackup.lean | 267 ++++++++++++++++++ .../Proofs/Handlers/LifeNotes.lean | 248 ++++++++++++++++ .../Proofs/Handlers/OutOfLockHook.lean | 100 +++++++ 6 files changed, 824 insertions(+), 1 deletion(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/DropPendingTo.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ForceBecomePrimary.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeNotes.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/OutOfLockHook.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index be024661d108..c3ffd6505e35 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -7,7 +7,10 @@ import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks import Consensus.TraceValidation.Proofs.Handlers.AeHoare import Consensus.TraceValidation.Proofs.Handlers.AeLemmas -import Consensus.TraceValidation.Proofs.Handlers.LifeHoare +import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo +import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary +import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup +import Consensus.TraceValidation.Proofs.Handlers.OutOfLockHook import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas import Consensus.TraceValidation.Proofs.Section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/DropPendingTo.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/DropPendingTo.lean new file mode 100644 index 000000000000..ea2d45858476 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/DropPendingTo.lean @@ -0,0 +1,48 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Obligation: `drop_pending_to` (not reviewed) + +The driver's `drop_pending_to` only traces: no state change and no sends, so its clean +counterpart is the empty run. +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.TraceValidation.Exec (State Ctx Action) + +theorem run_dropPendingTo {env : Env} {saved : State} {actions : List Action} {c : Ctx} + (h : Exec.run env saved actions true Exec.dropPendingTo = .ok c) + : c.vars = saved /\ c.outbox = [] := by + cases actions with + | nil => unfold_run [Exec.dropPendingTo] at h + | cons a rest => + by_cases point : a.point = "drop_pending_to" + · unfold_run [Exec.dropPendingTo, point] at h + cases h + exact ⟨rfl, rfl⟩ + · unfold_run [Exec.dropPendingTo, point] at h + +theorem dropPendingToSound (env : Env) : DropPendingToSound env := by + intro node saved actions c vars others cleanOthers _ _ _ _ _ ran _ finished _ + obtain ⟨keeps, silent⟩ := run_dropPendingTo ran + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + rw [keeps, silent] + refine ⟨ + rfl, + fun clean _ agreed unmatched => + ⟨[], clean, ?_, agreed, unmatched, by simp, by simp⟩ + ⟩ + exact LocalRun.nil _ + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ForceBecomePrimary.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ForceBecomePrimary.lean new file mode 100644 index 000000000000..176d08d481ec --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ForceBecomePrimary.lean @@ -0,0 +1,157 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.LifeHoare + +@[expose] public section + +/-! +# Obligation: `force_become_primary` (not reviewed) + +The genesis node's untraced `force_become_primary`, opened by its `become_leader`. It starts +pristine (no ledger entry), so the clean part of the obligation is vacuous: `HoldSound` asks +for clean steps only from a non-pristine state. What remains is that the hold keeps the node +id (the machine checks `inv` at release). Throughout the hold the node has no ledger entry and nothing committed +(`ForceShape`), so `commit` never commits, `rollback` is never reached, and every state +change is the view bump, the leader role, and peer bookkeeping. +-/ + +namespace Consensus.TraceValidation.Proofs.Life + +open Consensus.Model.Node (activeConfigurations eligiblePeers) +open Consensus.TraceValidation.Exec + +/-- The genesis primary between the view bump and the end of `force_become_primary`. -/ +def ForceShape (n : NodeId) (v : State) (_ : Outbox) : Prop := + v.nodeId = n + /\ v.currentView = 2 + /\ v.lastIdx = 0 + /\ v.ledger.size = 0 + /\ v.commitIdx = 0 + /\ v.committable = [] + /\ v.views.size = 0 + /\ (v.leadership = .leader -> v.leaderId = some v.nodeId) + +/-- One step of a `ForceShape` preservation proof. -/ +macro "force_step" : tactic => + `(tactic| + first + | with_reducible exact pres_highest _ + | pres_step + | (with_reducible refine Pres.setV (fun _ _ h => ?_) + simpa [ForceShape, State.setPeer] using h) + | (with_reducible refine Tri.send fun _ _ h => ?_; simpa [ForceShape] using h) + | dsimp only) + +variable {env : Env} {n : NodeId} + +theorem force_commit (i : Nat) : Pres env (ForceShape n) (commit i) := by + unfold commit + refine Pres.getV_bind fun v o h => ?_ + obtain ⟨_, _, _, _, _, _⟩ := h + dsimp only + repeat' (first | (exfalso; omega) | force_step) + +theorem force_updateCommitGo (fuel first : Nat) (nc : Option Nat) + : Pres env (ForceShape n) (updateCommitGo first nc fuel) := by + induction fuel generalizing first nc with + | zero => unfold updateCommitGo; exact Pres.fail _ + | succ fuel ih => + unfold updateCommitGo + repeat' (first | with_reducible exact ih _ _ | force_step) + +theorem force_updateCommit : Pres env (ForceShape n) updateCommit := by + unfold updateCommit + repeat' + first + | with_reducible exact force_updateCommitGo _ _ _ + | with_reducible exact force_commit _ + | force_step + +theorem force_sendRange (to : NodeId) (s e : Nat) (ext : Bool) + : Pres env (ForceShape n) (sendAppendEntriesRange to s e ext) := by + unfold sendAppendEntriesRange + repeat' force_step + +theorem force_sendLoop (to : NodeId) (ext : Bool) (fuel s : Nat) (b : Option Nat) + : Pres env (ForceShape n) (sendAppendEntries.loop to ext fuel s b) := by + induction fuel generalizing s b with + | zero => unfold sendAppendEntries.loop; repeat' force_step + | succ fuel ih => + rw [sendAppendEntries.loop] + dsimp only + repeat' + first + | with_reducible exact ih _ _ + | with_reducible exact force_sendRange _ _ _ _ + | force_step + +theorem force_send (to : NodeId) (s : Nat) (ext : Bool) + : Pres env (ForceShape n) (sendAppendEntries to s ext) := by + unfold sendAppendEntries + repeat' (first | with_reducible exact force_sendLoop _ _ _ _ _ | force_step) + +theorem force_becomeLeader : Pres env (ForceShape n) becomeLeader := by + unfold becomeLeader + refine Pres.getV_bind fun v o h => ?_ + obtain ⟨_, _, _, _, _, _⟩ := h + dsimp only + repeat' + first + | (exfalso; omega) + | with_reducible exact force_updateCommit + | with_reducible exact force_send _ _ _ + | with_reducible exact pres_otherNodesSorted + | (with_reducible refine Pres.setV fun _ _ h => ?_ + obtain ⟨h1, h2, h3, h4, h5, h6, h7, _⟩ := h + exact ⟨h1, h2, h3, h4, h5, h6, h7, fun _ => rfl⟩) + | force_step + +/-- The pristine genesis node at view 0 with no role, as `inv` and the premises give it. -/ +def ForceStart (n : NodeId) (v : State) (_ : Outbox) : Prop := + v.nodeId = n + /\ v.currentView = 0 + /\ v.lastIdx = 0 + /\ v.ledger.size = 0 + /\ v.commitIdx = 0 + /\ v.committable = [] + /\ v.views.size = 0 + /\ v.leadership = .none + +theorem force_hold : Tri env (ForceStart n) forceBecomePrimary fun _ => ForceShape n := by + unfold forceBecomePrimary + refine Tri.bind (Q := fun _ => ForceShape n) (Tri.setV fun v _ h => ?_) fun _ => ?_ + · obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8⟩ := h + exact ⟨h1, by simp [h2], h3, h4, h5, h6, h7, fun l => by simp [h8] at l⟩ + · exact Pres.bind force_becomeLeader fun _ => Pres.ite (fun _ => Pres.pure _) fun _ => + Pres.fail _ + +end Consensus.TraceValidation.Proofs.Life + +namespace Consensus.TraceValidation.Proofs + +open Consensus.TraceValidation.Exec (State) + +theorem forceBecomePrimarySound (env : Env) : ForceBecomePrimarySound env := by + intro node saved view0 none_ pristine_ actions c vars others cleanOthers _ _ invSaved _ _ ran + _ finished _ + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have last : saved.lastIdx = 0 := by + simp only [pristine, Bool.and_eq_true, beq_iff_eq] at pristine_ + exact pristine_.2 + have start : Life.ForceStart saved.nodeId saved [] := by + simp only [inv, invChecks, List.all_cons, List.all_nil, Bool.and_true, Bool.and_eq_true] + at invSaved + obtain ⟨size, le, committable, _, _, views, _⟩ := invSaved + simp only [beq_iff_eq, decide_eq_true_eq, last, view0] at size le committable views + refine ⟨rfl, view0, last, size, by omega, ?_, by omega, none_⟩ + simpa [signaturesIn, last] using committable + have shape := Life.Tri.run Life.force_hold start ran + refine ⟨shape.1, fun clean notPristine _ _ => ?_⟩ + rw [pristine_] at notPristine + cases notPristine + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean new file mode 100644 index 000000000000..5a4605d86211 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean @@ -0,0 +1,267 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.LifeNotes + +@[expose] public section + +/-! +# Obligation: `init_as_backup` (not reviewed) + +A joiner initialising from a snapshot. The handler (`init_hold`) records the snapshot's +index and view in a note, sizes the ledger to the index and makes the node a follower in +the snapshot's view. The release (`joinFinish`) fills the ledger with a donor's committed +prefix (`fillSnapshot`), so the clean `initAsBackup` input is the abstraction of that +prefix: the donor's clean state has committed it (`admit`), and `fillSnapshot`'s checks give +the clean guard (the prefix ends at a signature) and the clean view (every entry of the +prefix is in the snapshot's view). +-/ + +namespace Consensus.TraceValidation.Proofs.Life + +open Consensus.Model.Node (NodeID) +open Consensus.TraceValidation.Exec + +/-- A joiner's `init_as_backup` hold, from `saved`, at its end. -/ +def InitPost (saved : State) (_ : Unit) (v : State) (o : Outbox) (n : List Note) : Prop := + exists index term, + n = [.initAsBackup index term] + /\ o = [] + /\ saved.leadership = .none + /\ saved.currentView = 0 + /\ saved.lastIdx = 0 + /\ ((index == 0) == (term == 0)) = true + /\ v.nodeId = saved.nodeId + /\ v.currentView = term + /\ v.lastIdx = index + /\ v.commitIdx = index + /\ v.ledger.size = index + /\ v.leadership = .follower + /\ v.leaderId = none + /\ v.isNewFollower = true + /\ v.votedFor = (if term = 0 then saved.votedFor else none) + /\ v.retiredCommittedIdx = saved.retiredCommittedIdx + +/-- Setting configurations keeps the ledger's size. -/ +theorem size_foldl {α : Type} (cs : List α) (f : Array Entry -> α -> Array Entry) + (keeps : forall l c, (f l c).size = l.size) (l : Array Entry) + : (cs.foldl f l).size = l.size := by + induction cs generalizing l with + | nil => rfl + | cons c rest ih => rw [List.foldl_cons, ih, keeps] + +/-- The `init_as_backup` handler, run to the end. -/ +theorem init_hold (env : Env) (saved : State) + : TriN env (fun v o n => v = saved /\ o = [] /\ n = []) Exec.initAsBackup + (InitPost saved) := by + unfold Exec.initAsBackup Exec.becomeAwareOfNewTerm Exec.resetVotesForMe Exec.becomeFollower + repeat' (first | trin_step | dsimp only) + rename_i _ index term v fresh iff _ _ _ _ _ _ vEnd o n h + obtain ⟨w, ⟨w1, ⟨w2, ⟨w3, ⟨⟨m, ⟨⟨e1, e2, e3⟩, e4⟩, e5⟩, e6⟩, e7⟩, e8⟩, e9⟩, e10⟩ := h + subst_vars + simp only [Bool.and_eq_true, beq_iff_eq] at fresh + obtain ⟨⟨l, cv⟩, li⟩ := fresh + refine ⟨ + index, + term, + by simp, + rfl, + l, + cv, + li, + iff, + rfl, + rfl, + rfl, + rfl, + ?_, + rfl, + rfl, + rfl, + ?_, + rfl + ⟩ + · rw [size_foldl _ _ (fun l c => by split <;> simp)] + simp + · by_cases t : term = 0 + · simp [t, cv] + · simp [t, cv, Ne.symm t] + +/-- A related entry of a keyed table. -/ +theorem keyed_mem {Node A B : Type} {R : Node -> A -> B -> Prop} + : forall {lefts : List (Node × A)} {rights : List (Node × B)}, + CCF.Sections.Keyed R lefts rights + -> forall {k : Node} {a : A}, + (k, a) ∈ lefts -> exists b, (k, b) ∈ rights /\ R k a b + | [], [], .nil, _, _, member => by cases member + | _ :: _, _ :: _, .cons holds rest, _, _, member => by + rcases List.mem_cons.mp member with head | tail + · cases head + exact ⟨_, List.mem_cons_self, holds⟩ + · obtain ⟨b, found, related⟩ := keyed_mem rest tail + exact ⟨b, List.mem_cons_of_mem _ found, related⟩ + +/-- What a successful `fillSnapshot` checked. -/ +theorem fill_ok {others : List (NodeID × Local)} {index term : Nat} {vars vars' : State} + (filled : fillSnapshot others index term vars = .ok vars') + : exists k donor, + (k, donor) ∈ others + /\ index <= donor.vars.commitIdx + /\ index <= donor.vars.ledger.size + /\ (forall e, e ∈ donor.vars.ledger.extract 0 index -> e.term = term) + /\ (index != 0 + -> ((donor.vars.ledger.extract 0 index)[index - 1]?.any (·.sig)) = true) + /\ vars' + = { + vars with + ledger := + donor.vars.ledger.extract 0 index + ++ vars.ledger.extract index vars.ledger.size + } := by + unfold fillSnapshot at filled + split at filled + · cases filled + rename_i k donor found + have member := List.mem_of_find?_eq_some found + have chosen := List.find?_some found + simp only [Bool.and_eq_true, decide_eq_true_eq] at chosen + dsimp only at filled + split at filled + · cases filled + rename_i terms + split at filled + · cases filled + rename_i sig + split at filled + · cases filled + split at filled + · cases filled + cases filled + refine ⟨k, donor, member, chosen.1, chosen.2, ?_, ?_, rfl⟩ + · intro e member + have all : (donor.vars.ledger.extract 0 index).all (·.term == term) = true := by + cases hx : (donor.vars.ledger.extract 0 index).all (·.term == term) + · rw [hx] at terms + exact absurd rfl terms + · rfl + simpa using Array.all_eq_true_iff_forall_mem.mp all e member + · intro nonzero + simpa [nonzero] using sig + +end Consensus.TraceValidation.Proofs.Life + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.Model.Node + +/-- +The clean step is `initAsBackup` of the donor's prefix: the joiner is fresh, the prefix ends +at a signature, its last entry is in the snapshot's view, and the donor has committed it. +-/ +theorem initAsBackupSound (env : Env) : InitAsBackupSound env := by + intro node saved actions c vars others cleanOthers _ _ invSaved _ keyed ran _ finished _ + obtain ⟨index, term, notes, outbox, none_, view0, last0, iff, nodeId, view, lastIdx, commitIdx, + size, role, leader, newFollower, votedFor, retired⟩ := + Life.TriN.run (Life.init_hold env saved) ⟨rfl, rfl, rfl⟩ ran + have snap : snapshotOf c = some (index, term) := by simp [snapshotOf, notes] + simp only [joinFinish, snap] at finished + obtain ⟨k, donor, member, committed, enough, terms, sig, filled⟩ := Life.fill_ok finished + subst filled + have commit0 : saved.commitIdx = 0 := by + simp only [inv, invChecks, List.all_cons, Bool.and_eq_true] at invSaved + obtain ⟨_, le, _⟩ := invSaved + simp only [decide_eq_true_eq, last0] at le + omega + generalize hpre : donor.vars.ledger.extract 0 index = pre at terms sig + have preSize : pre.size = index := by + rw [← hpre, Array.size_extract] + omega + have ledger : c.vars.ledger.extract index c.vars.ledger.size = #[] := by + simp [size] + rw [ledger, Array.append_empty] + refine ⟨nodeId, fun clean notPristine agreed _ => ?_⟩ + simp only [agrees, Bool.and_eq_true, beq_iff_eq, and_assoc] at agreed + obtain ⟨cRole, cTerm, cLog, cCommit, _, _, cVoted, _, _, _, cRetired⟩ := agreed + simp only [abs, absRole, none_, view0, last0, commit0, List.take_zero, List.map_nil] + at cRole cTerm cLog cCommit cVoted cRetired + have takeAll : pre.toList.take index = pre.toList := by + apply List.take_of_length_le + simp [preSize] + generalize hentries : pre.toList.map (absEntry env.names) = entries + have entriesLen : entries.length = index := by + rw [← hentries] + simp [preSize] + have atEnd : index ≠ 0 -> exists e, entries[index - 1]? = some (absEntry env.names e) + /\ e.term = term /\ e.sig = true := by + intro nonzero + have within : index - 1 < pre.size := by omega + refine ⟨pre[index - 1], ?_, terms _ (Array.getElem_mem within), ?_⟩ + · rw [← hentries] + simp [within] + · have := sig (by simpa using nonzero) + simpa [within] using this + have endTerm : termAt entries index = term := by + by_cases nonzero : index = 0 + · simp only [nonzero, beq_self_eq_true, beq_iff_eq] at iff + have t0 : term = 0 := beq_iff_eq.mp iff.symm + simp [termAt, entryAt?, nonzero, t0] + · obtain ⟨e, found, eTerm, _⟩ := atEnd nonzero + simp [termAt, entryAt?, nonzero, found, absEntry, eTerm] + have sigOk : entries = [] \/ isSignatureAt entries entries.length = true := by + by_cases nonzero : index = 0 + · left + rw [← List.length_eq_zero_iff, entriesLen, nonzero] + · right + obtain ⟨e, found, _, eSig⟩ := atEnd nonzero + simp [isSignatureAt, entryAt?, entriesLen, nonzero, found, absEntry, eSig, + EntryContent.isSignature] + refine ⟨[.initAsBackup entries], + becomeAwareOfNewTerm { clean with log := entries, commitIndex := index } term, + ?_, ?_, ?_, ?_, ?_⟩ + · have step := LocalRun.cons (protocol := protocol env) (node := node) (state := clean) + (middle := becomeAwareOfNewTerm { clean with log := entries, commitIndex := index } term) + (action := (protocol env).internal (.initAsBackup entries)) (effects := {}) ?_ + (LocalRun.nil _) + · simpa [cleanActions, outbox] using step + · rw [entriesLen] at sigOk + simp [protocol, Consensus.Model.protocol, Consensus.Model.Node.step, act, initAsBackup, + guard, NodeState.isFresh, cRole, cTerm, cLog, cCommit, sigOk, entriesLen, endTerm] + · by_cases t : term = 0 + · simp [agrees, abs, absRole, trackedPeers, becomeAwareOfNewTerm, role, view, lastIdx, + commitIdx, newFollower, leader, votedFor, retired, cVoted, cRetired, cTerm, t, takeAll, + hentries] + · simp [agrees, abs, absRole, trackedPeers, becomeAwareOfNewTerm, role, view, lastIdx, + commitIdx, newFollower, leader, votedFor, retired, cRetired, cTerm, t, Ne.symm t, + takeAll, hentries] + · intro primary + simp [becomeAwareOfNewTerm] at primary + · intro input inputMember + simp only [List.mem_singleton] at inputMember + subst inputMember + obtain ⟨cd, cdMember, _, _, invDonor, agreeOrPristine, _⟩ := Life.keyed_mem keyed member + simp only [inv, invChecks, List.all_cons, Bool.and_eq_true] at invDonor + obtain ⟨_, le, _⟩ := invDonor + simp only [decide_eq_true_eq] at le + simp only [admit, List.any_eq_true, Bool.and_eq_true, decide_eq_true_eq, beq_iff_eq] + refine ⟨(k, cd), cdMember, ?_⟩ + rcases agreeOrPristine with ⟨_, agreedDonor⟩ | ⟨pristineDonor, _⟩ + · simp only [agrees, Bool.and_eq_true, beq_iff_eq, and_assoc] at agreedDonor + obtain ⟨_, _, dLog, dCommit, _⟩ := agreedDonor + refine ⟨by rw [entriesLen, dCommit]; exact committed, ?_⟩ + rw [entriesLen, dLog, ← hentries, ← hpre] + simp only [abs] + rw [← List.map_take, List.take_take, Nat.min_eq_left (by omega)] + simp + · simp only [pristine, Bool.and_eq_true, beq_iff_eq] at pristineDonor + have nil : entries = [] := by + rw [← List.length_eq_zero_iff, entriesLen] + omega + simp [nil] + · intro envelope envelopeMember + rw [outbox] at envelopeMember + cases envelopeMember + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeNotes.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeNotes.lean new file mode 100644 index 000000000000..20ae1177fe54 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/LifeNotes.lean @@ -0,0 +1,248 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Monad + +@[expose] public section + +/-! +# Handler runs that also track the notes (not reviewed; lifecycle obligations) + +`TriN env P x Q` is `Life.Tri` with the hold's notes as a third component: a joiner's +release reads its snapshot from them (`snapshotOf`). The rules for primitives are in +strongest-postcondition form, so a straight-line handler is walked by `trin_step` and only +the last `setV` needs its postcondition proved. +-/ + +namespace Consensus.TraceValidation.Proofs.Life + +open Consensus.TraceValidation.Exec + +/-- A Hoare triple over handler runs that sees the declared state, outbox and notes. -/ +def TriN {α : Type} (env : Env) (P : State -> Outbox -> List Note -> Prop) (x : M α) + (Q : α -> State -> Outbox -> List Note -> Prop) + : Prop := + forall (c : Ctx) (a : α) (c' : Ctx), + c.env = env + -> P c.vars c.outbox c.notes + -> x.run c = .ok (a, c') + -> c'.env = env /\ Q a c'.vars c'.outbox c'.notes + +/-- `x` leaves the notes alone. -/ +def NotesKeep {α : Type} (x : M α) : Prop := + forall (c : Ctx) (a : α) (c' : Ctx), x.run c = .ok (a, c') -> c'.notes = c.notes + +namespace NotesKeep + +theorem bind {α β : Type} {x : M α} {f : α -> M β} (hx : NotesKeep x) + (hf : forall a, NotesKeep (f a)) + : NotesKeep (x >>= f) := by + intro c b c'' h + simp only [StateT.run, Bind.bind, StateT.bind, Except.bind] at h + split at h + · cases h + · rename_i r found + obtain ⟨a, c'⟩ := r + exact (hf a c' b c'' h).trans (hx c a c' found) + +theorem pure {α : Type} (a : α) : NotesKeep (Pure.pure a : M α) := by + intro c b c' h + simp only [Pure.pure, StateT.run, StateT.pure, Except.pure, Except.ok.injEq, + Prod.mk.injEq] at h + obtain ⟨_, rfl⟩ := h + rfl + +theorem fail {α : Type} (msg : String) : NotesKeep (Exec.fail msg : M α) := by + intro c a c' h + simp [Exec.fail, throw, throwThe, MonadExceptOf.throw, StateT.lift, StateT.run, + Bind.bind, Except.bind] at h + +theorem yieldAtPoint : NotesKeep Exec.yieldAtPoint := by + intro c a c' h + simp only [Exec.yieldAtPoint] at h + prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + rfl + +theorem trace (fn : String) : NotesKeep (Exec.trace fn) := by + refine bind yieldAtPoint fun _ => ?_ + intro c a c' h + prim_cases + rcases hq : c.queue with _ | ⟨x, rest⟩ <;> simp only [hq] at h <;> prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + rfl + +theorem getV : NotesKeep Exec.getV := by + intro c a c' h + simp only [Exec.getV] at h + prim_cases + obtain ⟨_, rfl⟩ := h + rfl + +theorem setV (f : State -> State) : NotesKeep (Exec.setV f) := by + refine bind yieldAtPoint fun _ => ?_ + intro c a c' h + simp only [_root_.modify, modifyGet] at h + prim_cases + obtain ⟨_, rfl⟩ := h + rfl + +theorem curLoc : NotesKeep Exec.curLoc := by + intro c a c' h + simp only [Exec.curLoc] at h + prim_cases + rcases hq : c.cur with _ | x <;> simp only [hq] at h <;> prim_cases + all_goals + obtain ⟨_, rfl⟩ := h + rfl + +theorem liftE {α : Type} (x : Except String α) : NotesKeep (Exec.liftE x) := by + unfold Exec.liftE + split + · exact pure _ + · exact bind curLoc fun _ => fail _ + +theorem use (k : String) : NotesKeep (Exec.use k) := by + intro c a c' h + simp only [Exec.use] at h + prim_cases + generalize c.cur = cur at h + cases cur with + | none => + simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, Exec.fail, Functor.map, + Except.map] at h + | some act => + simp only at h + generalize List.lookup k act.inputs = found at h + cases found with + | none => + simp [throw, throwThe, MonadExceptOf.throw, StateT.lift, Exec.fail, Functor.map, + Except.map] at h + | some j => + simp only [StateT.pure] at h + obtain ⟨_, rfl⟩ := h + rfl + +theorem inNat (k : String) : NotesKeep (Exec.inNat k) := + bind (use k) fun _ => liftE _ + +end NotesKeep + +namespace TriN + +variable {env : Env} {α β : Type} + +theorem bind {x : M α} {f : α -> M β} {P : State -> Outbox -> List Note -> Prop} + {Q : α -> State -> Outbox -> List Note -> Prop} + {R : β -> State -> Outbox -> List Note -> Prop} + (hx : TriN env P x Q) (hf : forall a, TriN env (Q a) (f a) R) + : TriN env P (x >>= f) R := by + intro c b c'' e p h + simp only [StateT.run, Bind.bind, StateT.bind, Except.bind] at h + split at h + · cases h + · rename_i r found + obtain ⟨a, c'⟩ := r + obtain ⟨e', q⟩ := hx c a c' e p found + exact hf a c' b c'' e' q h + +/-- A primitive that keeps the declared state, outbox and notes. -/ +theorem keeps {x : M α} {P : State -> Outbox -> List Note -> Prop} (k : Spec.Keeps env x) + (n : NotesKeep x) + : TriN env P x fun _ => P := by + intro c a c' e p r + obtain ⟨e', rv, ro⟩ := k c a c' e r + refine ⟨e', ?_⟩ + rw [rv, ro, n c a c' r] + exact p + +theorem getV {P : State -> Outbox -> List Note -> Prop} + : TriN env P Exec.getV fun a v o n => P v o n /\ a = v := by + intro c a c' e p r + obtain ⟨e', ra, rv, ro⟩ := Spec.getV c a c' e r + refine ⟨e', ?_⟩ + rw [rv, ro, NotesKeep.getV c a c' r, ra] + exact ⟨p, rfl⟩ + +theorem setV {f : State -> State} {P : State -> Outbox -> List Note -> Prop} + : TriN env P (Exec.setV f) fun _ v o n => exists w, P w o n /\ v = f w := by + intro c a c' e p r + obtain ⟨e', rv, ro⟩ := Spec.setV f c a c' e r + refine ⟨e', c.vars, ?_, rv⟩ + rw [ro, NotesKeep.setV f c a c' r] + exact p + +/-- The last write of a handler: prove the postcondition. -/ +theorem setV_last {f : State -> State} {P : State -> Outbox -> List Note -> Prop} + {Q : Unit -> State -> Outbox -> List Note -> Prop} + (h : forall v o n, P v o n -> Q () (f v) o n) + : TriN env P (Exec.setV f) Q := by + intro c a c' e p r + obtain ⟨e', rv, ro⟩ := Spec.setV f c a c' e r + refine ⟨e', ?_⟩ + rw [rv, ro, NotesKeep.setV f c a c' r] + exact h _ _ _ p + +theorem note (nt : Note) {P : State -> Outbox -> List Note -> Prop} + : TriN env P (Exec.note nt) fun _ v o n => exists m, P v o m /\ n = m ++ [nt] := by + intro c a c' e p r + obtain ⟨e', rv, ro⟩ := Spec.note nt c a c' e r + refine ⟨e', ?_⟩ + simp only [Exec.note, _root_.modify, modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, + StateT.run] at r + obtain ⟨_, rfl⟩ := r + rw [rv, ro] + exact ⟨c.notes, p, rfl⟩ + +theorem fail_bind {f : α -> M β} {P : State -> Outbox -> List Note -> Prop} + {Q : β -> State -> Outbox -> List Note -> Prop} (msg : String) + : TriN env P (Exec.fail msg >>= f) Q := by + intro c a c' _ _ r + simp [Exec.fail, throw, throwThe, MonadExceptOf.throw, StateT.lift, StateT.run, + Bind.bind, StateT.bind, Except.bind] at r + +theorem ite {b : Prop} [Decidable b] {x y : M α} + {P : State -> Outbox -> List Note -> Prop} + {Q : α -> State -> Outbox -> List Note -> Prop} (hx : b -> TriN env P x Q) + (hy : Not b -> TriN env P y Q) + : TriN env P (if b then x else y) Q := by + by_cases hb : b + · simpa [hb] using hx hb + · simpa [hb] using hy hb + +/-- Any run: what `TriN` says holds of a hold's result. -/ +theorem run {x : M Unit} {P : State -> Outbox -> List Note -> Prop} + {Q : Unit -> State -> Outbox -> List Note -> Prop} (t : TriN env P x Q) {vars : State} + {queue : List Action} {final : Bool} {c : Ctx} (pre : P vars [] []) + (h : Exec.run env vars queue final x = .ok c) + : Q () c.vars c.outbox c.notes := by + unfold Exec.run at h + split at h + · rename_i c'' found + cases h + exact (t _ _ _ rfl pre found).2 + · cases h + +end TriN + +/-- One step of a straight-line `TriN` proof: control, then primitives. -/ +macro "trin_step" : tactic => + `(tactic| + first + | with_reducible exact TriN.fail_bind _ + | with_reducible refine TriN.bind (Q := ?_) ?_ (fun _ => ?_) + | with_reducible refine TriN.ite (fun _ => ?_) (fun _ => ?_) + | with_reducible exact TriN.keeps (Spec.trace _) (NotesKeep.trace _) + | with_reducible exact TriN.keeps (Spec.inNat _) (NotesKeep.inNat _) + | with_reducible exact TriN.keeps Spec.curLoc NotesKeep.curLoc + | with_reducible exact TriN.getV + | with_reducible exact TriN.note _ + | with_reducible exact TriN.setV + | with_reducible refine TriN.setV_last (fun _ _ _ _ => ?_)) + +end Consensus.TraceValidation.Proofs.Life diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/OutOfLockHook.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/OutOfLockHook.lean new file mode 100644 index 000000000000..8c8a46d23831 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/OutOfLockHook.lean @@ -0,0 +1,100 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.LifeHoare + +@[expose] public section + +/-! +# Obligation: the out-of-lock `add_configuration` hook (not reviewed) + +A joiner installing a snapshot runs the snapshot's configuration hooks outside the consensus +lock, before `init_as_backup`, with no role and at view 0. The hook only touches the +configuration bookkeeping (`configurations`, `all_other_nodes`, and the retirement fields +`retired`, `retirement_phase`, `retirement_idx`), and sends nothing since the node is not +primary (`OolShape`). `agrees` reads none of these fields of a node that is not primary, so +the clean state agrees before and after: the hold is matched by no clean step. +-/ + +namespace Consensus.TraceValidation.Proofs.Life + +open Consensus.Model.Node (activeConfigurations eligiblePeers) +open Consensus.TraceValidation.Exec + +/-- `s` with only its configuration bookkeeping changed, and nothing sent. -/ +def OolShape (s : State) (v : State) (o : Outbox) : Prop := + o = [] + /\ exists configurations allOtherNodes retired retirementPhase retirementIdx, + v + = { s with configurations, allOtherNodes, retired, retirementPhase, retirementIdx } + +/-- One step of an `OolShape` preservation proof. -/ +macro "ool_step" : tactic => + `(tactic| + first + | pres_step + | (with_reducible refine Pres.setV (fun _ _ h => ?_) + obtain ⟨o, _, _, _, _, _, e⟩ := h + subst e + exact ⟨o, _, _, _, _, _, rfl⟩) + | dsimp only) + +variable {env : Env} {s : State} + +theorem ool_becomeRetired (idx : Nat) + : Pres env (OolShape s) (becomeRetired idx .ordered) := by + unfold becomeRetired + dsimp only + repeat' ool_step + +theorem ool_createAndRemoveNodeState (none_ : s.leadership = .none) + : Pres env (OolShape s) createAndRemoveNodeState := by + unfold createAndRemoveNodeState + repeat' + first + | (exfalso; simp_all; done) + | (with_reducible refine Pres.getV_bind fun _ _ h => ?_ + obtain ⟨_, _, _, _, _, _, e⟩ := h + subst e) + | ool_step + +theorem ool_addConfiguration (none_ : s.leadership = .none) (idx? : Option Nat) + (expected : Option Nodes) + : Pres env (OolShape s) (addConfiguration idx? expected) := by + unfold addConfiguration + repeat' + first + | with_reducible exact ool_becomeRetired _ + | with_reducible exact ool_createAndRemoveNodeState none_ + | ool_step + +theorem ool_hold (none_ : s.leadership = .none) + : Pres env (OolShape s) outOfLockHook := by + unfold outOfLockHook + exact Tri.discard (ool_addConfiguration none_ none none) + +end Consensus.TraceValidation.Proofs.Life + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.TraceValidation.Exec (State) + +theorem outOfLockHookSound (env : Env) : OutOfLockHookSound env := by + intro node saved none_ view0 actions c vars others cleanOthers _ _ _ _ _ ran _ + finished _ + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have start : Life.OolShape saved saved [] := ⟨rfl, _, _, _, _, _, rfl⟩ + obtain ⟨silent, cs, aon, r, rp, ri, shape⟩ := Life.Tri.run (Life.ool_hold none_) start ran + rw [silent, shape] + refine ⟨ + rfl, + fun clean _ agreed unmatched => + ⟨[], clean, LocalRun.nil _, ?_, unmatched, by simp, by simp⟩ + ⟩ + simpa [agrees, abs, trackedPeers, none_] using agreed + +end Consensus.TraceValidation.Proofs From a0e30eaf8d5957362071913bcb068356d04d0bb8 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:04 +0000 Subject: [PATCH 10/25] Prove the AppendEntries obligation A follower's `recv_append_entries` (term check, previous-index check, conflict scan and rollback, append, commit and response) refines the clean `receiveAppendEntries` step, keeping the invariant and the relation, with every sent message satisfying the message invariant. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 3 +- .../Proofs/Handlers/AeAgree.lean | 451 ++++++++++++++ .../Proofs/Handlers/AeClean.lean | 491 +++++++++++++++ .../Proofs/Handlers/AeCommit.lean | 514 ++++++++++++++++ .../Proofs/Handlers/AeExec.lean | 570 ++++++++++++++++++ .../Proofs/Handlers/AeFrame.lean | 204 +++++++ .../Proofs/Handlers/AeMatch.lean | 244 ++++++++ .../Proofs/Handlers/AeRecv.lean | 298 +++++++++ .../Proofs/Handlers/AeScan.lean | 525 ++++++++++++++++ .../Proofs/Handlers/AppendEntries.lean | 239 ++++++++ 10 files changed, 3537 insertions(+), 2 deletions(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeAgree.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeClean.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeCommit.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeExec.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeMatch.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRecv.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeScan.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntries.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index c3ffd6505e35..8c5f6bdffaaa 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -5,8 +5,7 @@ public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks -import Consensus.TraceValidation.Proofs.Handlers.AeHoare -import Consensus.TraceValidation.Proofs.Handlers.AeLemmas +import Consensus.TraceValidation.Proofs.Handlers.AppendEntries import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeAgree.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeAgree.lean new file mode 100644 index 000000000000..53614ed34457 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeAgree.lean @@ -0,0 +1,451 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRecv + +@[expose] public section + +/-! +# The clean AppendEntries handler and its agreement with the term phase (not reviewed) + +`clean_ae` reduces the clean step to `handleAppendEntriesRequest` after `updateTerm`; +`handle_nack`, `handle_silent` and `handle_accept` give its three ends from `cleanMid`. +`cleanMid_agrees` relates `cleanMid` to the program's `aeMid`, and `ae_msg` unpacks `msgInv` +of the request. `accept_agrees` closes the accepting path: the clean handler, run on the cut +state `cutClean`, answers with the program's ACK and agrees with its end state. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) + +/-- The clean state after the term phase of `handleAppendEntriesRequest`. -/ +def cleanMid (s : NodeState) (r : AppendEntriesRequest) : NodeState := + if r.term = s.currentTerm /\ (s.role = .candidate \/ s.role = .preVoteCandidate) then + becomeAwareOfNewTerm s r.term + else + s + +def aerMsg (term idx : Nat) (ok : Bool) : Message := + .appendEntriesResponse { term := term, success := ok, lastLogIndex := idx } + +theorem clean_ae (node source : NodeID) (clean : NodeState) (r : AppendEntriesRequest) + : (Consensus.Model.Node.step (CCF.Capabilities.record node) node clean + (.receive source (.appendEntriesRequest r))).run + {} + = (handleAppendEntriesRequest (CCF.Capabilities.record node) node source + (updateTerm clean r.term) r).run + {} := by + simp [Consensus.Model.Node.step, Model.Node.receive, observeTerm, Message.term] + +theorem handle_nack (node source : NodeID) (s : NodeState) (r : AppendEntriesRequest) + (h + : r.term < (cleanMid s r).currentTerm + \/ Not (appendEntryMatchesLog (cleanMid s r) r)) + : (handleAppendEntriesRequest (CCF.Capabilities.record node) node source s r).run {} + = some + ( + cleanMid s r, + { + outgoing := + [⟨ + node, + source, + if r.term < (cleanMid s r).currentTerm + \/ termAt (cleanMid s r).log r.prevLogIndex = 0 then + aerMsg (cleanMid s r).currentTerm (cleanMid s r).log.length false + else + aerMsg + (termAt (cleanMid s r).log + (findHighestPossibleMatch (cleanMid s r).log r.prevLogIndex + r.prevLogTerm)) + (findHighestPossibleMatch (cleanMid s r).log r.prevLogIndex + r.prevLogTerm) + false + ⟩] + } + ) := by + unfold handleAppendEntriesRequest + rw [show (if r.term = s.currentTerm /\ (s.role = .candidate \/ s.role = .preVoteCandidate) then + becomeAwareOfNewTerm s r.term else s) = cleanMid s r from rfl] + generalize cleanMid s r = m at * + dsimp only + simp only [h, ↓reduceIte] + split <;> simp [CCF.Capabilities.record, aerMsg, *] + +theorem handle_silent (node source : NodeID) (s : NodeState) (r : AppendEntriesRequest) + (h1 : Not (r.term < (cleanMid s r).currentTerm)) + (h2 : appendEntryMatchesLog (cleanMid s r) r) + (h3 + : r.prevLogIndex < (cleanMid s r).commitIndex + \/ ((firstTermConflictIndex (cleanMid s r) r).isSome + /\ !(cleanMid s r).isNewFollower)) + : (handleAppendEntriesRequest (CCF.Capabilities.record node) node source s r).run {} + = some ({ cleanMid s r with primaryKnown := true }, {}) := by + unfold handleAppendEntriesRequest + rw [show (if r.term = s.currentTerm /\ (s.role = .candidate \/ s.role = .preVoteCandidate) then + becomeAwareOfNewTerm s r.term else s) = cleanMid s r from rfl] + generalize cleanMid s r = m at * + have hf : firstTermConflictIndex { m with primaryKnown := true } r + = firstTermConflictIndex m r := rfl + have hn : Not (r.term < m.currentTerm \/ Not (appendEntryMatchesLog m r)) := by + simp only [not_or, Decidable.not_not]; exact ⟨h1, h2⟩ + dsimp only + simp only [hn, ↓reduceIte, hf, h3] + rfl + +/-- The clean state the accept path hands to `handleAppendEntiresFromPrimary`. -/ +def cutClean (m : NodeState) (K : Option Nat) : NodeState := + match K with + | none => { m with primaryKnown := true } + | some index => + { + m with + primaryKnown := true, log := m.log.take (index - 1), isNewFollower := false + } + +theorem handle_accept (node source : NodeID) (s : NodeState) (r : AppendEntriesRequest) + (h1 : Not (r.term < (cleanMid s r).currentTerm)) + (h2 : appendEntryMatchesLog (cleanMid s r) r) + (h3 + : Not + (r.prevLogIndex < (cleanMid s r).commitIndex + \/ ((firstTermConflictIndex (cleanMid s r) r).isSome + /\ !(cleanMid s r).isNewFollower))) + : (handleAppendEntriesRequest (CCF.Capabilities.record node) node source s r).run {} + = some + ( + (handleAppendEntiresFromPrimary node + (cutClean (cleanMid s r) (firstTermConflictIndex (cleanMid s r) r)) r).1, + { + outgoing := + [⟨ + node, + source, + .appendEntriesResponse + (handleAppendEntiresFromPrimary node + (cutClean (cleanMid s r) (firstTermConflictIndex (cleanMid s r) r)) + r).2 + ⟩] + } + ) := by + unfold handleAppendEntriesRequest + rw [show (if r.term = s.currentTerm /\ (s.role = .candidate \/ s.role = .preVoteCandidate) then + becomeAwareOfNewTerm s r.term else s) = cleanMid s r from rfl] + generalize cleanMid s r = m at * + have hf : firstTermConflictIndex { m with primaryKnown := true } r + = firstTermConflictIndex m r := rfl + have hn : Not (r.term < m.currentTerm \/ Not (appendEntryMatchesLog m r)) := by + simp only [not_or, Decidable.not_not]; exact ⟨h1, h2⟩ + dsimp only + simp only [hn, ↓reduceIte, hf, h3] + cases firstTermConflictIndex m r <;> simp [CCF.Capabilities.record, cutClean] + +theorem agrees_role {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.role = absRole d.leadership := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + exact h.1.1.1.1.1.1.1.1.1.1 + +theorem agrees_rci {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.retiredCommittedIndex = d.retiredCommittedIdx + /\ c.commitIndex = d.commitIdx + /\ c.isNewFollower = d.isNewFollower := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + exact ⟨h.2, h.1.1.1.1.1.1.1.2, h.1.1.1.1.1.2⟩ + +theorem aeMid_role (r : AppendEntriesRequest) (v : State) + (h : Not (v.currentView > r.term)) + : (aeMid r v).leadership ≠ .candidate + /\ (aeMid r v).leadership ≠ .preVoteCandidate := by + unfold aeMid + split + · exact ⟨by simp [bant], by simp [bant]⟩ + · rename_i hb + split + · exact ⟨by simp [bant], by simp [bant]⟩ + · have : v.currentView = r.term := by omega + simp only [this, beq_self_eq_true, Bool.true_and, Bool.or_eq_true, beq_iff_eq] at hb + exact ⟨fun e => hb (Or.inl e), fun e => hb (Or.inr e)⟩ + +theorem cleanMid_agrees {names : Names} {clean : NodeState} {d : State} + {r : AppendEntriesRequest} (h : agrees names clean d = true) + (hns : Not (d.currentView > r.term)) + : agrees names (cleanMid (updateTerm clean r.term) r) (aeMid r d) = true := by + obtain ⟨hterm, -⟩ := agrees_term_log h + have hrole := agrees_role h + unfold aeMid + split + · rename_i hb + simp only [Bool.and_eq_true, beq_iff_eq, Bool.or_eq_true] at hb + have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + have hc : cleanMid clean r = Model.Node.becomeAwareOfNewTerm clean r.term := by + have c : r.term = clean.currentTerm + /\ (clean.role = .candidate \/ clean.role = .preVoteCandidate) := by + refine ⟨by omega, ?_⟩ + rcases hb.2 with e | e <;> simp [hrole, e, absRole] + unfold cleanMid + exact ite_eq_left c + rw [hu, hc] + exact agrees_bant _ h + · rename_i hb + split + · have hu : updateTerm clean r.term = Model.Node.becomeAwareOfNewTerm clean r.term := + updateTerm_of_lt (by omega) + have hc : cleanMid (Model.Node.becomeAwareOfNewTerm clean r.term) r + = Model.Node.becomeAwareOfNewTerm clean r.term := by + unfold cleanMid + simp [Model.Node.becomeAwareOfNewTerm] + rw [hu, hc] + exact agrees_bant _ h + · have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + have hv : d.currentView = r.term := by omega + have hc : cleanMid clean r = clean := by + have c : Not (r.term = clean.currentTerm + /\ (clean.role = .candidate \/ clean.role = .preVoteCandidate)) := by + simp only [hv, beq_self_eq_true, Bool.true_and, Bool.or_eq_true, beq_iff_eq] at hb + rw [hrole] + intro ⟨_, e⟩ + apply hb + cases hl : d.leadership <;> rw [hl] at e <;> simp [absRole] at e <;> simp + unfold cleanMid + simp only [c, ↓reduceIte] + rw [hu, hc] + exact h + +theorem agrees_known {names : Names} {c : NodeState} {d : State} (x : Exec.NodeId) + (h : agrees names c d = true) + : agrees names { c with primaryKnown := true } { d with leaderId := some x } + = true := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, -⟩, h9⟩, h10⟩, h11⟩ := h + exact ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, rfl⟩, h9⟩, h10⟩, h11⟩ + +theorem unmatched_of_role {node : NodeID} {c : NodeState} (h : c.role ≠ .primary) + : UnnamedUnmatched node c := + fun p => absurd p h + +theorem absRole_ne_primary {l : Exec.Leadership} (h : l ≠ .leader) + : absRole l ≠ .primary := by + cases l <;> simp_all [absRole] + +theorem aeMid_getTerm (r : AppendEntriesRequest) (v : State) + : (aeMid r v).getTerm = v.getTerm := by + unfold aeMid + split + · rfl + · split <;> rfl + +theorem abs_aeMid_log (names : Names) (r : AppendEntriesRequest) (v : State) + : (abs names (aeMid r v)).log = (abs names v).log := by + unfold aeMid + split + · rfl + · split <;> rfl + +theorem ae_msg {env : Env} {source node : NodeID} {r : AppendEntriesRequest} + (h : msgInv env.names ⟨source, node, .appendEntriesRequest r⟩ = true) + : (forall e, + e ∈ r.entries -> e.term = Exec.aeTermOfIdx r /\ 0 < e.term /\ e.term <= r.term) + /\ (r.prevLogIndex = 0 \/ 0 < r.prevLogTerm) + /\ r.entries.map (fun e => absEntry env.names (Exec.toExecEntry env e)) + = r.entries := by + simp only [msgInv, Bool.and_eq_true, List.all_eq_true] at h + obtain ⟨⟨⟨-, hn⟩, ht, hp⟩, hq⟩ := h + refine ⟨fun e he => ?_, ?_, ?_⟩ + · have := ht e he + simp only [beq_iff_eq, decide_eq_true_eq] at this + obtain ⟨⟨h1, h2⟩, h3⟩ := this + refine ⟨?_, h2, h3⟩ + simp only [Exec.aeTermOfIdx, ← h1, Option.getD_some] + · simpa [Bool.or_eq_true, beq_iff_eq] using hp + · conv => rhs; rw [← List.map_id r.entries] + exact List.map_congr_left fun e he => absEntry_toExecEntry env e (hq e he) (List.all_eq_true.mpr (hn e he)) + +theorem inv_rci {names : Names} {d : State} (h : inv names d = true) + : d.retiredCommittedIdx = firstConf (names.id d.nodeId) (abs names d).log d.commitIdx + /\ forall j, + d.retiredCommittedIdx = some j + -> (retirementIndexInLog (names.id d.nodeId) + ((abs names d).log.take j)).isSome := by + refine ⟨?_, ?_⟩ + · have hc : d.retiredCommittedIdx + = firstLogIndexAfter ((abs names d).log.take d.commitIdx) 0 + fun c => decide (names.id d.nodeId ∈ c.metadata.retirementConfirmations) := by + inv_conj h "rci_first" + exact hc + · intro j hj + have hc : d.retiredCommittedIdx.all + (fun j => (retirementIndexInLog (names.id d.nodeId) ((abs names d).log.take j)).isSome) + = true := by + inv_conj h "rci_retired" + rw [hj] at hc + simpa using hc + +/-! ## The accepting path -/ + +theorem abs_log_length {names : Names} {d : State} (h : d.ledger.size = d.lastIdx) + : (abs names d).log.length = d.lastIdx := by + simp [abs, h] + +theorem cutClean_eq (m : NodeState) (U : State) (K : Option Nat) + (hl : m.log.length = U.lastIdx) + : (cutClean m K).log = m.log.take (cutOf U K) + /\ (cutClean m K).isNewFollower = (if K.isSome then false else m.isNewFollower) + /\ (cutClean m K).role = m.role + /\ (cutClean m K).currentTerm = m.currentTerm + /\ (cutClean m K).commitIndex = m.commitIndex + /\ (cutClean m K).retiredCommittedIndex = m.retiredCommittedIndex + /\ (cutClean m K).votedFor = m.votedFor + /\ (cutClean m K).primaryKnown = true := by + cases K with + | none => simp [cutClean, cutOf, ← hl] + | some k => simp [cutClean, cutOf] + +theorem firstConf_take {node : NodeID} {L : List Entry} {c k : Nat} (h : c <= k) + : firstConf node (L.take k) c = firstConf node L c := by + unfold firstConf + rw [List.take_take, Nat.min_eq_left h] + +theorem accept_agrees (env : Env) (from_ : Exec.NodeId) (r : AppendEntriesRequest) + (saved vars : State) (K : Option Nat) (cm : NodeState) + (invSaved : inv env.names saved = true) (invVars : inv env.names vars = true) + (hcm : agrees env.names { cm with primaryKnown := true } (aeU from_ r saved) = true) + (hns : Not (saved.currentView > r.term)) + (hP : r.prevLogIndex <= saved.lastIdx) (hci : saved.commitIdx <= r.prevLogIndex) + (hK + : ConflictSpec (aeU from_ r saved) r.prevLogIndex r.entries.length + (Exec.aeTermOfIdx r) K) + (hrt + : r.entries.map (fun e => absEntry env.names (Exec.toExecEntry env e)) = r.entries) + (hg + : GN + (aePar env.names from_ r ((r.entries.map (Exec.toExecEntry env)).toArray) + (aeU from_ r saved) K) + (aePar env.names from_ r ((r.entries.map (Exec.toExecEntry env)).toArray) + (aeU from_ r saved) K).lx.length + (core vars)) + (hbd + : vars.commitIdx + = (aePar env.names from_ r ((r.entries.map (Exec.toExecEntry env)).toArray) + (aeU from_ r saved) K).bd) + : (handleAppendEntiresFromPrimary (env.names.id saved.nodeId) (cutClean cm K) r).2 + = { term := vars.currentView, success := true, lastLogIndex := Exec.aeIdx r } + /\ agrees env.names + (handleAppendEntiresFromPrimary (env.names.id saved.nodeId) (cutClean cm K) + r).1 vars + = true := by + generalize hU : aeU from_ r saved = U at * + obtain ⟨hlI, hled, -, hciU, -, -, hnid, hrciU⟩ := aeMid_frame r saved + have hUl : U.lastIdx = saved.lastIdx := by rw [← hU]; exact hlI + have hUled : U.ledger = saved.ledger := by rw [← hU]; exact hled + have hUci : U.commitIdx = saved.commitIdx := by rw [← hU]; exact hciU + have hUnid : U.nodeId = saved.nodeId := by rw [← hU]; exact hnid + have hUrci : U.retiredCommittedIdx = saved.retiredCommittedIdx := by rw [← hU]; exact hrciU + have hUabs : (abs env.names U).log = (abs env.names saved).log := by + rw [← hU]; exact abs_aeMid_log env.names r saved + obtain ⟨hsz, -⟩ := inv_parts invSaved + obtain ⟨hterm, hlog⟩ := agrees_term_log hcm + obtain ⟨hrci, hcci, hnf⟩ := agrees_rci hcm + simp only at hterm hlog hrci hcci hnf + rw [hUabs] at hlog + have hl : cm.log.length = U.lastIdx := by rw [hlog, abs_log_length hsz, hUl] + obtain ⟨htl, htnf, htrole, htterm, htci, htrci, htvf, htpk⟩ := cutClean_eq cm U K hl + have ⟨hc1, hc2⟩ := cutOf_le (U := U) (by omega) hK + generalize hcut : cutOf U K = cut at * + have htl' : (cutClean cm K).log = (abs env.names saved).log.take cut := by rw [htl, hlog] + have htlen : (cutClean cm K).log.length = cut := by + rw [htl', List.length_take, abs_log_length hsz]; omega + obtain ⟨g, hlen⟩ := hg + have gnid := g.nodeId + have gled := g.ledger + have gview := g.view + have gnf := g.nf + have gd := g.d + have gnl := g.nl + simp only [core, aePar] at gnid gled gview gnf gd hlen gnl + rw [hcut] at gled hlen + have habs : (abs env.names vars).log + = (cutClean cm K).log ++ r.entries.drop (cut - r.prevLogIndex) := by + show (vars.ledger.toList.take vars.lastIdx).map _ = _ + rw [gled, hlen, List.take_take, Nat.min_self, List.take_length, List.map_append, htl'] + congr 1 + · have e : U.ledger.toList = saved.ledger.toList := by rw [hUled] + rw [e] + show _ = ((saved.ledger.toList.take saved.lastIdx).map _).take cut + rw [← List.map_take, List.take_take, Nat.min_eq_left (by omega)] + · conv => rhs; rw [← hrt] + rw [← List.map_drop, List.map_map, List.map_drop] + rfl + have hlx : (abs env.names vars).log + = (aePar env.names from_ r ((r.entries.map (Exec.toExecEntry env)).toArray) U K).lx.map + (absEntry env.names) := by + show (vars.ledger.toList.take vars.lastIdx).map _ = _ + rw [gled, hlen, List.take_take, Nat.min_self, List.take_length] + simp only [aePar, hcut] + have hciV : vars.commitIdx = max (cutClean cm K).commitIndex + (maxCommittableIndexUpTo (abs env.names vars).log + (min r.primaryCommit (r.prevLogIndex + r.entries.length))) := by + rw [hbd, hlx, htci, hcci] + rfl + obtain ⟨hrV, hrR⟩ := inv_rci invVars + rw [show vars.nodeId = saved.nodeId by rw [gnid, hUnid]] at hrV hrR + obtain ⟨hrS, -⟩ := inv_rci invSaved + have hs : (cutClean cm K).retiredCommittedIndex + = firstConf (env.names.id saved.nodeId) (cutClean cm K).log (cutClean cm K).commitIndex := by + rw [htrci, hrci, hUrci, hrS, htl', htci, hcci, hUci, firstConf_take (by omega)] + have hL : (cutClean cm K).log ++ r.entries.drop ((cutClean cm K).log.length - r.prevLogIndex) + = (abs env.names vars).log := by rw [habs, htlen] + rw [fromPrimary_eq _ _ _ hs (by rw [htlen, htci, hcci, hUci]; omega) + (by rw [hL, ← hciV, ← hrV]; exact hrR), hL, ← hciV] + refine ⟨by simp only [htterm, hterm, gview, Exec.aeIdx], ?_⟩ + have hvf := (agrees_vote_parts hcm).1 + simp only at hvf + have hrole := agrees_role hcm + simp only at hrole + have hmr := aeMid_role r saved hns + have hUlead : U.leadership = (aeMid r saved).leadership := by rw [← hU]; rfl + have htr : (trackedPeers env.names vars) = [] := by + simp [trackedPeers, gnl] + have gvf := g.vf + simp only [core, aePar] at gvf + have hnfV : (cutClean cm K).isNewFollower = vars.isNewFollower := by + rw [htnf, gnf] + cases K <;> simp [cCut, hnf, core] + have hcand : absRole U.leadership ≠ .candidate /\ absRole U.leadership ≠ .preVoteCandidate := by + rw [hUlead] + revert hmr + cases (aeMid r saved).leadership <;> simp [absRole] + unfold settle + rw [← hrV] + rcases gd with ⟨hr1, hl1, hld1⟩ | ⟨⟨s1, hs1, hr1⟩, hl1, hld1⟩ + · simp only [agrees, abs, htr, hr1, htrci, hrci, hl1, hld1, hUrci, htrole, hrole, htterm, hterm, + gview, hvf, htvf, htpk, hnfV, gvf] + cases saved.retiredCommittedIdx <;> simp [hcand] + · have hsn : saved.retiredCommittedIdx = none := by + cases hsr : saved.retiredCommittedIdx with + | none => rfl + | some x => + rw [hsr] at hrS + have hpre : (abs env.names saved).log.take saved.commitIdx + <+: (abs env.names vars).log.take vars.commitIdx := by + have e : (abs env.names saved).log.take saved.commitIdx + = (cutClean cm K).log.take saved.commitIdx := by + rw [htl', List.take_take, Nat.min_eq_left (by omega)] + rw [e, habs] + exact take_prefix_take (List.prefix_append _ _) (by rw [hciV, htci, hcci, hUci]; omega) + have h1 := firstConf_mono hrS.symm hpre + rw [← hrV, hr1] at h1 + have h2 := firstConf_le hrS.symm + rw [Option.some.injEq] at h1 + rw [hUci] at hs1 + omega + simp only [agrees, abs, htr, hr1, htrci, hrci, hl1, hld1, hUrci, hsn, htterm, hterm, + gview, htvf, hvf, gvf, hnfV] + simp [absRole] + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeClean.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeClean.lean new file mode 100644 index 000000000000..1657eafe8849 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeClean.lean @@ -0,0 +1,491 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeLemmas +public import CCF.Proofs.Finset + +@[expose] public section + +/-! +# The clean AppendEntries handler in closed form (not reviewed) + +`handleAppendEntiresFromPrimary` appends the new entries and commits at each signature and +at the end. Its result is `settle`: the extended log, the commit index +`max ci (maxCommittableIndexUpTo log limit)`, and the retirement latch that `recordCommit` +derives from the committed prefix (`firstConf`), clearing the role when it latches. Also: the +first term conflict of a request whose entries share one term, and the round trip of +received entries through the declared ledger. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +theorem find?_prefix {α : Type} {l₁ l₂ : List α} {p : α -> Bool} (h : l₁ <+: l₂) {x : α} + (hx : l₁.find? p = some x) + : l₂.find? p = some x := by + obtain ⟨t, rfl⟩ := h + simp [List.find?_append, hx] + +theorem zipIdx_prefix {α : Type} {l₁ l₂ : List α} (h : l₁ <+: l₂) (k : Nat) + : l₁.zipIdx k <+: l₂.zipIdx k := by + obtain ⟨t, rfl⟩ := h + rw [List.zipIdx_append] + exact List.prefix_append _ _ + +theorem take_prefix_take {α : Type} {l₁ l₂ : List α} (h : l₁ <+: l₂) {a b : Nat} + (ab : a <= b) + : l₁.take a <+: l₂.take b := + List.prefix_take_iff.mpr ⟨(List.take_prefix a l₁).trans h, by simp; omega⟩ + +theorem fla_prefix {l₁ l₂ : List Entry} (h : l₁ <+: l₂) {a : Nat} + {p : EntryContent -> Bool} {x : Nat} (hx : firstLogIndexAfter l₁ a p = some x) + : firstLogIndexAfter l₂ a p = some x := by + unfold firstLogIndexAfter at * + obtain ⟨y, hy, rfl⟩ := Option.map_eq_some_iff.mp hx + rw [find?_prefix (zipIdx_prefix h 1) hy] + rfl + +theorem fla_le {l : List Entry} {a : Nat} {p : EntryContent -> Bool} {x : Nat} + (hx : firstLogIndexAfter l a p = some x) + : 1 <= x /\ x <= l.length := by + unfold firstLogIndexAfter at hx + obtain ⟨⟨e, i⟩, hy, rfl⟩ := Option.map_eq_some_iff.mp hx + have := List.mem_zipIdx (List.mem_of_find?_eq_some hy) + dsimp only + omega + +theorem zip_tail_prefix {α : Type} + : forall {A B : List α}, A <+: B -> A.zip A.tail <+: B.zip B.tail + | [], _, _ => by simp + | [_], _, _ => by simp + | a :: a2 :: A, B, h => by + obtain ⟨t, rfl⟩ := h + have ih := zip_tail_prefix (A := a2 :: A) (B := a2 :: A ++ t) (List.prefix_append _ _) + simp only [List.tail_cons, List.cons_append, List.zip_cons_cons] at ih ⊢ + exact List.cons_prefix_cons.mpr ⟨rfl, ih⟩ + +theorem configurationHistory_prefix {l₁ l₂ : List Entry} (h : l₁ <+: l₂) + : configurationHistory l₁ <+: configurationHistory l₂ := + (zipIdx_prefix h 1).filterMap _ + +theorem rii_prefix {n : NodeID} {l₁ l₂ : List Entry} (h : l₁ <+: l₂) + (hx : (retirementIndexInLog n l₁).isSome) + : (retirementIndexInLog n l₂).isSome := by + unfold retirementIndexInLog at * + dsimp only at * + obtain ⟨y, hy⟩ := Option.isSome_iff_exists.mp hx + obtain ⟨z, hz, rfl⟩ := Option.map_eq_some_iff.mp hy + rw [find?_prefix (zip_tail_prefix (configurationHistory_prefix h)) hz] + rfl + +/-! ## `maxCommittableIndex` -/ + +theorem mcI_cases (l : List Entry) + : maxCommittableIndex l = 0 \/ isSignatureAt l (maxCommittableIndex l) = true := + foldMax_cases (isSignatureAt l) _ 0 + +theorem le_mcI {l : List Entry} {i : Nat} (h : isSignatureAt l i = true) + : i <= maxCommittableIndex l := + foldMax_ge_mem _ _ _ _ + (List.mem_range.mpr (Nat.lt_succ_of_le (isSignatureAt_le_length h))) h + +theorem mcI_le_length (l : List Entry) : maxCommittableIndex l <= l.length := by + rcases mcI_cases l with h | h + · omega + · exact isSignatureAt_le_length h + +theorem isSignatureAt_prefix {l₁ l₂ : List Entry} (h : l₁ <+: l₂) {i : Nat} + (hi : isSignatureAt l₁ i = true) + : isSignatureAt l₂ i = true := by + have hl := isSignatureAt_le_length hi + unfold isSignatureAt entryAt? at hi ⊢ + by_cases i0 : i = 0 + · simp [i0] at hi + · simp only [i0, ite_false] at hi ⊢ + have lt : i - 1 < l₁.length := by omega + rw [List.getElem?_eq_getElem lt] at hi + rw [List.getElem?_eq_getElem (Nat.lt_of_lt_of_le lt h.length_le), ← h.getElem lt] + exact hi + +theorem mcI_prefix {l₁ l₂ : List Entry} (h : l₁ <+: l₂) + : maxCommittableIndex l₁ <= maxCommittableIndex l₂ := by + rcases mcI_cases l₁ with e | e + · omega + · exact le_mcI (isSignatureAt_prefix h e) + +theorem mcIUpTo_le (l : List Entry) (lim : Nat) + : maxCommittableIndexUpTo l lim <= lim + /\ maxCommittableIndexUpTo l lim <= l.length := by + have := mcI_le_length (l.take lim) + simp only [maxCommittableIndexUpTo, List.length_take] at * + omega + +theorem mcIUpTo_prefix {l₁ l₂ : List Entry} (h : l₁ <+: l₂) (lim : Nat) + : maxCommittableIndexUpTo l₁ lim <= maxCommittableIndexUpTo l₂ lim := + mcI_prefix (take_prefix_take h (Nat.le_refl _)) + +/-! ## The commits of `handleAppendEntiresFromPrimary` in closed form -/ + +/-- What `recordCommit` latches at commit index `ci` of `l`. -/ +def firstConf (node : NodeID) (l : List Entry) (ci : Nat) : Option Nat := + firstLogIndexAfter (l.take ci) 0 + fun content => decide (node ∈ content.metadata.retirementConfirmations) + +/-- +`s` with log `log` and commit index `ci`, after the commits in between: the latch is the +first committed confirmation, and the role and primary knowledge clear if it was unset. +-/ +def settle (node : NodeID) (s : NodeState) (log : List Entry) (ci : Nat) : NodeState := + let rci := firstConf node log ci + let cleared := s.retiredCommittedIndex.isNone && rci.isSome + { + s with + log + commitIndex := ci + retiredCommittedIndex := rci + role := if cleared then .none else s.role + primaryKnown := if cleared then false else s.primaryKnown + } + +theorem isRetiredCommitted_iff (node : NodeID) (s : NodeState) + : s.isRetiredCommitted node + <-> (retirementIndexInLog node s.log).isSome /\ s.retiredCommittedIndex.isSome := by + unfold NodeState.isRetiredCommitted NodeState.retirement + dsimp only + cases retirementIndexInLog node s.log with + | none => simp + | some i => + simp only [Option.isSome_some, true_and] + split <;> simp_all <;> split <;> simp_all <;> split <;> simp_all + +theorem firstConf_mono {node : NodeID} {L L' : List Entry} {C C' x : Nat} + (h : firstConf node L C = some x) (hl : L.take C <+: L'.take C') + : firstConf node L' C' = some x := + fla_prefix hl h + +theorem firstConf_le {node : NodeID} {L : List Entry} {C x : Nat} + (h : firstConf node L C = some x) + : 1 <= x /\ x <= C /\ x <= L.length := by + have := fla_le h + simp only [List.length_take] at this + omega + +theorem recordCommit_settle {node : NodeID} {s : NodeState} {L : List Entry} {C C' : Nat} + (hs : s.retiredCommittedIndex = firstConf node s.log s.commitIndex) + (hsl : s.log.take s.commitIndex <+: L.take C) (hC : C <= C') + (hR + : forall j, + firstConf node L C' = some j -> (retirementIndexInLog node (L.take j)).isSome) + : (settle node s L C).recordCommit node C' = settle node s L C' := by + have mono : L.take C <+: L.take C' := take_prefix_take (List.prefix_refl L) hC + cases h1 : firstConf node L C with + | some x => + have h2 := firstConf_mono h1 mono + unfold NodeState.recordCommit settle + simp only [h1, h2, Option.isSome_some, Option.orElse_some, Bool.and_true, + Bool.not_true] + rfl + | none => + have s0 : s.retiredCommittedIndex = none := by + cases h0 : s.retiredCommittedIndex with + | none => rfl + | some y => + rw [h0] at hs + have := firstConf_mono hs.symm (by simpa [List.take_take] using hsl) + rw [h1] at this + cases this + cases h2 : firstConf node L C' with + | none => + unfold NodeState.recordCommit settle firstConf at * + simp only [h1, h2, s0, Option.isSome_none, Bool.and_false, Option.orElse_none, + Bool.false_eq_true, ite_false, Bool.not_false, isRetiredCommitted_iff, + and_false] + | some j => + have rj := hR j h2 + have rL : (retirementIndexInLog node L).isSome := rii_prefix (List.take_prefix j L) rj + unfold NodeState.recordCommit settle firstConf at * + simp only [h1, h2, s0, Option.isSome_none, Bool.and_false, Option.orElse_none, + Bool.false_eq_true, ite_false, Bool.not_false, isRetiredCommitted_iff, + Option.isSome_some, and_true, rL, Option.isNone_none, Bool.and_self, ite_true] + +/-- `commitIfPossible` of `handleAppendEntiresFromPrimary`. -/ +def cip (node : NodeID) (lim : Nat) (s : NodeState) : NodeState := + s.recordCommit node (max s.commitIndex (maxCommittableIndexUpTo s.log lim)) + +/-- The log append of one step of the entry fold of `handleAppendEntiresFromPrimary`. -/ +def appendLog (s : NodeState) (e : Entry) : NodeState := { s with log := s.log ++ [e] } + +/-- One step of the entry fold of `handleAppendEntiresFromPrimary`. -/ +def aeStep (node : NodeID) (lim : Nat) (s : NodeState) (e : Entry) : NodeState := + if e.content.isSignature then cip node lim (appendLog s e) else appendLog s e + +theorem fromPrimary_unfold (node : NodeID) (s : NodeState) (r : AppendEntriesRequest) + : handleAppendEntiresFromPrimary node s r + = let fin := + cip node (min r.primaryCommit (r.prevLogIndex + r.entries.length)) + ((r.entries.drop (s.log.length - r.prevLogIndex)).foldl + (aeStep node (min r.primaryCommit (r.prevLogIndex + r.entries.length))) s) + ( + fin, + { + term := fin.currentTerm + success := true + lastLogIndex := r.prevLogIndex + r.entries.length + } + ) := + rfl + +theorem settle_log (node : NodeID) (s : NodeState) {L : List Entry} {C : Nat} + (e : Entry) (hC : C <= L.length) + : appendLog (settle node s L C) e = settle node s (L ++ [e]) C := by + have : firstConf node (L ++ [e]) C = firstConf node L C := by + simp [firstConf, List.take_append_of_le_length hC] + simp only [appendLog, settle, this] + +theorem settle_self (node : NodeID) (s : NodeState) + (hs : s.retiredCommittedIndex = firstConf node s.log s.commitIndex) + : settle node s s.log s.commitIndex = s := by + cases s with + | mk role ct log ci si mi nf vf pk vg pvg rci => + simp only at hs + unfold settle + simp only + rw [← hs] + cases rci <;> simp + +theorem fold_settle (node : NodeID) (lim : Nat) (s : NodeState) (Lf : List Entry) + (Cf : Nat) (hs : s.retiredCommittedIndex = firstConf node s.log s.commitIndex) + (hR + : forall j, + firstConf node Lf Cf = some j -> (retirementIndexInLog node (Lf.take j)).isSome) + : forall (es L : List Entry) (C : Nat), + L ++ es = Lf + -> s.log.take s.commitIndex <+: L.take C + -> C <= L.length + -> max C (maxCommittableIndexUpTo Lf lim) <= Cf + -> exists C', + C <= C' + /\ C' <= max C (maxCommittableIndexUpTo Lf lim) + /\ C' <= Lf.length + /\ es.foldl (aeStep node lim) (settle node s L C) = settle node s Lf C' := by + intro es + induction es with + | nil => + intro L C hL hp hC hCf + simp only [List.append_nil] at hL + subst hL + exact ⟨C, Nat.le_refl _, Nat.le_max_left _ _, hC, rfl⟩ + | cons e es ih => + intro L C hL hp hC hCf + have hL' : (L ++ [e]) ++ es = Lf := by simp [← hL] + have pre : L ++ [e] <+: Lf := ⟨es, hL'⟩ + have up := mcIUpTo_prefix pre lim + have upL := (mcIUpTo_le (L ++ [e]) lim).2 + have lenL : (L ++ [e]).length = L.length + 1 := by simp + have hp' : s.log.take s.commitIndex <+: (L ++ [e]).take C := + hp.trans (take_prefix_take (List.prefix_append _ _) (Nat.le_refl _)) + simp only [List.foldl_cons] + have st : aeStep node lim (settle node s L C) e + = if e.content.isSignature then cip node lim (settle node s (L ++ [e]) C) + else settle node s (L ++ [e]) C := by + unfold aeStep + rw [settle_log node s e hC] + rw [st] + split + · let C2 := max C (maxCommittableIndexUpTo (L ++ [e]) lim) + have c2 : cip node lim (settle node s (L ++ [e]) C) = settle node s (L ++ [e]) C2 := by + have e1 : cip node lim (settle node s (L ++ [e]) C) + = (settle node s (L ++ [e]) C).recordCommit node C2 := rfl + rw [e1] + refine recordCommit_settle hs hp' (Nat.le_max_left _ _) fun j hj => ?_ + have big : firstConf node Lf Cf = some j := + firstConf_mono hj (take_prefix_take pre (by omega)) + have hjle := firstConf_le hj + have := hR j big + have eq : Lf.take j = (L ++ [e]).take j := by + rw [← hL'] + exact List.take_append_of_le_length (by omega) + rwa [eq] at this + rw [c2] + obtain ⟨C', a, b, c, d⟩ := ih (L ++ [e]) C2 hL' + (hp.trans (take_prefix_take (List.prefix_append _ _) (Nat.le_max_left _ _))) + (by omega) (by omega) + exact ⟨C', by omega, by omega, c, d⟩ + · obtain ⟨C', a, b, c, d⟩ := ih (L ++ [e]) C hL' hp' (by omega) hCf + exact ⟨C', a, b, c, d⟩ + +theorem fromPrimary_eq (node : NodeID) (s : NodeState) (r : AppendEntriesRequest) + (hs : s.retiredCommittedIndex = firstConf node s.log s.commitIndex) + (hci : s.commitIndex <= s.log.length) + (hR + : forall j, + firstConf node (s.log ++ r.entries.drop (s.log.length - r.prevLogIndex)) + (max s.commitIndex + (maxCommittableIndexUpTo + (s.log ++ r.entries.drop (s.log.length - r.prevLogIndex)) + (min r.primaryCommit (r.prevLogIndex + r.entries.length)))) + = some j + -> (retirementIndexInLog node + ((s.log ++ r.entries.drop (s.log.length - r.prevLogIndex)).take + j)).isSome) + : handleAppendEntiresFromPrimary node s r + = ( + settle node s (s.log ++ r.entries.drop (s.log.length - r.prevLogIndex)) + (max s.commitIndex + (maxCommittableIndexUpTo + (s.log ++ r.entries.drop (s.log.length - r.prevLogIndex)) + (min r.primaryCommit (r.prevLogIndex + r.entries.length)))), + { + term := s.currentTerm + success := true + lastLogIndex := r.prevLogIndex + r.entries.length + } + ) := by + generalize hlim : min r.primaryCommit (r.prevLogIndex + r.entries.length) = lim at * + generalize hes : r.entries.drop (s.log.length - r.prevLogIndex) = es at * + rw [fromPrimary_unfold, hlim, hes] + obtain ⟨C', a, b, c, d⟩ := fold_settle node lim s _ _ hs hR es s.log s.commitIndex rfl + (List.prefix_refl _) hci (Nat.le_refl _) + rw [settle_self node s hs] at d + have up := (mcIUpTo_le (s.log ++ es) lim).2 + have e2 : max C' (maxCommittableIndexUpTo (s.log ++ es) lim) + = max s.commitIndex (maxCommittableIndexUpTo (s.log ++ es) lim) := by omega + have fin : cip node lim (settle node s (s.log ++ es) C') + = settle node s (s.log ++ es) + (max s.commitIndex (maxCommittableIndexUpTo (s.log ++ es) lim)) := by + have e1 : cip node lim (settle node s (s.log ++ es) C') + = (settle node s (s.log ++ es) C').recordCommit node + (max C' (maxCommittableIndexUpTo (s.log ++ es) lim)) := rfl + rw [e1, recordCommit_settle (L := s.log ++ es) hs + (take_prefix_take (List.prefix_append _ _) a) (Nat.le_max_left _ _) + (by rw [e2]; exact hR), e2] + simp only [d, fin] + rfl + +theorem set_name_sort (names : Names) (s : CCF.Finset NodeID) + (h : s.sort.all (fun i => names.id (names.name i) == i) = true) + : names.set (s.sort.map names.name) = s := by + apply CCF.Finset.ext + intro a + simp only [Names.set, CCF.Finset.mem_ofList, List.map_map] + have : (s.sort.map (names.id ∘ names.name)) = s.sort := by + conv => rhs; rw [← List.map_id s.sort] + apply List.map_congr_left + intro i hi + simp only [List.all_eq_true, beq_iff_eq] at h + exact h i hi + rw [this, CCF.Finset.mem_sort] + +theorem absEntry_toExecEntry (env : Env) (e : Entry) + (hq + : (match e.content with + | .transaction q _ => q == 0 + | .signature => true) + = true) + (hn + : (((e.content.metadata.configuration.map (·.sort)).getD [] + ++ e.content.metadata.retirementConfirmations.sort).all + fun i => env.names.id (env.names.name i) == i) + = true) + : absEntry env.names (Exec.toExecEntry env e) = e := by + obtain ⟨t, c⟩ := e + cases c with + | signature => rfl + | transaction q md => + obtain ⟨cfg, rc⟩ := md + simp only [beq_iff_eq] at hq + subst hq + simp only [EntryContent.metadata, List.all_append, Bool.and_eq_true] at hn + simp only [absEntry, Exec.toExecEntry, Bool.false_eq_true, ite_false] + congr + · cases cfg with + | none => rfl + | some s => + simp only [Option.map_some, Option.getD_some] at hn + simp only [Option.map_some, Exec.envNodes, List.map_map, Function.comp_def, + Option.some.injEq] + exact set_name_sort env.names s hn.1 + · exact set_name_sort env.names rc hn.2 + +theorem ftci_at (L : List Entry) (es : List Entry) (p n : Nat) + (hn : n < (((L.drop p).zip es).zipIdx (p + 1)).length) + : (((L.drop p).zip es).zipIdx (p + 1))[n] + = ((L[p + n]'(by simp at hn; omega), es[n]'(by simp at hn; omega)), p + 1 + n) := by + simp [List.getElem_zipIdx] + +theorem termAt_get (L : List Entry) (j : Nat) (h1 : 0 < j) (h2 : j <= L.length) + : termAt L j = (L[j - 1]'(by omega)).term := by + simp only [termAt, entryAt?, Nat.ne_of_gt h1, ite_false] + rw [List.getElem?_eq_getElem (by omega)] + rfl + +theorem ftci_spec (s : NodeState) (r : AppendEntriesRequest) (τ : Nat) + (hτ : forall e, e ∈ r.entries -> e.term = τ) + : match firstTermConflictIndex s r with + | some k => + r.prevLogIndex < k + /\ k <= s.log.length + /\ k <= r.prevLogIndex + r.entries.length + /\ termAt s.log k ≠ τ + /\ forall j, r.prevLogIndex < j -> j < k -> termAt s.log j = τ + | none => + forall j, + r.prevLogIndex < j + -> j <= s.log.length + -> j <= r.prevLogIndex + r.entries.length + -> termAt s.log j = τ := by + unfold firstTermConflictIndex + generalize hp : r.prevLogIndex = p + generalize hes : r.entries = es at hτ + generalize hL : s.log = L + simp only + have len : (((L.drop p).zip es).zipIdx (p + 1)).length = min (L.length - p) es.length := by + simp + -- the element at position `n` is the comparison at index `p + 1 + n` + have key : forall n (hn : n < min (L.length - p) es.length), + termAt L (p + 1 + n) = (L[p + n]'(by omega)).term + /\ (es[n]'(by omega)).term = τ := by + intro n hn + refine ⟨?_, hτ _ (List.getElem_mem _)⟩ + rw [termAt_get L _ (by omega) (by omega)] + congr 2 + omega + cases h + : (((L.drop p).zip es).zipIdx (p + 1)).find? + (fun x => x.1.1.term != x.1.2.term) with + | none => + simp only [Option.map_none] + intro j pj jL jr + rw [List.find?_eq_none] at h + have hn : j - p - 1 < (((L.drop p).zip es).zipIdx (p + 1)).length := by + rw [len]; omega + have := h _ (List.getElem_mem hn) + rw [ftci_at L es p _ hn] at this + simp only [bne_iff_ne, ne_eq, Decidable.not_not] at this + obtain ⟨k1, k2⟩ := key (j - p - 1) (by rw [← len]; exact hn) + have e : p + 1 + (j - p - 1) = j := by omega + rw [e] at k1 + rw [k1, this, k2] + | some x => + simp only [Option.map_some] + rw [List.find?_eq_some_iff_getElem] at h + obtain ⟨px, n, hn, hx, before⟩ := h + rw [ftci_at L es p _ hn] at hx + subst hx + have hn' : n < min (L.length - p) es.length := by rw [← len]; exact hn + obtain ⟨k1, k2⟩ := key n hn' + simp only [bne_iff_ne, ne_eq] at px + refine ⟨by omega, by omega, by omega, by rw [k1, ← k2]; exact px, ?_⟩ + intro j pj jk + have hm : j - p - 1 < n := by omega + have := before (j - p - 1) hm + rw [ftci_at L es p _ (by omega)] at this + simp only [Bool.not_eq_true', bne_eq_false_iff_eq] at this + obtain ⟨m1, m2⟩ := key (j - p - 1) (by omega) + have e : p + 1 + (j - p - 1) = j := by omega + rw [e] at m1 + rw [m1, this, m2] + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeCommit.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeCommit.lean new file mode 100644 index 000000000000..b92d5ae035e3 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeCommit.lean @@ -0,0 +1,514 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeClean +public import Consensus.TraceValidation.Proofs.Handlers.AeFrame + +@[expose] public section + +/-! +# The commit path during AppendEntries (not reviewed) + +`GInv` says a handler keeps a predicate of the core and sends nothing. `Good` is the declared +core during the execute phase of an AppendEntries hold: the ledger is a prefix of the final +ledger `lx`, the committable list is its signatures above the commit index, and the commit +index stays between the starting one `c0` and the clean bound `Par.bd`. Retirement through +`storeCompact` only latches an index above `c0` and steps down. `commit` moves the commit +index and keeps `Good`; `commitIfPossible` keeps `Good` and, once the whole ledger is in, +reaches `Par.bd`. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- `x` keeps `G` of the core and sends nothing. -/ +def GInv {α : Type} (env : Env) (G : Core -> Prop) (x : M α) : Prop := + forall o0 : Outbox, + Hoare env (fun v o => G (core v) /\ o = o0) x (fun _ v o => G (core v) /\ o = o0) + +namespace GInv +variable {env : Env} {G : Core -> Prop} + +theorem of_frame {α : Type} {x : M α} (nl : forall c, G c -> c.leadership ≠ .leader) + (h : Frame env x) + : GInv env G x := by + intro o0 + refine Hoare.pin fun v0 _ ⟨g, ho⟩ => ?_ + subst ho + refine Hoare.post + (Hoare.pre (h (core v0) _ (nl _ g)) fun v o ⟨hv, ho⟩ => ⟨by rw [hv], ho⟩) ?_ + intro _ v o ⟨hc, ho⟩ + exact ⟨by rw [hc]; exact g, ho⟩ + +theorem bind {α β : Type} {x : M α} {f : α -> M β} (hx : GInv env G x) + (hf : forall a, GInv env G (f a)) + : GInv env G (x >>= f) := + fun o0 => Hoare.bind (hx o0) fun a => hf a o0 + +theorem getV_bind {β : Type} {k : State -> M β} + (hk : forall s, G (core s) -> GInv env G (k s)) + : GInv env G (Exec.getV >>= k) := by + intro o0 + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v0 o1 ⟨⟨g, ho1⟩, hv⟩ => ?_ + subst hv ho1 + exact Hoare.pre (hk v0 g o1) fun v o ⟨hv, ho⟩ => ⟨by rw [hv]; exact g, ho⟩ + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} (hx : b -> GInv env G x) + (hy : Not b -> GInv env G y) + : GInv env G (if b then x else y) := by + by_cases h : b + · simpa [h] using hx h + · simpa [h] using hy h + +theorem pure {α : Type} (a : α) : GInv env G (Pure.pure a : M α) := + fun _ => Hoare.pure a fun _ _ p => p + +theorem fail {α : Type} (m : String) : GInv env G (Exec.fail m : M α) := + fun _ => Hoare.fail m + +theorem fail_bind {α β : Type} (m : String) (f : α -> M β) + : GInv env G (Exec.fail m >>= f) := + fun _ => + Hoare.bind (R := fun _ _ _ => False) (Hoare.fail m) + fun _ => + Hoare.false_pre fun _ _ h => h + +theorem keeps {α : Type} {x : M α} (h : Spec.Keeps env x) : GInv env G x := + fun _ => Hoare.keeps h fun _ _ _ p => p + +theorem setV {f : State -> State} (hf : forall v, G (core v) -> G (core (f v))) + : GInv env G (Exec.setV f) := + fun _ => Hoare.setV f fun v _ ⟨g, ho⟩ => ⟨hf v g, ho⟩ + +theorem forIn_list {α β : Type} (l : List α) (init : β) {f : α -> β -> M (ForInStep β)} + (hf : forall a b, a ∈ l -> GInv env G (f a b)) + : GInv env G (forIn l init f) := by + induction l generalizing init with + | nil => exact pure init + | cons a rest ih => + rw [List.forIn_cons] + refine bind (hf a init (List.mem_cons_self ..)) fun r => ?_ + cases r with + | done b => exact pure b + | yield b => exact ih b (fun a b m => hf a b (List.mem_cons_of_mem _ m)) + +theorem option {α β : Type} {o : Option α} {x : M β} {f : α -> M β} (hx : GInv env G x) + (hf : forall a, o = some a -> GInv env G (f a)) + : GInv env G + (match o with + | none => x + | some a => f a) := by + cases o + · exact hx + · exact hf _ rfl + +end GInv + +/-- The fixed parameters of the AppendEntries execute phase. -/ +structure Par where + names : Names + nid : NodeId + view : Nat + vf : Option NodeId + nf : Bool + lt : Leadership + ldr : NodeId + rciT : Option Nat + c0 : Nat + lim : Nat + /-- The ledger at the end of the hold. -/ + lx : List Exec.Entry + +/-- Signature indexes of a ledger in `(lo, hi]`, as `signaturesIn`. -/ +def sigsIn (ledger : Array Exec.Entry) (lo hi : Nat) : List Nat := + (List.range' (lo + 1) (hi - lo)).filter fun i => ledger[i - 1]?.any (·.sig) + +/-- The commit index the hold ends with. -/ +def Par.bd (p : Par) : Nat := + max p.c0 (maxCommittableIndexUpTo (p.lx.map (absEntry p.names)) p.lim) + +/-- The declared core during the execute phase. -/ +structure Good (p : Par) (c : Core) : Prop where + nodeId : c.nodeId = p.nid + view : c.currentView = p.view + vf : c.votedFor = p.vf + nf : c.isNewFollower = p.nf + size : c.ledger.size = c.lastIdx + ledger : c.ledger.toList = p.lx.take c.lastIdx + last : c.lastIdx <= p.lx.length + committable : c.committable = sigsIn c.ledger c.commitIdx c.lastIdx + c0 : p.c0 <= c.commitIdx + bd : c.commitIdx <= p.bd + ci : c.commitIdx <= c.lastIdx + views : c.views.size <= p.view + rc : forall x, x ∈ c.rcEntries -> p.c0 < x.1 + lt : p.lt ≠ .leader + d + : (c.retiredCommittedIdx = p.rciT /\ c.leadership = p.lt /\ c.leaderId = some p.ldr) + \/ ((exists s, p.c0 < s /\ c.retiredCommittedIdx = some s) + /\ c.leadership = .none + /\ c.leaderId = none) + +theorem Good.nl {p : Par} {c : Core} (g : Good p c) : c.leadership ≠ .leader := by + rcases g.d with ⟨_, h, _⟩ | ⟨_, h, _⟩ + · rw [h]; exact g.lt + · rw [h]; decide + +/-- `Good` with a fixed last and commit index: what the commit path keeps. -/ +def CG (p : Par) (n m : Nat) (c : Core) : Prop := + Good p c /\ c.lastIdx = n /\ c.commitIdx = m + +theorem CG.nl {p : Par} {n m : Nat} : forall c, CG p n m c -> c.leadership ≠ .leader := + fun _ g => g.1.nl + +theorem CG.retire {p : Par} {n m : Nat} {c : Core} (g : CG p n m c) {s : Nat} + (hs : p.c0 < s) + : CG p n m + { c with retiredCommittedIdx := some s, leadership := .none, leaderId := none } := + ⟨{ g.1 with d := Or.inr ⟨⟨s, hs, rfl⟩, rfl, rfl⟩ }, g.2⟩ + +def stepDown (w : State) : State := + { + w with + leaderId := none + leadership := .none + } + +/-- The effect of `becomeRetired _ .retiredCommitted` on a non-leader. -/ +def retireRC (w : State) : State := + { + w with + leaderId := none + leadership := .none + retired := true + retirementPhase := some .retiredCommitted + } + +theorem hoare_becomeRetired_rc {env : Env} (i : Nat) (Pre : State -> Outbox -> Prop) + (hnl : forall v o, Pre v o -> v.leadership ≠ .leader) + : Hoare env Pre (becomeRetired i .retiredCommitted) + (fun _ v o => exists w, Pre w o /\ v = retireRC w) := by + unfold becomeRetired becomeRetired.nominateSuccessorUnsafe + refine Hoare.pin fun w o0 pw => ?_ + refine Hoare.bind (R := fun _ v o => v = w /\ o = o0) ?_ fun _ => ?_ + · refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v1 o1 ⟨⟨hv1, ho1⟩, hs⟩ => ?_ + subst hv1 ho1 hs + have nl := hnl _ _ pw + refine Hoare.ite (fun h => absurd (beq_iff_eq.mp h) nl) fun _ => ?_ + exact Hoare.pure _ fun _ _ p => p + · refine Hoare.bind (Hoare.setV _ (Q := fun _ v o => v = stepDown w /\ o = o0) fun v o ⟨hv, ho⟩ => ⟨by rw [hv]; rfl, ho⟩) fun _ => ?_ + exact Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨w, ho ▸ pw, by rw [hv]; rfl⟩ + +theorem core_retireRC (w : State) (s : Nat) + : core (retireRC { w with retiredCommittedIdx := some s }) + = { + core w with + retiredCommittedIdx := some s, leadership := .none, leaderId := none + } := + rfl + +theorem ginv_retire_self {env : Env} {p : Par} {n m : Nat} (seqno : Nat) + (hs : p.c0 < seqno) {β : Type} (k : Unit -> M β) + (hk : forall a, GInv env (CG p n m) (k a)) + : GInv env (CG p n m) + (Exec.setV (fun v => { v with retiredCommittedIdx := some seqno }) + >>= fun _ => + becomeRetired seqno .retiredCommitted >>= k) := by + intro o0 + refine Hoare.bind + (R := + fun _ v o => + exists w, + (CG p n m (core w) /\ o = o0) + /\ v = { w with retiredCommittedIdx := some seqno }) + (Hoare.setV _ fun v o h => ⟨v, h, rfl⟩) fun _ => ?_ + refine Hoare.bind (hoare_becomeRetired_rc seqno _ ?_) fun a => ?_ + · rintro v o ⟨w, ⟨g, _⟩, rfl⟩ + exact g.1.nl + · refine Hoare.pre (hk a o0) ?_ + rintro v o ⟨w', ⟨w, ⟨g, ho⟩, rfl⟩, rfl⟩ + exact ⟨by rw [core_retireRC]; exact g.retire hs, ho⟩ + +theorem ginv_setRetiredCommitted {env : Env} {p : Par} {n m : Nat} (seqno : Nat) + (hs : p.c0 < seqno) (ids : List NodeId) (peers0 : List (NodeId × Peer)) + : GInv env (CG p n m) (setRetiredCommitted seqno ids peers0) := by + unfold setRetiredCommitted + refine GInv.bind (GInv.forIn_list _ _ fun id _ _ => ?_) fun _ => GInv.pure _ + refine GInv.getV_bind fun s g => ?_ + refine GInv.ite (fun _ => ?_) (fun _ => ?_) + · dsimp only + have nl : ¬ (s.leadership == .leader) = true := fun h => g.1.nl (beq_iff_eq.mp h) + refine GInv.ite (fun _ => ?_) fun _ => + GInv.bind (GInv.keeps Spec.curLoc) fun _ => GInv.fail_bind _ _ + exact GInv.ite (fun h => absurd h nl) fun _ => + ginv_retire_self seqno hs _ fun _ => GInv.pure _ + · exact GInv.bind (GInv.setV fun _ h => h) fun _ => GInv.pure _ + +theorem ginv_storeCompact_go {env : Env} {p : Par} {n m : Nat} (idx : Nat) + (peers0 : List (NodeId × Peer)) + : forall l : List (Nat × List NodeId), + (forall x, x ∈ l -> p.c0 < x.1) + -> GInv env (CG p n m) (storeCompact.go idx peers0 l) := by + intro l + induction l with + | nil => intro _; exact GInv.pure _ + | cons x rest ih => + intro h + obtain ⟨ver, ids⟩ := x + rw [storeCompact.go] + refine GInv.ite (fun _ => ?_) fun _ => GInv.pure _ + exact GInv.bind (ginv_setRetiredCommitted ver (h _ (List.mem_cons_self ..)) ids peers0) + fun _ => ih fun y hy => h y (List.mem_cons_of_mem _ hy) + +theorem ginv_storeCompact {env : Env} {p : Par} {n m : Nat} (idx : Nat) + : GInv env (CG p n m) (storeCompact idx) := by + unfold storeCompact + refine GInv.getV_bind fun _ _ => GInv.getV_bind fun s g => ?_ + refine GInv.bind (ginv_storeCompact_go idx _ _ g.1.rc) fun _ => GInv.setV fun v h => ?_ + exact ⟨{ h.1 with rc := fun x hx => h.1.rc x (List.mem_filter.mp hx).1 }, h.2⟩ + +theorem sigsIn_filter (ledger : Array Exec.Entry) {m idx n : Nat} (h1 : m <= idx) + (h2 : idx <= n) + : (sigsIn ledger m n).filter (fun x => decide (x > idx)) = sigsIn ledger idx n := by + unfold sigsIn + have split : List.range' (m + 1) (n - m) + = List.range' (m + 1) (idx - m) ++ List.range' (idx + 1) (n - idx) := by + rw [show n - m = (idx - m) + (n - idx) by omega, ← List.range'_append_1, + show m + 1 + (idx - m) = idx + 1 by omega] + rw [split, List.filter_append, List.filter_append] + have a : ((List.range' (m + 1) (idx - m)).filter fun i => ledger[i - 1]?.any (·.sig)).filter + (fun x => decide (x > idx)) = [] := by + rw [List.filter_eq_nil_iff] + intro x hx + have := (List.mem_filter.mp hx).1 + rw [List.mem_range'_1] at this + simp only [decide_eq_true_eq] + omega + have b : ((List.range' (idx + 1) (n - idx)).filter fun i => ledger[i - 1]?.any (·.sig)).filter + (fun x => decide (x > idx)) + = (List.range' (idx + 1) (n - idx)).filter fun i => ledger[i - 1]?.any (·.sig) := by + rw [List.filter_eq_self] + intro x hx + have := (List.mem_filter.mp hx).1 + rw [List.mem_range'_1] at this + simp only [decide_eq_true_eq] + omega + rw [a, b, List.nil_append] + +/-- Decompose a handler into `GInv` rules for `CG`. -/ +macro "ginv_tac" : tactic => + `(tactic| repeat' (first + | with_reducible exact GInv.pure _ + | with_reducible exact GInv.fail _ + | with_reducible exact GInv.keeps (Spec.trace _) + | with_reducible exact GInv.keeps (Spec.emitNat _ _) + | with_reducible exact GInv.keeps (Spec.emitStr _ _) + | with_reducible exact GInv.keeps Spec.curLoc + | with_reducible exact ginv_storeCompact _ + | (refine GInv.of_frame CG.nl ?_; frame_ext) + | (with_reducible apply GInv.getV_bind; intro _ _) + | with_reducible apply GInv.bind + | with_reducible apply GInv.ite + | (refine GInv.setV fun _ h => h) + | (with_reducible intro) + | dsimp only + | with_reducible split)) + +theorem hoare_commit {env : Env} {p : Par} {n m : Nat} (idx : Nat) (o0 : Outbox) + (hm : m < idx) (hn : idx <= n) (hb : idx <= p.bd) + : Hoare env (fun v o => CG p n m (core v) /\ o = o0) (commit idx) + (fun _ v o => CG p n idx (core v) /\ o = o0) := by + unfold commit + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v0 o1 ⟨⟨g, ho1⟩, hv⟩ => ?_ + subst hv ho1 + dsimp only + have l : v0.lastIdx = n := g.2.1 + have c : v0.commitIdx = m := g.2.2 + refine Hoare.ite (fun h => ?_) fun _ => ?_ + · exfalso + omega + refine Hoare.ite (fun h => ?_) fun _ => ?_ + · exfalso + omega + refine Hoare.bind (Hoare.keeps (Spec.trace _) (Q := fun _ v o => v = v0 /\ o = o1) + fun _ _ _ p => p) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.emitNat _ _) (Q := fun _ v o => v = v0 /\ o = o1) + fun _ _ _ p => p) fun _ => ?_ + refine Hoare.bind (Hoare.setV _ (Q := fun _ v o => CG p n idx (core v) /\ o = o1) + fun v o ⟨hv, ho⟩ => ⟨?_, ho⟩) fun _ => ?_ + · subst hv + have g1 := g.1 + refine ⟨{ g1 with + committable := ?_ + c0 := Nat.le_trans g1.c0 (by simp only [core] at c ⊢; omega) + bd := hb + ci := by simp only [core] at l ⊢; omega }, l, rfl⟩ + have e := g1.committable + simp only [core] at e l c ⊢ + rw [e, l, c] + exact sigsIn_filter _ (Nat.le_of_lt hm) hn + · refine (?_ : GInv env (CG p n idx) _) o1 + ginv_tac + +theorem mem_sigsIn {ledger : Array Exec.Entry} {lo hi x : Nat} + : x ∈ sigsIn ledger lo hi + <-> lo < x /\ x <= hi /\ ledger[x - 1]?.any (·.sig) = true := by + unfold sigsIn + simp only [List.mem_filter, List.mem_range'_1] + constructor + · rintro ⟨⟨a, b⟩, c⟩ + exact ⟨by omega, by omega, c⟩ + · rintro ⟨a, b, c⟩ + exact ⟨⟨by omega, by omega⟩, c⟩ + +theorem sigsIn_sorted (ledger : Array Exec.Entry) (lo hi : Nat) + : (sigsIn ledger lo hi).Pairwise (· < ·) := + (List.pairwise_lt_range' (s := lo + 1) (n := hi - lo)).filter _ + +theorem isSig_abs (names : Names) (lx : List Exec.Entry) {lim h : Nat} (h0 : 0 < h) + (hl : h <= lim) + : isSignatureAt ((lx.map (absEntry names)).take lim) h = lx[h - 1]?.any (·.sig) := by + unfold isSignatureAt entryAt? + simp only [Nat.pos_iff_ne_zero.mp h0, ite_false, List.getElem?_take, + show h - 1 < lim by omega, ite_true, List.getElem?_map] + cases lx[h - 1]? with + | none => rfl + | some e => + simp only [Option.map_some, Option.any_some] + unfold absEntry + cases e.sig <;> rfl + +theorem Good.get {p : Par} {c : Core} (g : Good p c) {h : Nat} (hh : h <= c.lastIdx) + (h0 : 0 < h) + : c.ledger[h - 1]? = p.lx[h - 1]? := by + rw [← Array.getElem?_toList, g.ledger, List.getElem?_take] + simp only [show h - 1 < c.lastIdx by omega, ite_true] + +theorem Good.sig_le_bd {p : Par} {c : Core} (g : Good p c) {h : Nat} + (hm : h ∈ sigsIn c.ledger c.commitIdx c.lastIdx) (hl : h <= p.lim) + : h <= p.bd := by + obtain ⟨lo, hi, sig⟩ := mem_sigsIn.mp hm + rw [g.get hi (by omega), ← isSig_abs p.names _ (by omega) hl] at sig + have := le_mcI sig + unfold Par.bd maxCommittableIndexUpTo + omega + +theorem viewAt_le_size' (v : State) (i : Nat) : v.viewAt i <= v.views.size := by + unfold State.viewAt + have := List.length_filter_le (fun x => decide (x <= i)) v.views.toList + simpa using this + +theorem getLast_max {l : List Nat} (sorted : l.Pairwise (· < ·)) {x : Nat} + (last : l.getLast? = some x) + : forall y, y ∈ l -> y <= x := by + obtain ⟨ys, rfl⟩ := List.getLast?_eq_some_iff.mp last + intro y mem + rcases List.mem_append.mp mem with mem | mem + · have := (List.pairwise_append.mp sorted).2.2 y mem x (List.mem_singleton_self _) + omega + · simp only [List.mem_singleton] at mem + omega + +theorem hoare_cip {env : Env} {p : Par} {n : Nat} (o0 : Outbox) + : Hoare env (fun v o => Good p (core v) /\ v.lastIdx = n /\ o = o0) + (commitIfPossible p.lim) + (fun _ v o => + Good p (core v) + /\ v.lastIdx = n + /\ (n = p.lx.length -> v.commitIdx = p.bd) + /\ o = o0) := by + unfold commitIfPossible + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v0 o1 ⟨⟨g, l, ho1⟩, hv⟩ => ?_ + subst hv ho1 + -- The bound when the whole ledger is in: the top signature up to `lim` is committable. + have top : n = p.lx.length -> p.bd <= v0.commitIdx \/ (v0.commitIdx < p.bd + /\ p.bd ∈ (v0.committable.filter fun x => decide (x <= p.lim))) := by + intro hn + by_cases lt : p.bd <= v0.commitIdx + · exact Or.inl lt + · refine Or.inr ⟨by omega, ?_⟩ + have c0 := g.c0 + simp only [core] at c0 + have eq : p.bd = maxCommittableIndexUpTo (p.lx.map (absEntry p.names)) p.lim := by + unfold Par.bd at lt ⊢ + omega + rcases mcI_cases ((p.lx.map (absEntry p.names)).take p.lim) with z | sig + · unfold maxCommittableIndexUpTo at eq + omega + · have b := mcIUpTo_le (p.lx.map (absEntry p.names)) p.lim + unfold maxCommittableIndexUpTo at eq b + rw [← eq] at sig b + rw [List.length_map] at b + rw [isSig_abs _ _ (by omega) b.1] at sig + have cm := g.committable + simp only [core] at cm l + have gg := g.get (h := p.bd) (by simp only [core]; omega) (by omega) + simp only [core] at gg + rw [List.mem_filter, cm, mem_sigsIn, gg] + exact ⟨⟨by omega, by omega, sig⟩, by simp only [decide_eq_true_eq]; omega⟩ + have cm : v0.committable = sigsIn v0.ledger v0.commitIdx v0.lastIdx := g.committable + have bd : v0.commitIdx <= p.bd := g.bd + have done : (n = p.lx.length -> v0.commitIdx = p.bd) + -> Hoare env (fun v o => v = v0 /\ o = o1) (Pure.pure () : M Unit) + (fun _ v o => Good p (core v) /\ v.lastIdx = n + /\ (n = p.lx.length -> v.commitIdx = p.bd) /\ o = o1) := + fun h => Hoare.pure _ fun v o ⟨hv, ho⟩ => by + subst hv ho + exact ⟨g, l, h, rfl⟩ + have sorted : (v0.committable.filter fun x => decide (x <= p.lim)).Pairwise (· < ·) := by + rw [cm] + exact (sigsIn_sorted _ _ _).filter _ + refine Hoare.ite (fun _ => ?_) fun hg => done fun hn => ?_ + · split + · rename_i h heq + unfold State.highestCommittableLe at heq + have mem : h ∈ v0.committable.filter fun x => decide (x <= p.lim) := by + obtain ⟨ys, eq⟩ := List.getLast?_eq_some_iff.mp heq + rw [eq] + exact List.mem_append_right _ (List.mem_singleton_self _) + have mem' := List.mem_filter.mp mem + rw [cm] at mem' + have hb := g.sig_le_bd mem'.1 (by simpa using mem'.2) + obtain ⟨lo, hi, _⟩ := mem_sigsIn.mp mem'.1 + refine Hoare.pre (Hoare.post (hoare_commit h o1 lo (by omega) hb) + fun _ v o ⟨cg, ho⟩ => ⟨cg.1, cg.2.1, fun hn => ?_, ho⟩) fun v o ⟨hv, ho⟩ => by + subst hv ho + exact ⟨⟨g, l, rfl⟩, rfl⟩ + have e : v.commitIdx = h := cg.2.2 + rw [e] + rcases top hn with t | ⟨_, t⟩ + · omega + · have := getLast_max sorted heq p.bd t + omega + · rename_i x hx + refine done fun hn => ?_ + rcases top hn with t | ⟨_, t⟩ + · omega + · exfalso + unfold State.highestCommittableLe at hx + obtain ⟨y, hy⟩ := Option.ne_none_iff_exists'.mp + (mt List.getLast?_eq_none_iff.mp (List.ne_nil_of_mem t)) + exact hx y hy + · rcases top hn with t | ⟨lt, t⟩ + · omega + · exfalso + apply hg + have hl := (List.mem_filter.mp t).2 + simp only [decide_eq_true_eq] at hl + simp only [Bool.and_eq_true, decide_eq_true_eq] + refine ⟨by omega, ?_⟩ + have vw : v0.views.size <= p.view := g.views + have cv : v0.currentView = p.view := g.view + have := viewAt_le_size' v0 p.lim + unfold State.getTerm + split <;> omega + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeExec.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeExec.lean new file mode 100644 index 000000000000..af395e8edb17 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeExec.lean @@ -0,0 +1,570 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeCommit + +@[expose] public section + +/-! +# The execute phase of AppendEntries (not reviewed) + +`recvAppendEntries_eq` restates the handler through named pieces: the scan loop's body +`scanBody`, the execute loop's body `execBody`, the finish `aeFinish`, and the phases after +the term handling (`aeMatch`, `aeApply`). `GT` says a handler takes the core from one +predicate to another and sends nothing. Executing entry `i` of the final ledger takes `Good` +at last index `i - 1` to `Good` at `i` (`gt_exec`), so the execute loop over the work list +ends with the whole final ledger (`gt_execLoop`), and the finish reaches the clean commit +bound and sends the ACK (`hoare_finish`). +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- The scan loop's body. -/ +def scanBody (from_ : NodeId) (r : AppendEntriesRequest) (payload : Array Exec.Entry) + (i : Nat) (s : Option Unit × Array (Nat × Exec.Entry × Bool)) + : M (ForInStep (Option Unit × Array (Nat × Exec.Entry × Bool))) := + let toApply := s.snd + let entry? := payload[i - r.prevLogIndex - 1]? + if entry?.isNone = true then do + nack from_ + pure (ForInStep.done (some (), toApply)) + else do + let entry := entry?.get! + let v ← getV + let push : Unit -> M (ForInStep (Option Unit × Array (Nat × Exec.Entry × Bool))) := + fun _ => do + if (!entry.retired.isEmpty) = true then + setV fun v => { v with rcEntries := v.rcEntries ++ [(i, entry.retired)] } + pure + (ForInStep.yield (none, toApply.push (i, entry, entry.term == aeTermOfIdx r))) + if i ≤ v.lastIdx then + if (aeTermOfIdx r != v.viewAt i) = true then + if v.isNewFollower = true then do + rollback (i - 1) + setV fun v => { v with isNewFollower := false } + push () + else + pure (ForInStep.done (some (), toApply)) + else + pure (ForInStep.yield (none, toApply)) + else + push () + +/-- The execute loop's body. -/ +def execBody (from_ : NodeId) (r : AppendEntriesRequest) (x : Nat × Exec.Entry × Bool) + (_s : Option Unit × Unit) + : M (ForInStep (Option Unit × Unit)) := + match x with + | (i, entry, ok) => do + trace "execute_append_entries_sync" + emitStr "from_node_id" from_ + if ok = true then do + setV fun v => { v with lastIdx := i } + forIn entry.retired PUnit.unit + fun id _ => do + trace "retired_committed_tx" + emitNat "seqno" i + emitStr "retired_node_id" id + pure (ForInStep.yield PUnit.unit) + let jp : Unit -> M (ForInStep (Option Unit × Unit)) := + fun _ => + let jp := + fun (_ : Unit) => do + setV fun v => { v with ledger := (v.ledger.extract 0 (i - 1)).push entry } + if entry.sig = true then do + let v ← getV + let jp : Unit -> M (ForInStep (Option Unit × Unit)) := + fun _ => do + setV fun v => { v with committable := v.committable ++ [i] } + if (entry.term != 0) = true then + let jp := + fun (_ : Unit) => do + commitIfPossible (min r.primaryCommit (aeIdx r)) + pure (ForInStep.yield (none, ())) + if (aeTermOfIdx r == 0) = true then do + let x ← viewUpdate 1 r.term + jp x + else do + let x ← viewUpdate (r.prevLogIndex + 1) entry.term + jp x + else + pure (ForInStep.yield (none, ())) + if (v.retired && v.retirementPhase == some Phase.ordered) = true then do + let x ← becomeRetired i Phase.signed + jp x + else + jp () + else + pure (ForInStep.yield (none, ())) + if entry.sig = true then do + let x ← startTickingIfNecessary + jp x + else + jp () + match entry.config with + | some nodes => do + let _ ← addConfiguration (some i) (some nodes) + jp () + | _ => jp () + else do + setV fun v => { v with ledger := v.ledger.extract 0 (i - 1) } + nack from_ + pure (ForInStep.done (some (), ())) + +/-- `execute_append_entries_finish` and the ACK. -/ +def aeFinish (from_ : NodeId) (r : AppendEntriesRequest) : M Unit := do + commitIfPossible (min r.primaryCommit (aeIdx r)) + let w ← getV + let lci := w.lastCommittable + let jp : Unit -> M Unit := + fun _ => do + let w ← getV + sendAer from_ w.currentView (aeIdx r) true + if (aeTermOfIdx r == 0) = true then do + let x ← viewUpdate 1 r.term + jp x + else if aeIdx r > lci then do + let x ← viewUpdate (lci + 1) (aeTermOfIdx r) + jp x + else + jp () + +/-- The scan and execute phases and the finish. -/ +def aeApply (from_ : NodeId) (r : AppendEntriesRequest) (payload : Array Exec.Entry) + : M Unit := do + let s ← forIn [r.prevLogIndex + 1 : aeIdx r + 1] (none, #[]) (scanBody from_ r payload) + match s.fst with + | some x => pure x + | none => do + let t ← forIn s.snd (none, ()) (execBody from_ r) + match t.fst with + | some x => pure x + | none => aeFinish from_ r + +/-- After the term phase and the leader guard. -/ +def aeMatch (from_ : NodeId) (r : AppendEntriesRequest) (payload : Array Exec.Entry) + (v : State) + : M Unit := + let prevTerm := v.getTerm r.prevLogIndex + if (prevTerm != r.prevLogTerm) = true then + let jp := fun (_ : Unit) => (pure () : M Unit) + if (prevTerm == 0) = true then do + let x ← nack from_ + jp x + else do + let x ← nackRejected from_ r.prevLogTerm r.prevLogIndex + jp x + else do + setV fun v => { v with leaderId := some from_ } + let v ← getV + if r.prevLogIndex < v.commitIdx then + pure () + else if r.prevLogIndex > v.lastIdx then + pure () + else + aeApply from_ r payload + +theorem recvAppendEntries_eq (from_ : NodeId) (r : AppendEntriesRequest) + : recvAppendEntries from_ r + = (do + traceRecv "recv_append_entries" from_ (.appendEntriesRequest r) + let c ← get + let payload := (r.entries.map (toExecEntry c.env)).toArray + let v ← getV + let jp : Unit -> M Unit := + fun _ => do + let v ← getV + let jp : Unit -> M Unit := fun _ => aeMatch from_ r payload v + if (v.leadership == .leader && v.currentView == r.term) = true then do + let l ← curLoc + let x ← + fail + (toString l + ++ toString ": AppendEntries from " + ++ toString from_ + ++ toString " to a leader in its own view " + ++ toString r.term) + jp x + else + jp () + if (v.currentView == r.term + && (v.leadership == .candidate || v.leadership == .preVoteCandidate)) + = true then do + let x ← becomeAwareOfNewTerm r.term + jp x + else if v.currentView < r.term then + do + let x ← becomeAwareOfNewTerm r.term + jp x + else if v.currentView > r.term then + do + nack from_ + pure () + else + jp ()) := by + unfold recvAppendEntries + refine congrArg (fun k => traceRecv _ _ _ >>= k) (funext fun _ => ?_) + refine congrArg (fun k => get >>= k) (funext fun c => ?_) + refine congrArg (fun k => getV >>= k) (funext fun v => ?_) + refine ite_congr rfl (fun _ => ?_) fun _ => ite_congr rfl (fun _ => ?_) fun _ => + ite_congr rfl (fun _ => rfl) fun _ => ?_ + all_goals first + | refine congrArg (fun k => Exec.becomeAwareOfNewTerm _ >>= k) (funext fun _ => ?_) + | skip + all_goals + refine congrArg (fun k => getV >>= k) (funext fun w => ?_) + refine ite_congr rfl (fun _ => ?_) (fun _ => ?_) + all_goals first + | refine congrArg (fun k => curLoc >>= k) (funext fun l => ?_) + refine congrArg (fun k => Exec.fail _ >>= k) (funext fun x => ?_) + | skip + all_goals + show _ = aeMatch from_ r _ w + unfold aeMatch + refine ite_congr rfl (fun _ => rfl) (fun _ => ?_) + refine congrArg (fun k => setV _ >>= k) (funext fun _ => ?_) + refine congrArg (fun k => getV >>= k) (funext fun u => ?_) + refine ite_congr rfl (fun _ => rfl) (fun _ => ite_congr rfl (fun _ => rfl) (fun _ => ?_)) + unfold aeApply + refine congr (congrArg (fun f k => forIn _ _ f >>= k) ?_) (funext fun t => ?_) + · funext i s + exact rfl + · obtain ⟨a, b⟩ := t + cases a + · show _ = (do let t ← forIn b (none, ()) (execBody from_ r); _) + refine congr (congrArg (fun f k => forIn _ _ f >>= k) ?_) (funext fun t => ?_) + · funext x s + exact rfl + · obtain ⟨a, b⟩ := t + cases a + · exact rfl + · rfl + · rfl + +/-- `Good` at a fixed last index. -/ +def GN (p : Par) (n : Nat) (c : Core) : Prop := + Good p c /\ c.lastIdx = n + +theorem GN.nl {p : Par} {n : Nat} : forall c, GN p n c -> c.leadership ≠ .leader := + fun _ g => g.1.nl + +theorem ginv_viewUpdate {env : Env} {p : Par} {n : Nat} (idx t : Nat) (ht : t <= p.view) + : GInv env (GN p n) (viewUpdate idx t) := by + unfold viewUpdate + refine GInv.getV_bind fun _ _ => ?_ + intro + have hs : GInv env (GN p n) (setV fun v : State => + { v with views := v.views ++ Array.replicate (t - v.views.size) idx }) := by + refine GInv.setV fun v g => ?_ + refine ⟨{ g.1 with views := ?_ }, g.2⟩ + have := g.1.views + simp only [core, Array.size_append, Array.size_replicate] at this ⊢ + omega + apply GInv.ite + · intro _; exact GInv.bind (GInv.keeps Spec.curLoc) fun _ => GInv.bind (GInv.fail _) fun _ => hs + · intro _; exact hs + +theorem sigsIn_succ (ledger : Array Exec.Entry) {lo hi : Nat} (h : lo <= hi) + : sigsIn ledger lo (hi + 1) + = sigsIn ledger lo hi ++ (if ledger[hi]?.any (·.sig) then [hi + 1] else []) := by + unfold sigsIn + rw [show hi + 1 - lo = (hi - lo) + 1 by omega, List.range'_1_concat, List.filter_append, + show lo + 1 + (hi - lo) = hi + 1 by omega] + simp only [List.filter_cons, List.filter_nil, Nat.add_sub_cancel] + +theorem sigsIn_congr {a b : Array Exec.Entry} {lo hi : Nat} + (h : forall j, lo < j -> j <= hi -> a[j - 1]? = b[j - 1]?) + : sigsIn a lo hi = sigsIn b lo hi := by + unfold sigsIn + apply List.filter_congr + intro j hj + rw [List.mem_range'_1] at hj + rw [h j (by omega) (by omega)] + +/-- The core after pushing entry `e` at index `i`, with its signature in `committable`. -/ +def pushed (c : Core) (i : Nat) (e : Exec.Entry) : Core := + { + c with + ledger := (c.ledger.extract 0 (i - 1)).push e + committable := c.committable ++ (if e.sig then [i] else []) + } + +theorem good_push {p : Par} {i : Nat} {e : Exec.Entry} {c : Core} + (hi : p.lx[i - 1]? = some e) (h1 : 1 <= i) + (g : Good p { c with lastIdx := i - 1 }) (hl : c.lastIdx = i) + : Good p (pushed c i e) := by + have gs := g.size + have gl := g.ledger + have gL := g.last + have gc := g.committable + have gci := g.ci + simp only at gs gl gL gc gci + have hx : c.ledger.extract 0 (i - 1) = c.ledger := by + rw [Array.extract_eq_self_iff]; omega + have hlx : i <= p.lx.length := by + have := (List.getElem?_eq_some_iff.mp hi).1; omega + unfold pushed + refine { g with size := ?_, ledger := ?_, last := ?_, committable := ?_, ci := ?_ } + · simp only [hx, Array.size_push, hl]; omega + · simp only [hx, Array.toList_push, gl, hl] + rw [show i = (i - 1) + 1 by omega, List.take_add_one, hi] + simp + · simp only [hl]; exact hlx + · simp only [hx, hl] + rw [show i = (i - 1) + 1 by omega, sigsIn_succ _ gci, gc] + rw [sigsIn_congr (b := c.ledger.push e) fun j hj1 hj2 => ?_] + · simp only [Array.getElem?_push] + simp [gs] + · rw [Array.getElem?_push]; simp only [gs] + split + · omega + · rfl + · simp only [hl]; omega + +/-- `x` takes the core from `G` to `H` and sends nothing. -/ +def GT {α : Type} (env : Env) (G : Core -> Prop) (H : α -> Core -> Prop) (x : M α) + : Prop := + forall o0 : Outbox, + Hoare env (fun v o => G (core v) /\ o = o0) x (fun a v o => H a (core v) /\ o = o0) + +namespace GT +variable {env : Env} + +theorem of_ginv {α : Type} {G : Core -> Prop} {x : M α} (h : GInv env G x) + : GT env G (fun _ => G) x := + h + +theorem bind {α β : Type} {G : Core -> Prop} {H : α -> Core -> Prop} + {K : β -> Core -> Prop} {x : M α} {f : α -> M β} (hx : GT env G H x) + (hf : forall a, GT env (H a) K (f a)) + : GT env G K (x >>= f) := + fun o0 => Hoare.bind (hx o0) fun a => hf a o0 + +theorem setV {G : Core -> Prop} {H : Unit -> Core -> Prop} {f : State -> State} + (hf : forall v, G (core v) -> H () (core (f v))) + : GT env G H (Exec.setV f) := + fun _ => Hoare.setV f fun v _ ⟨g, ho⟩ => ⟨hf v g, ho⟩ + +theorem pure {α : Type} {G : Core -> Prop} {H : α -> Core -> Prop} (a : α) + (h : forall c, G c -> H a c) + : GT env G H (Pure.pure a : M α) := + fun _ => Hoare.pure a fun _ _ ⟨g, ho⟩ => ⟨h _ g, ho⟩ + +theorem fail {α : Type} {G : Core -> Prop} {H : α -> Core -> Prop} (m : String) + : GT env G H (Exec.fail m : M α) := + fun _ => Hoare.fail m + +theorem getV_bind {β : Type} {G : Core -> Prop} {H : β -> Core -> Prop} {k : State -> M β} + (hk : forall s, G (core s) -> GT env (fun c => G c /\ c = core s) H (k s)) + : GT env G H (Exec.getV >>= k) := by + intro o0 + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v0 o1 ⟨⟨g, ho1⟩, hv⟩ => ?_ + subst hv ho1 + exact Hoare.pre (hk v0 g o1) fun v o ⟨hv, ho⟩ => ⟨⟨by rw [hv]; exact g, by rw [hv]⟩, ho⟩ + +theorem pre {α : Type} {G G' : Core -> Prop} {H : α -> Core -> Prop} {x : M α} + (h : GT env G' H x) (imp : forall c, G c -> G' c) + : GT env G H x := + fun o0 => Hoare.pre (h o0) fun _ _ ⟨g, ho⟩ => ⟨imp _ g, ho⟩ + +theorem post {α : Type} {G : Core -> Prop} {H H' : α -> Core -> Prop} {x : M α} + (h : GT env G H x) (imp : forall a c, H a c -> H' a c) + : GT env G H' x := + fun o0 => Hoare.post (h o0) fun _ _ _ ⟨g, ho⟩ => ⟨imp _ _ g, ho⟩ + +theorem ite {α : Type} {G : Core -> Prop} {H : α -> Core -> Prop} {b : Prop} [Decidable b] + {x y : M α} (hx : b -> GT env G H x) (hy : Not b -> GT env G H y) + : GT env G H (if b then x else y) := by + by_cases h : b + · simpa [h] using hx h + · simpa [h] using hy h + +end GT + +theorem ginv_execTail {env : Env} {p : Par} {i : Nat} (lim : Nat) (hlim : lim = p.lim) + : GT env (GN p i) (fun _ => GN p i) (commitIfPossible lim) := by + subst hlim + intro o0 + exact Hoare.post (Hoare.pre (hoare_cip (n := i) o0) fun _ _ ⟨⟨g, hn⟩, ho⟩ => ⟨g, hn, ho⟩) + fun _ _ _ ⟨g, hn, _, ho⟩ => ⟨⟨g, hn⟩, ho⟩ + +/-- Between setting `lastIdx := i` and pushing entry `i`. -/ +def Mid (p : Par) (i : Nat) (c : Core) : Prop := + c.lastIdx = i /\ Good p { c with lastIdx := i - 1 } + +theorem Mid.nl {p : Par} {i : Nat} : forall c, Mid p i c -> c.leadership ≠ .leader := + fun _ g => g.2.nl + +/-- After pushing entry `i`, before recording it as committable. -/ +def Pushed (p : Par) (i : Nat) (e : Exec.Entry) (c : Core) : Prop := + c.lastIdx = i + /\ Good p { c with committable := c.committable ++ (if e.sig then [i] else []) } + +theorem Pushed.nl {p : Par} {i : Nat} {e : Exec.Entry} + : forall c, Pushed p i e c -> c.leadership ≠ .leader := + fun _ g => g.2.nl + +theorem gt_exec {env : Env} {p : Par} (from_ : NodeId) (r : AppendEntriesRequest) + {i : Nat} {e : Exec.Entry} (s : Option Unit × Unit) (hi : p.lx[i - 1]? = some e) + (h1 : 1 <= i) (hv1 : r.term <= p.view) (hv2 : e.term <= p.view) + (hlim : min r.primaryCommit (aeIdx r) = p.lim) + : GT env (GN p (i - 1)) (fun st c => st = .yield (none, ()) /\ GN p i c) + (execBody from_ r (i, e, true) s) := by + unfold execBody + refine GT.bind (GT.of_ginv (GInv.keeps (Spec.trace _))) fun _ => ?_ + refine GT.bind (GT.of_ginv (GInv.keeps (Spec.emitStr _ _))) fun _ => ?_ + refine GT.ite (fun _ => ?_) (fun h => absurd rfl h) + refine GT.bind (H := fun _ => Mid p i) (GT.setV fun v g => ?_) fun _ => ?_ + · obtain ⟨g, hn⟩ := g + refine ⟨rfl, ?_⟩ + have hc : { core { v with lastIdx := i } with lastIdx := i - 1 } = core v := by + simp only [core] at hn ⊢ + rw [hn] + rw [hc] + exact g + refine GT.bind (GT.of_ginv (GInv.forIn_list _ _ fun _ _ _ => + GInv.bind (GInv.keeps (Spec.trace _)) fun _ => + GInv.bind (GInv.keeps (Spec.emitNat _ _)) fun _ => + GInv.bind (GInv.keeps (Spec.emitStr _ _)) fun _ => GInv.pure _)) fun _ => ?_ + extract_lets j1 j2 j3 j4 + have k1 : forall u, GT env (GN p i) (fun (st : ForInStep (Option Unit × Unit)) c => + st = .yield (none, ()) /\ GN p i c) (j1 u) := fun _ => + GT.bind (ginv_execTail _ hlim) fun _ => GT.pure _ fun _ g => ⟨rfl, g⟩ + have k2 : e.sig = true -> forall u, GT env (Pushed p i e) (fun st c => + st = .yield (none, ()) /\ GN p i c) (j2 u) := fun hs _ => by + refine GT.bind (H := fun _ => GN p i) (GT.setV fun v g => ?_) fun _ => ?_ + · obtain ⟨hl, g⟩ := g + simp only [hs, ite_true] at g + exact ⟨g, hl⟩ + · refine GT.ite (fun _ => GT.ite (fun _ => GT.bind (GT.of_ginv (ginv_viewUpdate _ _ hv1)) k1) + (fun _ => GT.bind (GT.of_ginv (ginv_viewUpdate _ _ hv2)) k1)) + (fun _ => GT.pure _ fun _ g => ⟨rfl, g⟩) + have k3 : forall u, GT env (Mid p i) (fun st c => + st = .yield (none, ()) /\ GN p i c) (j3 u) := fun _ => by + refine GT.bind (H := fun _ => Pushed p i e) (GT.setV fun v g => ?_) fun _ => ?_ + · exact ⟨g.1, good_push hi h1 g.2 g.1⟩ + · refine GT.ite (fun hs => GT.getV_bind fun _ _ => GT.pre (G' := Pushed p i e) ?_ fun _ g => g.1) + (fun hs => GT.pure _ fun c g => ⟨rfl, ?_, g.1⟩) + · exact GT.ite (fun _ => GT.bind (GT.of_ginv (GInv.of_frame Pushed.nl + (frame_becomeRetired _ _ _ (by decide)))) (k2 hs)) (fun _ => k2 hs ()) + · have g := g.2 + simp only [hs, Bool.false_eq_true, ite_false, List.append_nil] at g + exact g + have k4 : forall u, GT env (Mid p i) (fun st c => + st = .yield (none, ()) /\ GN p i c) (j4 u) := fun _ => + GT.ite (fun _ => GT.bind (GT.of_ginv (GInv.of_frame Mid.nl (frame_startTicking _))) k3) + (fun _ => k3 ()) + split + · exact GT.bind (GT.of_ginv (GInv.of_frame Mid.nl (frame_addConfiguration _ _ _))) fun _ => k4 () + · exact k4 () + +theorem ginv_viewUpdate' {env : Env} {p : Par} {n m : Nat} (idx t : Nat) + (ht : t <= p.view) + : GInv env (fun c => GN p n c /\ c.commitIdx = m) (viewUpdate idx t) := by + unfold viewUpdate + refine GInv.getV_bind fun _ _ => ?_ + extract_lets jp + have hs : GInv env (fun c => GN p n c /\ c.commitIdx = m) (setV fun v : State => + { v with views := v.views ++ Array.replicate (t - v.views.size) idx }) := by + refine GInv.setV fun v ⟨g, hm⟩ => ⟨⟨{ g.1 with views := ?_ }, g.2⟩, hm⟩ + have := g.1.views + simp only [core, Array.size_append, Array.size_replicate] at this ⊢ + omega + apply GInv.ite + · intro _; exact GInv.bind (GInv.keeps Spec.curLoc) fun _ => GInv.bind (GInv.fail _) fun _ => hs + · intro _; exact hs + +theorem hoare_sendAer {env : Env} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (to : NodeId) (term idx : Nat) (ok : Bool) + (imp + : forall v o, + P v o + -> Q () v + (o + ++ [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id to) + (.appendEntriesResponse + { term := term, success := ok, lastLogIndex := idx })])) + : Hoare env P (sendAer to term idx ok) Q := by + unfold sendAer + refine Hoare.bind (Hoare.keeps (Spec.trace _) fun _ _ _ p => p) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.emit _ _) fun _ _ _ p => p) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.emitStr _ _) fun _ _ _ p => p) fun _ => ?_ + exact Hoare.send _ _ imp + +/-- The ACK the accept path sends. -/ +def ack (env : Env) (from_ : NodeId) (r : AppendEntriesRequest) (v : State) : Outbox := + [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id from_) + (.appendEntriesResponse + { term := v.currentView, success := true, lastLogIndex := aeIdx r })] + +theorem hoare_finish {env : Env} {p : Par} (from_ : NodeId) (r : AppendEntriesRequest) + (hv1 : r.term <= p.view) (hv2 : aeTermOfIdx r <= p.view) + (hlim : min r.primaryCommit (aeIdx r) = p.lim) + : Hoare env (fun v o => GN p p.lx.length (core v) /\ o = []) (aeFinish from_ r) + (fun _ v o => + GN p p.lx.length (core v) /\ v.commitIdx = p.bd /\ o = ack env from_ r v) := by + unfold aeFinish + rw [hlim] + refine Hoare.bind (R := fun _ v o => (GN p p.lx.length (core v) /\ v.commitIdx = p.bd) + /\ o = []) (Hoare.post (Hoare.pre (hoare_cip (n := p.lx.length) []) + fun _ _ ⟨⟨g, hn⟩, ho⟩ => ⟨g, hn, ho⟩) + fun _ _ _ ⟨g, hn, hb, ho⟩ => ⟨⟨⟨g, hn⟩, hb rfl⟩, ho⟩) fun _ => ?_ + refine Hoare.getV_bind fun _ => Hoare.pre (P' := fun v o => + (GN p p.lx.length (core v) /\ v.commitIdx = p.bd) /\ o = []) ?_ fun _ _ h => h.1 + extract_lets lci jp + have k : forall u, Hoare env (fun v o => + (GN p p.lx.length (core v) /\ v.commitIdx = p.bd) /\ o = []) (jp u) + (fun _ v o => GN p p.lx.length (core v) /\ v.commitIdx = p.bd + /\ o = ack env from_ r v) := fun _ => + Hoare.getV_bind fun _ => hoare_sendAer _ _ _ _ fun v o ⟨⟨⟨g, hb⟩, ho⟩, hv⟩ => by + subst hv ho + exact ⟨g, hb, rfl⟩ + refine Hoare.ite (fun _ => Hoare.bind (ginv_viewUpdate' _ _ hv1 []) k) + (fun _ => Hoare.ite (fun _ => Hoare.bind (ginv_viewUpdate' _ _ hv2 []) k) fun _ => k ()) + +/-- The execute loop's work list: entries `n0 + 1 ..` of the final ledger, all accepted. -/ +def Work (p : Par) (n0 : Nat) (l : List (Nat × Exec.Entry × Bool)) : Prop := + forall k (hk : k < l.length), + l[k].1 = n0 + k + 1 + /\ p.lx[n0 + k]? = some l[k].2.1 + /\ l[k].2.2 = true + /\ l[k].2.1.term <= p.view + +theorem gt_execLoop {env : Env} {p : Par} (from_ : NodeId) (r : AppendEntriesRequest) + (n0 : Nat) (l : List (Nat × Exec.Entry × Bool)) (hl : Work p n0 l) + (hv1 : r.term <= p.view) (hlim : min r.primaryCommit (aeIdx r) = p.lim) + : GT env (GN p n0) (fun t c => t.fst = none /\ GN p (n0 + l.length) c) + (forIn l (none, ()) (execBody from_ r)) := by + intro o0 + refine Hoare.pre + (Hoare.forIn_list l (none, ()) _ + (fun pre b v o => b = (none, ()) /\ GN p (n0 + pre.length) (core v) /\ o = o0) + (fun t v o => (t.fst = none /\ GN p (n0 + l.length) (core v)) /\ o = o0) ?_ ?_) + fun _ _ ⟨g, ho⟩ => ⟨rfl, by simpa using g, ho⟩ + · intro pre a rest b he + have hk : pre.length < l.length := by rw [he]; simp + have ha : l[pre.length] = a := by simp [he] + obtain ⟨h1, h2, h3, h4⟩ := hl _ hk + rw [ha] at h1 h2 h3 h4 + obtain ⟨i, e, ok⟩ := a + simp only at h1 h2 h3 h4 + subst h1 h3 + refine Hoare.pin fun v0 o1 ⟨hb, g, ho⟩ => ?_ + subst hb ho + refine Hoare.post (Hoare.pre (gt_exec (env := env) (i := n0 + pre.length + 1) from_ r + (none, ()) (by simpa using h2) (by omega) hv1 h4 hlim o1) ?_) ?_ + · rintro _ _ ⟨rfl, rfl⟩ + exact ⟨by simpa using g, rfl⟩ + · rintro st v o ⟨⟨rfl, g⟩, ho⟩ + refine ⟨rfl, ?_, ho⟩ + simpa [Nat.add_assoc] using g + · rintro b v o ⟨rfl, g, ho⟩ + exact ⟨⟨rfl, g⟩, ho⟩ + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean new file mode 100644 index 000000000000..346bdefb1427 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean @@ -0,0 +1,204 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeHoare +public import Consensus.TraceValidation.Aft + +@[expose] public section + +/-! +# Helpers that leave the AppendEntries-relevant state alone (not reviewed) + +`core v` collects the declared fields the AppendEntries proof tracks. `Frame env x`: on a +non-leader, `x` keeps `core` and sends nothing. Configuration hooks, peer bookkeeping and +retirement phases other than `retired_committed` are frames. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +structure Core where + nodeId : NodeId + currentView : Nat + votedFor : Option NodeId + isNewFollower : Bool + ledger : Array Exec.Entry + lastIdx : Nat + commitIdx : Nat + committable : List Nat + views : Array Nat + leadership : Leadership + leaderId : Option NodeId + retiredCommittedIdx : Option Nat + rcEntries : List (Nat × List NodeId) + +def core (v : State) : Core := + ⟨ + v.nodeId, + v.currentView, + v.votedFor, + v.isNewFollower, + v.ledger, + v.lastIdx, + v.commitIdx, + v.committable, + v.views, + v.leadership, + v.leaderId, + v.retiredCommittedIdx, + v.rcEntries + ⟩ + +def Frame {α : Type} (env : Env) (x : M α) : Prop := + forall (c0 : Core) (o0 : Outbox), + c0.leadership ≠ .leader + -> Hoare env (fun v o => core v = c0 /\ o = o0) x (fun _ v o => core v = c0 /\ o = o0) + +namespace Frame +variable {env : Env} + +theorem keeps {α : Type} {x : M α} (h : Spec.Keeps env x) : Frame env x := + fun _ _ _ => Hoare.keeps h fun _ _ _ p => p + +theorem bind {α β : Type} {x : M α} {f : α -> M β} (hx : Frame env x) + (hf : forall a, Frame env (f a)) + : Frame env (x >>= f) := + fun c0 o0 h => Hoare.bind (hx c0 o0 h) fun a => hf a c0 o0 h + +theorem getV_bind {β : Type} {k : State -> M β} + (hk : forall s, s.leadership ≠ .leader -> Frame env (k s)) + : Frame env (Exec.getV >>= k) := by + intro c0 o0 h + refine Hoare.getV_bind fun s => ?_ + by_cases hs : s.leadership ≠ .leader + · exact Hoare.pre (hk s hs c0 o0 h) fun _ _ p => p.1 + · refine Hoare.false_pre fun v o ⟨⟨hc, _⟩, hv⟩ => ?_ + subst hv hc + exact hs h + +theorem ite {α : Type} {b : Prop} [Decidable b] {x y : M α} (hx : b -> Frame env x) + (hy : Not b -> Frame env y) + : Frame env (if b then x else y) := by + by_cases h : b + · simpa [h] using hx h + · simpa [h] using hy h + +theorem pure {α : Type} (a : α) : Frame env (Pure.pure a : M α) := + keeps (Spec.Keeps.pure a) + +theorem fail {α : Type} (m : String) : Frame env (Exec.fail m : M α) := + fun _ _ _ => Hoare.fail m + +theorem setV {f : State -> State} + (hf : forall v, v.leadership ≠ .leader -> core (f v) = core v) + : Frame env (Exec.setV f) := by + intro c0 o0 h + refine Hoare.setV f fun v o ⟨hc, ho⟩ => ⟨?_, ho⟩ + rw [hf v (by subst hc; exact h), hc] + +theorem trace (fn : String) : Frame env (Exec.trace fn) := keeps (Spec.trace fn) + +theorem emit (k : String) (j : Lean.Json) : Frame env (Exec.emit k j) := + keeps (Spec.emit k j) + +theorem emitStr (k s : String) : Frame env (Exec.emitStr k s) := keeps (Spec.emitStr k s) + +theorem emitNat (k : String) (n : Nat) : Frame env (Exec.emitNat k n) := + keeps (Spec.emitNat k n) + +theorem curLoc : Frame env Exec.curLoc := keeps Spec.curLoc +theorem inNat (k : String) : Frame env (Exec.inNat k) := keeps (Spec.inNat k) +theorem use (k : String) : Frame env (Exec.use k) := keeps (Spec.use k) + +theorem liftE {α : Type} (x : Except String α) : Frame env (Exec.liftE x) := + keeps (Spec.liftE x) + +theorem forIn_list {α β : Type} (l : List α) (init : β) {f : α -> β -> M (ForInStep β)} + (hf : forall a b, Frame env (f a b)) + : Frame env (forIn l init f) := by + induction l generalizing init with + | nil => exact pure init + | cons a rest ih => + rw [List.forIn_cons] + refine bind (hf a init) fun r => ?_ + cases r with + | done b => exact pure b + | yield b => exact ih b + +theorem option {α β : Type} {o : Option α} {x : M β} {f : α -> M β} (hx : Frame env x) + (hf : forall a, Frame env (f a)) + : Frame env + (match o with + | none => x + | some a => f a) := by + cases o + · exact hx + · exact hf _ + +end Frame + +/-- Extension point: `Frame` lemmas for named helpers. -/ +syntax "frame_ext" : tactic +macro_rules | `(tactic| frame_ext) => `(tactic| fail "no frame lemma") + +/-- Decompose a handler into `Frame` rules. -/ +macro "frame_tac" : tactic => + `(tactic| repeat' (first + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.pure _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.fail _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.trace _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.emit _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.emitStr _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.emitNat _ _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.curLoc + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.inNat _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.use _ + | with_reducible exact Consensus.TraceValidation.Proofs.Ae.Frame.liftE _ + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.getV_bind + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.bind + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.ite + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.forIn_list + | with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.option + | ((with_reducible apply Consensus.TraceValidation.Proofs.Ae.Frame.setV); intro _ _; + first + | rfl + | (simp only [Consensus.TraceValidation.Proofs.Ae.core, + Consensus.TraceValidation.Exec.State.setPeer]; done)) + | frame_ext + | (exfalso; simp_all; done) + | (with_reducible intro) + | dsimp only + | with_reducible split)) + +theorem frame_startTicking (env : Env) : Frame env Exec.startTickingIfNecessary := by + unfold Exec.startTickingIfNecessary + refine Frame.setV fun v _ => ?_ + split <;> rfl + +theorem frame_createAndRemove (env : Env) : Frame env Exec.createAndRemoveNodeState := by + unfold Exec.createAndRemoveNodeState + frame_tac + +macro_rules | `(tactic| frame_ext) => `(tactic| exact frame_createAndRemove _) +macro_rules | `(tactic| frame_ext) => `(tactic| exact frame_startTicking _) + +theorem frame_becomeRetired (env : Env) (idx : Nat) (phase : Phase) + (h : phase ≠ .retiredCommitted) + : Frame env (Exec.becomeRetired idx phase) := by + unfold Exec.becomeRetired + cases phase + all_goals first | exact absurd rfl h | skip + all_goals frame_tac + +macro_rules | `(tactic| frame_ext) => `(tactic| exact frame_becomeRetired _ _ _ (by decide)) + +theorem frame_addConfiguration (env : Env) (idx : Option Nat) (nodes : Option Nodes) + : Frame env (Exec.addConfiguration idx nodes) := by + unfold Exec.addConfiguration + frame_tac + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeMatch.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeMatch.lean new file mode 100644 index 000000000000..850812108c42 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeMatch.lean @@ -0,0 +1,244 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeLemmas + +@[expose] public section + +/-! +# `find_highest_possible_match` (not reviewed) + +Under `inv`, cft.h's view-history walk `State.highestMatch` computes the clean +`findHighestPossibleMatch` of the abstract log: both are the highest index at or below +`min idx lastIdx` whose term is at most `term`. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- Adjacent order implies pairwise order. -/ +theorem pairwise_of_zip_tail + : forall w : List Nat, + (w.zip w.tail).all (fun (x, y) => decide (x <= y)) = true -> w.Pairwise (· <= ·) + | [], _ => List.Pairwise.nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: rest, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true, + decide_eq_true_eq] at h + have ih := pairwise_of_zip_tail (b :: rest) (by simpa using h.2) + refine List.Pairwise.cons ?_ ih + intro y hy + rcases List.mem_cons.mp hy with rfl | hy + · exact h.1 + · exact Nat.le_trans h.1 ((List.pairwise_cons.mp ih).1 y hy) + +/-- In a sorted list, the first `count` elements are exactly those at or below `q`. -/ +theorem sorted_le_iff + : forall {w : List Nat}, + w.Pairwise (· <= ·) + -> forall (q k : Nat) (hk : k < w.length), + w[k] <= q <-> k < (w.filter (· <= q)).length + | [], _, _, _, hk => absurd hk (Nat.not_lt_zero _) + | a :: w, hs, q, k, hk => by + have hs' := List.pairwise_cons.mp hs + by_cases ha : a <= q + · have hf : ((a :: w).filter (· <= q)).length = (w.filter (· <= q)).length + 1 := by + simp [ha] + rw [hf] + cases k with + | zero => simp [ha] + | succ k => + have := sorted_le_iff hs'.2 q k (by simpa using hk) + simp only [List.getElem_cons_succ] + omega + · have hnil : (a :: w).filter (· <= q) = [] := by + rw [List.filter_eq_nil_iff] + intro x hx + rcases List.mem_cons.mp hx with rfl | hx + · simpa using ha + · have := hs'.1 x hx; simp; omega + rw [hnil] + cases k with + | zero => simpa using ha + | succ k => + have := hs'.1 _ (List.getElem_mem (l := w) (n := k) (by simpa using hk)) + simp only [List.getElem_cons_succ, List.length_nil, Nat.not_lt_zero, iff_false] + omega + +/-- `highestMatch`'s answer for `probe`: the highest index at or below it whose view is at most `t`. -/ +def IsHM (v : State) (t q x : Nat) : Prop := + x <= q /\ v.viewAt x <= t /\ forall c, c <= q -> v.viewAt c <= t -> c <= x + +theorem IsHM.unique {v : State} {t q x y : Nat} (hx : IsHM v t q x) (hy : IsHM v t q y) + : x = y := + Nat.le_antisymm (hy.2.2 x hx.1 hx.2.1) (hx.2.2 y hy.1 hy.2.1) + +section +variable {v : State} + +private theorem viewAt_eq (q : Nat) + : v.viewAt q = (v.views.toList.filter (· <= q)).length := + rfl + +theorem viewAt_mono' {i j : Nat} (ij : i <= j) : v.viewAt i <= v.viewAt j := by + unfold State.viewAt + simp only [← List.countP_eq_length_filter] + apply List.countP_mono_left + intro x _ h + simp only [decide_eq_true_eq] at h ⊢ + omega + +theorem viewAt_le_size' (i : Nat) : v.viewAt i <= v.views.size := by + unfold State.viewAt + have := List.length_filter_le (fun x => decide (x <= i)) v.views.toList + simpa using this + +variable (sorted : v.views.toList.Pairwise (· <= ·)) (pos : v.views.all (0 < ·) = true) +include sorted + +/-- With `tp = viewAt q` positive, view `tp` starts at or below `q` and `startOfView` finds it. -/ +theorem startOfView_viewAt {q : Nat} (tp1 : 1 <= v.viewAt q) + : exists st, + v.startOfView (v.viewAt q) = st + /\ st <= q + /\ st ∈ v.views + /\ (forall c, st <= c -> v.viewAt q <= v.viewAt c) + /\ (0 < st -> v.viewAt (st - 1) < v.viewAt q) := by + have hsz := viewAt_le_size' (v := v) q + have hk : v.viewAt q - 1 < v.views.toList.length := by simp; omega + have hst := (sorted_le_iff sorted q (v.viewAt q - 1) hk).mpr (by rw [← viewAt_eq]; omega) + refine ⟨v.views.toList[v.viewAt q - 1], ?_, hst, ?_, ?_, ?_⟩ + · unfold State.startOfView + have c1 : ¬ (v.viewAt q > v.views.size || v.viewAt q == 0) = true := by + simp; omega + simp only [c1] + have e1 : v.views[v.viewAt q - 1]! = v.views.toList[v.viewAt q - 1] := by + simp [getElem!_pos, show v.viewAt q - 1 < v.views.size by omega] + rw [e1] + by_cases hlt : v.viewAt q + 1 <= v.views.size + · have hk2 : v.viewAt q < v.views.toList.length := by simp; omega + have hgt := (not_congr (sorted_le_iff sorted q (v.viewAt q) hk2)).mpr + (by rw [← viewAt_eq]; omega) + have e2 : v.views[v.viewAt q]! = v.views.toList[v.viewAt q] := by + simp [getElem!_pos, show v.viewAt q < v.views.size by omega] + have : (v.views[v.viewAt q]! == v.views.toList[v.viewAt q - 1]) = false := by + rw [e2]; simp only [beq_eq_false_iff_ne, ne_eq]; omega + simp only [hlt, this, decide_true, Bool.and_false, Bool.false_eq_true, ite_false] + · simp [hlt] + · have := List.getElem_mem hk + simp + · intro c hc + have := (sorted_le_iff sorted c (v.viewAt q - 1) hk).mp hc + rw [← viewAt_eq] at this + omega + · intro hp + refine Nat.lt_of_not_le fun hge => ?_ + have := (sorted_le_iff sorted (v.views.toList[v.viewAt q - 1] - 1) (v.viewAt q - 1) hk).mpr + (by rw [← viewAt_eq]; omega) + omega + +include pos + +theorem highestMatchGo_spec (t : Nat) + : forall (f q : Nat), + v.viewAt q < f -> IsHM v t q (v.highestMatchGo t q (v.viewAt q) f) + | 0, _, h => absurd h (Nat.not_lt_zero _) + | f + 1, q, h => by + unfold State.highestMatchGo + by_cases ht : v.viewAt q > t + · simp only [ht, ite_true] + obtain ⟨st, hst, stq, mem, above, below⟩ := startOfView_viewAt sorted (q := q) (by omega) + rw [hst] + have stpos : 0 < st := by + have := (Array.all_eq_true_iff_forall_mem.mp pos) _ mem + simpa using this + simp only [stpos, ite_true] + have r := highestMatchGo_spec t f (st - 1) (by have := below stpos; omega) + refine ⟨by have := r.1; omega, r.2.1, fun c hc hct => ?_⟩ + by_cases hcs : st <= c + · have := above c hcs; omega + · exact r.2.2 c (by omega) hct + · simp only [ht, ite_false] + exact ⟨Nat.le_refl _, by omega, fun c hc _ => hc⟩ + +theorem highestMatch_spec (t idx : Nat) + : IsHM v t (min idx v.lastIdx) (v.highestMatch t idx) := by + unfold State.highestMatch + exact highestMatchGo_spec sorted pos t _ _ + (by have := viewAt_le_size' (v := v) (min idx v.lastIdx); omega) + +end + +theorem foldMax_prop_cases (p : Nat -> Prop) [DecidablePred p] (l : List Nat) (b : Nat) + : l.foldl (fun best i => if p i then max best i else best) b = b + \/ (p (l.foldl (fun best i => if p i then max best i else best) b) + /\ l.foldl (fun best i => if p i then max best i else best) b ∈ l) := by + induction l generalizing b with + | nil => exact Or.inl rfl + | cons x xs ih => + simp only [List.foldl_cons] + rcases ih (if p x then max b x else b) with h | h + · rw [h] + by_cases hx : p x + · simp only [hx, ite_true] + rcases Nat.le_total b x with hb | hb + · rw [Nat.max_eq_right hb]; exact Or.inr ⟨hx, List.mem_cons_self⟩ + · rw [Nat.max_eq_left hb]; exact Or.inl rfl + · simp [hx] + · exact Or.inr ⟨h.1, List.mem_cons_of_mem _ h.2⟩ + +theorem foldMax_prop_ge (p : Nat -> Prop) [DecidablePred p] (l : List Nat) (b : Nat) + : b <= l.foldl (fun best i => if p i then max best i else best) b + /\ forall i, + i ∈ l + -> p i + -> i <= l.foldl (fun best i => if p i then max best i else best) b := by + induction l generalizing b with + | nil => exact ⟨Nat.le_refl _, fun _ h => absurd h List.not_mem_nil⟩ + | cons x xs ih => + simp only [List.foldl_cons] + obtain ⟨ih1, ih2⟩ := ih (if p x then max b x else b) + refine ⟨Nat.le_trans (by split <;> omega) ih1, fun i hi hp => ?_⟩ + rcases List.mem_cons.mp hi with rfl | hi + · refine Nat.le_trans ?_ ih1 + simp only [hp, ite_true]; omega + · exact ih2 i hi hp + +/-- Under `inv`, cft.h's `find_highest_possible_match` is the clean one. -/ +theorem highestMatch_eq {names : Names} {v : State} (h : inv names v = true) (t idx : Nat) + : v.highestMatch t idx = findHighestPossibleMatch (abs names v).log idx t := by + have sorted : v.views.toList.Pairwise (· <= ·) := by + apply pairwise_of_zip_tail + inv_conj h "views_sorted" + obtain ⟨h1, -, -, -, h5, -, h7⟩ := inv_parts h + have hlen : (abs names v).log.length = v.lastIdx := by simp [abs, h1] + have hterm : forall c, 1 <= c -> c <= v.lastIdx -> termAt (abs names v).log c = v.viewAt c := by + intro c c1 cL + simp only [termAt_abs h1, show ¬ c = 0 by omega, ↓reduceIte, h5 c c1 cL]; rfl + refine IsHM.unique (highestMatch_spec sorted h7 t idx) ?_ + unfold findHighestPossibleMatch + rw [hlen] + generalize hF : (List.range (min idx v.lastIdx + 1)).foldl _ 0 = F + have ge := foldMax_prop_ge (fun c => c > 0 /\ termAt (abs names v).log c <= t) + (List.range (min idx v.lastIdx + 1)) 0 + rw [hF] at ge + refine ⟨?_, ?_, fun c hc hct => ?_⟩ + · rcases foldMax_prop_cases (fun c => c > 0 /\ termAt (abs names v).log c <= t) + (List.range (min idx v.lastIdx + 1)) 0 with e | e <;> rw [hF] at e + · omega + · have := List.mem_range.mp e.2; omega + · rcases foldMax_prop_cases (fun c => c > 0 /\ termAt (abs names v).log c <= t) + (List.range (min idx v.lastIdx + 1)) 0 with e | e <;> rw [hF] at e + · subst e; rw [viewAt_zero h7]; omega + · have := List.mem_range.mp e.2 + rw [← hterm F (by omega) (by omega)]; exact e.1.2 + · by_cases c0 : c = 0 + · omega + · exact ge.2 c (List.mem_range.mpr (by omega)) + ⟨by omega, by rw [hterm c (by omega) (by omega)]; exact hct⟩ + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRecv.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRecv.lean new file mode 100644 index 000000000000..47e279b79430 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRecv.lean @@ -0,0 +1,298 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeScan + +@[expose] public section + +/-! +# The whole AppendEntries handler (not reviewed) + +`hoare_recv` runs `recvAppendEntries` from the released state `saved` and lists its ends +(`AeOut`): a stale-term NACK; past the term phase (`aeMid`), a log-mismatch NACK +(`nackOut`); a silent return before the commit index or past the log; a silent conflict; or +the accepting run, with `GN` over the parameters `aePar` and the ACK. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- The declared state after the term phase. -/ +def aeMid (r : AppendEntriesRequest) (v : State) : State := + if (v.currentView == r.term + && (v.leadership == .candidate || v.leadership == .preVoteCandidate)) + = true then + bant r.term v + else if v.currentView < r.term then + bant r.term v + else + v + +/-- The declared state when the request matches the log. -/ +def aeU (from_ : NodeId) (r : AppendEntriesRequest) (v : State) : State := + { aeMid r v with leaderId := some from_ } + +def aerOut (env : Env) (from_ : NodeId) (v : State) (term idx : Nat) (ok : Bool) + : Outbox := + [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id from_) + (.appendEntriesResponse { term := term, success := ok, lastLogIndex := idx })] + +/-- The NACK of a mismatching request. -/ +def nackOut (env : Env) (from_ : NodeId) (r : AppendEntriesRequest) (v : State) + : Outbox := + if v.getTerm r.prevLogIndex = 0 then + aerOut env from_ v v.currentView v.lastIdx false + else + aerOut env from_ v (v.getTerm (v.highestMatch r.prevLogTerm r.prevLogIndex)) + (v.highestMatch r.prevLogTerm r.prevLogIndex) false + +/-- The ends of the AppendEntries hold. -/ +def AeOut (env : Env) (from_ : NodeId) (r : AppendEntriesRequest) (K : Option Nat) + (saved v : State) (o : Outbox) + : Prop := + saved.currentView > r.term + /\ v = saved + /\ o = aerOut env from_ saved saved.currentView saved.lastIdx false + \/ Not (saved.currentView > r.term) + /\ (aeMid r saved).leadership ≠ .leader + /\ ((aeMid r saved).getTerm r.prevLogIndex ≠ r.prevLogTerm + /\ v = aeMid r saved + /\ o = nackOut env from_ r (aeMid r saved) + \/ (aeMid r saved).getTerm r.prevLogIndex = r.prevLogTerm + /\ ((r.prevLogIndex < saved.commitIdx \/ r.prevLogIndex > saved.lastIdx) + /\ v = aeU from_ r saved + /\ o = [] + \/ saved.commitIdx <= r.prevLogIndex + /\ r.prevLogIndex <= saved.lastIdx + /\ (silentOf (aeU from_ r saved) K + /\ v = aeU from_ r saved + /\ o = [] + \/ Not (silentOf (aeU from_ r saved) K) + /\ GN + (aePar env.names from_ r + ((r.entries.map (toExecEntry env)).toArray) + (aeU from_ r saved) K) + (aePar env.names from_ r + ((r.entries.map (toExecEntry env)).toArray) + (aeU from_ r saved) K).lx.length + (core v) + /\ v.commitIdx + = (aePar env.names from_ r + ((r.entries.map (toExecEntry env)).toArray) + (aeU from_ r saved) K).bd + /\ o = ack env from_ r v))) + +theorem hoare_nack {env : Env} (from_ : NodeId) (V : State) + : Hoare env (fun v o => v = V /\ o = []) (nack from_) + (fun _ v o => v = V /\ o = aerOut env from_ V V.currentView V.lastIdx false) := by + unfold nack + refine Hoare.getV_bind fun s => hoare_sendAer _ _ _ _ fun v o ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst hv ho hs + exact ⟨rfl, rfl⟩ + +theorem hoare_nackRejected {env : Env} (from_ : NodeId) (V : State) (t i : Nat) + : Hoare env (fun v o => v = V /\ o = []) (nackRejected from_ t i) + (fun _ v o => + v = V + /\ o + = aerOut env from_ V (V.getTerm (V.highestMatch t i)) + (V.highestMatch t i) false) := by + unfold nackRejected + refine Hoare.getV_bind fun s => hoare_sendAer _ _ _ _ fun v o ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst hv ho hs + exact ⟨rfl, rfl⟩ + +theorem aeMid_frame (r : AppendEntriesRequest) (v : State) + : (aeMid r v).lastIdx = v.lastIdx + /\ (aeMid r v).ledger = v.ledger + /\ (aeMid r v).views = v.views + /\ (aeMid r v).commitIdx = v.commitIdx + /\ (aeMid r v).committable = v.committable + /\ (aeMid r v).rcEntries = v.rcEntries + /\ (aeMid r v).nodeId = v.nodeId + /\ (aeMid r v).retiredCommittedIdx = v.retiredCommittedIdx := by + unfold aeMid + split + · exact ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩ + · split <;> exact ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩ + +theorem aeMid_view (r : AppendEntriesRequest) (v : State) + (h : Not (v.currentView > r.term)) + : (aeMid r v).currentView = r.term := by + unfold aeMid + split + · rfl + · split + · rfl + · omega + +theorem conflictSpec_congr {U V : State} {P n τ : Nat} {K : Option Nat} + (h1 : U.lastIdx = V.lastIdx) (h2 : U.views = V.views) + (h : ConflictSpec V P n τ K) + : ConflictSpec U P n τ K := by + have hv : U.viewAt = V.viewAt := by funext i; simp [State.viewAt, h2] + cases K <;> simpa [ConflictSpec, h1, hv] using h + +theorem hoare_match {env : Env} (from_ : NodeId) (r : AppendEntriesRequest) + (K : Option Nat) (saved : State) (hns : Not (saved.currentView > r.term)) + (hnl : (aeMid r saved).leadership ≠ .leader) (hsz : saved.ledger.size = saved.lastIdx) + (hcomm : saved.committable = sigsIn saved.ledger saved.commitIdx saved.lastIdx) + (hviews : saved.views.size <= saved.currentView) + (hrc : forall x, x ∈ saved.rcEntries -> saved.commitIdx < x.1) + (hτ + : forall j (h : j < ((r.entries.map (toExecEntry env)).toArray).size), + ((r.entries.map (toExecEntry env)).toArray)[j].term = aeTermOfIdx r) + (hK : ConflictSpec saved r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + (hv2 + : Not (saved.currentView > r.term) + -> (aeMid r saved).getTerm r.prevLogIndex = r.prevLogTerm + -> aeTermOfIdx r <= r.term) + : Hoare env (fun v o => v = aeMid r saved /\ o = []) + (aeMatch from_ r ((r.entries.map (toExecEntry env)).toArray) (aeMid r saved)) + (fun _ v o => AeOut env from_ r K saved v o) := by + have ⟨f1, f2, f3, f4, f5, f6, f7, f8⟩ := aeMid_frame r saved + have hview := aeMid_view r saved hns + unfold aeMatch + dsimp only + refine Hoare.ite (fun hb => ?_) (fun hb => ?_) + · simp only [bne_iff_ne, ne_eq] at hb + refine Hoare.post (Q := fun _ v o => v = aeMid r saved /\ o = nackOut env from_ r (aeMid r saved)) ?_ + fun _ v o h => Or.inr ⟨hns, hnl, Or.inl ⟨hb, h⟩⟩ + refine Hoare.ite (fun h0 => ?_) (fun h0 => ?_) + · simp only [beq_iff_eq] at h0 + refine Hoare.bind (hoare_nack from_ _) fun _ => Hoare.pure _ fun v o ⟨hv, ho⟩ => ⟨hv, ?_⟩ + simp [ho, nackOut, h0] + · simp only [beq_iff_eq] at h0 + refine Hoare.bind (hoare_nackRejected from_ _ _ _) fun _ => + Hoare.pure _ fun v o ⟨hv, ho⟩ => ⟨hv, ?_⟩ + simp [ho, nackOut, h0] + · simp only [bne_iff_ne, ne_eq, Decidable.not_not] at hb + refine Hoare.setV _ (Q := fun _ v o => v = aeU from_ r saved /\ o = []) + (fun v o ⟨hv, ho⟩ => ⟨by rw [hv]; rfl, ho⟩) |>.bind fun _ => ?_ + refine Hoare.getV_bind fun s => Hoare.pin fun v0 o0 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst hv ho hs + have u1 : (aeU from_ r saved).commitIdx = saved.commitIdx := f4 + have u2 : (aeU from_ r saved).lastIdx = saved.lastIdx := f1 + refine Hoare.ite (fun h1 => ?_) (fun h1 => ?_) + · exact Hoare.pure _ fun v o ⟨hv, ho⟩ => + Or.inr ⟨hns, hnl, Or.inr ⟨hb, Or.inl ⟨Or.inl (u1 ▸ h1), hv, ho⟩⟩⟩ + refine Hoare.ite (fun h2 => ?_) (fun h2 => ?_) + · exact Hoare.pure _ fun v o ⟨hv, ho⟩ => + Or.inr ⟨hns, hnl, Or.inr ⟨hb, Or.inl ⟨Or.inr (u2 ▸ h2), hv, ho⟩⟩⟩ + have hP : r.prevLogIndex <= saved.lastIdx := by omega + have hci : saved.commitIdx <= r.prevLogIndex := by omega + have hU : aeU from_ r saved = { aeMid r saved with leaderId := some from_ } := rfl + refine Hoare.post (hoare_apply from_ r _ (aeU from_ r saved) K + (aePar env.names from_ r ((r.entries.map (toExecEntry env)).toArray) (aeU from_ r saved) K) + (by simp) hτ (u2 ▸ hP) (u1 ▸ hci) hnl + (conflictSpec_congr f1 f3 hK) (by rw [u2]; exact f2 ▸ hsz) + (good_cCut _ _ _ _ _ _ (u2 ▸ hP) (u1 ▸ hci) hnl (conflictSpec_congr f1 f3 hK) + (by rw [u2]; exact f2 ▸ hsz) (by rw [u2, u1]; exact f5.trans (f2 ▸ hcomm)) + (by show (aeMid r saved).views.size <= (aeMid r saved).currentView; rw [f3]; omega) + (by rw [u1]; exact f6 ▸ hrc) rfl) + rfl (show (aeMid r saved).commitIdx <= r.prevLogIndex by omega) + (show r.term <= (aeMid r saved).currentView by omega) + (show aeTermOfIdx r <= (aeMid r saved).currentView by rw [hview]; exact hv2 hns hb) rfl) ?_ + intro _ v o h + exact Or.inr ⟨hns, hnl, Or.inr ⟨hb, Or.inr ⟨hci, hP, h⟩⟩⟩ + +theorem hoare_jp {env : Env} (from_ : NodeId) (r : AppendEntriesRequest) (K : Option Nat) + (saved : State) (hns : Not (saved.currentView > r.term)) + (hsz : saved.ledger.size = saved.lastIdx) + (hcomm : saved.committable = sigsIn saved.ledger saved.commitIdx saved.lastIdx) + (hviews : saved.views.size <= saved.currentView) + (hrc : forall x, x ∈ saved.rcEntries -> saved.commitIdx < x.1) + (hτ + : forall j (h : j < ((r.entries.map (toExecEntry env)).toArray).size), + ((r.entries.map (toExecEntry env)).toArray)[j].term = aeTermOfIdx r) + (hK : ConflictSpec saved r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + (hv2 + : Not (saved.currentView > r.term) + -> (aeMid r saved).getTerm r.prevLogIndex = r.prevLogTerm + -> aeTermOfIdx r <= r.term) + : Hoare env (fun v o => v = aeMid r saved /\ o = []) + (do + let v ← getV + let jp : Unit -> M Unit := + fun _ => aeMatch from_ r ((r.entries.map (toExecEntry env)).toArray) v + if (v.leadership == .leader && v.currentView == r.term) = true then do + let l ← curLoc + let x ← + Exec.fail + (toString l + ++ toString ": AppendEntries from " + ++ toString from_ + ++ toString " to a leader in its own view " + ++ toString r.term) + jp x + else + jp ()) + (fun _ v o => AeOut env from_ r K saved v o) := by + refine Hoare.getV_bind fun s => Hoare.pin fun v0 o0 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst hv ho hs + dsimp only + refine Hoare.ite (fun hb => ?_) (fun hb => ?_) + · refine Hoare.bind (Hoare.keeps Spec.curLoc (Q := fun _ _ _ => True) fun _ _ _ _ => trivial) + fun _ => Hoare.bind (Hoare.fail (Q := fun _ _ _ => False) _) fun _ => + Hoare.false_pre fun _ _ f => f + · have hnl : (aeMid r saved).leadership ≠ .leader := by + intro h + simp [h, aeMid_view r saved hns] at hb + exact hoare_match from_ r K saved hns hnl hsz hcomm hviews hrc hτ hK hv2 + +theorem hoare_recv {env : Env} (from_ : NodeId) (r : AppendEntriesRequest) + (K : Option Nat) (saved : State) (hsz : saved.ledger.size = saved.lastIdx) + (hcomm : saved.committable = sigsIn saved.ledger saved.commitIdx saved.lastIdx) + (hviews : saved.views.size <= saved.currentView) + (hrc : forall x, x ∈ saved.rcEntries -> saved.commitIdx < x.1) + (hτ + : forall j (h : j < ((r.entries.map (toExecEntry env)).toArray).size), + ((r.entries.map (toExecEntry env)).toArray)[j].term = aeTermOfIdx r) + (hK : ConflictSpec saved r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + (hv2 + : Not (saved.currentView > r.term) + -> (aeMid r saved).getTerm r.prevLogIndex = r.prevLogTerm + -> aeTermOfIdx r <= r.term) + : Hoare env (fun v o => v = saved /\ o = []) (recvAppendEntries from_ r) + (fun _ v o => AeOut env from_ r K saved v o) := by + rw [recvAppendEntries_eq] + refine Hoare.bind (Hoare.of_spec (det_traceRecv env _ from_ _) + (Q := fun _ v o => v = saved /\ o = []) fun v o _ v' o' ⟨hv, ho⟩ ⟨e1, e2⟩ => by + subst hv ho; simp [e1, e2]) fun _ => ?_ + refine Hoare.bind (Hoare.of_spec Spec.get + (Q := fun c v o => v = saved /\ o = [] /\ c.env = env) + fun v o a v' o' ⟨hv, ho⟩ ⟨a1, a2, a3, a4, a5⟩ => ⟨a4.trans hv, a5.trans ho, a3⟩) + fun c => ?_ + refine Hoare.pin fun v0 o0 ⟨hv, ho, hc⟩ => ?_ + subst hv ho + rw [hc] + dsimp only + refine Hoare.getV_bind fun s => Hoare.pin fun v0 o0 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst hv ho hs + have jp := fun hns => hoare_jp (env := env) from_ r K v0 hns hsz hcomm hviews hrc hτ hK hv2 + refine Hoare.ite (fun hb => ?_) (fun hb => ?_) + · have hns : Not (v0.currentView > r.term) := by + simp only [Bool.and_eq_true, beq_iff_eq] at hb; omega + have hm : aeMid r v0 = bant r.term v0 := by simp [aeMid, hb] + refine Hoare.bind (Hoare.of_spec (det_becomeAware env r.term) + (Q := fun _ v o => v = aeMid r v0 /\ o = []) fun v o _ v' o' ⟨hv, ho⟩ ⟨e1, e2⟩ => by + subst hv ho; simp [e1, e2, hm]) fun _ => jp hns + refine Hoare.ite (fun hb' => ?_) (fun hb' => ?_) + · have hns : Not (v0.currentView > r.term) := by omega + have hm : aeMid r v0 = bant r.term v0 := by simp [aeMid, hb, hb'] + refine Hoare.bind (Hoare.of_spec (det_becomeAware env r.term) + (Q := fun _ v o => v = aeMid r v0 /\ o = []) fun v o _ v' o' ⟨hv, ho⟩ ⟨e1, e2⟩ => by + subst hv ho; simp [e1, e2, hm]) fun _ => jp hns + refine Hoare.ite (fun hs => ?_) (fun hs => ?_) + · refine Hoare.bind (hoare_nack from_ v0) fun _ => Hoare.pure _ fun v o ⟨hv, ho⟩ => + Or.inl ⟨hs, hv, ho⟩ + · have hm : aeMid r v0 = v0 := by simp [aeMid, hb, hb'] + have := jp hs + rw [hm] at this + exact this + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeScan.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeScan.lean new file mode 100644 index 000000000000..7feda361f3d7 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeScan.lean @@ -0,0 +1,525 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeExec + +@[expose] public section + +/-! +# The conflict scan of AppendEntries (not reviewed) + +The scan walks the request's indexes from `prevLogIndex + 1`. Before the first conflict `K` +(`ConflictSpec`) it skips matching entries; at the conflict it rolls back to `K - 1` +(`hoare_rollback`) if the node is a new follower, else it stops silently (`silentOf`); from +there it queues every entry with its retirement record (`hoare_scan`). Executing the queue +and the finish then end with `Good` over the final ledger and the ACK (`hoare_apply`), from +`Good` at the cut (`good_cCut`) for the parameters `aePar`. +-/ + +namespace Consensus.TraceValidation.Proofs.Ae + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- The core after `rollback idx`. -/ +def rbCore (c : Core) (idx : Nat) : Core := + { + c with + rcEntries := c.rcEntries.filter (·.1 <= idx) + ledger := c.ledger.extract 0 idx + lastIdx := idx + views := c.views.filter (· <= idx) + committable := c.committable.filter (· <= idx) + } + +theorem hoare_rollback {env : Env} (C : Core) (o0 : Outbox) (idx : Nat) + (hci : C.commitIdx <= idx) (hnl : C.leadership ≠ .leader) + : Hoare env (fun v o => core v = C /\ o = o0) (rollback idx) + (fun _ v o => core v = rbCore C idx /\ o = o0) := by + unfold rollback + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v0 o1 ⟨⟨hc, ho⟩, hv⟩ => ?_ + subst hv ho hc + refine Hoare.ite (fun h => absurd h (by simp only [core] at hci; omega)) fun _ => ?_ + refine Hoare.bind (R := fun _ v o => core v = rbCore (core v0) idx /\ o = o1) + (Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨?_, ho⟩) fun _ => ?_ + · subst hv + simp only [core, rbCore] + split <;> (try split) <;> simp_all + · have hnl' : (rbCore (core v0) idx).leadership ≠ .leader := hnl + exact (show Frame env _ by frame_tac) _ _ hnl' + +/-- The retirement record the scan pushes for entry `i`. -/ +def rc1 (i : Nat) (e : Exec.Entry) : List (Nat × List NodeId) := + if e.retired.isEmpty then [] else [(i, e.retired)] + +/-- Entry `i` of the request, as the scan reads it. -/ +def ent (payload : Array Exec.Entry) (P i : Nat) : Exec.Entry := payload[i - P - 1]?.get! + +/-- The work list for entries `a ..= b`. -/ +def items (payload : Array Exec.Entry) (P a b : Nat) : List (Nat × Exec.Entry × Bool) := + (List.range' a (b + 1 - a)).map fun i => (i, ent payload P i, true) + +/-- The retirement records the scan pushes for entries `a ..= b`. -/ +def rcOf (payload : Array Exec.Entry) (P a b : Nat) : List (Nat × List NodeId) := + (List.range' a (b + 1 - a)).flatMap fun i => rc1 i (ent payload P i) + +def addRc (C : Core) (l : List (Nat × List NodeId)) : Core := + { C with rcEntries := C.rcEntries ++ l } + +theorem range'_snoc (a b : Nat) (h : a <= b + 1) + : List.range' a (b + 1 + 1 - a) = List.range' a (b + 1 - a) ++ [b + 1] := by + rw [show b + 1 + 1 - a = (b + 1 - a) + 1 by omega, List.range'_concat] + congr 2 + omega + +theorem items_snoc (payload : Array Exec.Entry) (P a b : Nat) (h : a <= b + 1) + : items payload P a (b + 1) + = items payload P a b ++ [(b + 1, ent payload P (b + 1), true)] := by + simp [items, range'_snoc a b h] + +theorem rcOf_snoc (payload : Array Exec.Entry) (P a b : Nat) (h : a <= b + 1) + : rcOf payload P a (b + 1) + = rcOf payload P a b ++ rc1 (b + 1) (ent payload P (b + 1)) := by + simp [rcOf, range'_snoc a b h] + +theorem items_empty (payload : Array Exec.Entry) (P a b : Nat) (h : b < a) + : items payload P a b = [] := by + simp [items]; omega + +theorem rcOf_empty (payload : Array Exec.Entry) (P a b : Nat) (h : b < a) + : rcOf payload P a b = [] := by + simp [rcOf]; omega + +theorem hoare_push {env : Env} (C : Core) (o0 : Outbox) (i : Nat) (e : Exec.Entry) + (toApply : Array (Nat × Exec.Entry × Bool)) (τ : Nat) + : Hoare env (fun v o => core v = C /\ o = o0) + (do + if (!e.retired.isEmpty) = true then + setV fun v => { v with rcEntries := v.rcEntries ++ [(i, e.retired)] } + pure (ForInStep.yield (none, toApply.push (i, e, e.term == τ))) + : M (ForInStep (Option Unit × Array (Nat × Exec.Entry × Bool)))) + (fun st v o => + st = .yield (none, toApply.push (i, e, e.term == τ)) + /\ core v = addRc C (rc1 i e) + /\ o = o0) := by + extract_lets jp + refine Hoare.ite (fun h => Hoare.bind (Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨?_, ho⟩) + fun _ => Hoare.pure _ fun _ _ h => ⟨rfl, h⟩) + (fun h => Hoare.pure _ fun v o ⟨hv, ho⟩ => ⟨rfl, ?_, ho⟩) + · subst hv + simp only [Bool.not_eq_eq_eq_not, Bool.not_true] at h + simp [core, addRc, rc1, h] + · subst hv + simp only [Bool.not_eq_eq_eq_not, Bool.not_true] at h + simp [core, addRc, rc1, h] + +/-- The last index the scan keeps: before the first conflict, else the whole log. -/ +def cutOf (U : State) : Option Nat -> Nat + | some k => k - 1 + | none => U.lastIdx + +/-- The core the scan starts appending from. -/ +def cCut (U : State) : Option Nat -> Core + | some k => { rbCore (core U) (k - 1) with isNewFollower := false } + | none => core U + +/-- The scan finds a conflict but may not roll back. -/ +def silentOf (U : State) (K : Option Nat) : Prop := + K.isSome = true /\ U.isNewFollower = false + +/-- What the scan compares: the first conflict `K` with the request's term `τ`. -/ +def ConflictSpec (U : State) (P n τ : Nat) : Option Nat -> Prop + | some k => + P < k + /\ k <= U.lastIdx + /\ k <= P + n + /\ U.viewAt k ≠ τ + /\ forall j, P < j -> j < k -> U.viewAt j = τ + | none => forall j, P < j -> j <= U.lastIdx -> j <= P + n -> U.viewAt j = τ + +theorem cCut_lastIdx (U : State) (K : Option Nat) : (cCut U K).lastIdx = cutOf U K := by + cases K <;> rfl + +theorem hoare_scan {env : Env} (from_ : NodeId) (r : AppendEntriesRequest) + (payload : Array Exec.Entry) (U : State) (K : Option Nat) + (hsize : payload.size = r.entries.length) + (hτ : forall j (h : j < payload.size), payload[j].term = aeTermOfIdx r) + (hP : r.prevLogIndex <= U.lastIdx) (hci : U.commitIdx <= r.prevLogIndex) + (hnl : U.leadership ≠ .leader) + (hK : ConflictSpec U r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + : Hoare env (fun v o => v = U /\ o = []) + (forIn [r.prevLogIndex + 1 : aeIdx r + 1] (none, #[]) (scanBody from_ r payload)) + (fun t v o => + o = [] + /\ (silentOf U K /\ t.fst = some () /\ v = U + \/ Not (silentOf U K) + /\ t.fst = none + /\ t.snd.toList = items payload r.prevLogIndex (cutOf U K + 1) (aeIdx r) + /\ core v + = addRc (cCut U K) + (rcOf payload r.prevLogIndex (cutOf U K + 1) (aeIdx r)))) := by + generalize hPd : r.prevLogIndex = P at * + generalize hnd : r.entries.length = n at * + have hA : aeIdx r = P + n := by rw [aeIdx, hPd, hnd] + generalize hτd : aeTermOfIdx r = τ at * + have hcut : P <= cutOf U K := by + cases K with + | none => exact hP + | some k => simp only [cutOf]; have := hK.1; omega + rw [Std.Legacy.Range.forIn_eq_forIn_range'] + simp only [Std.Legacy.Range.size, hA, show P + n + 1 - (P + 1) = n by omega, + Nat.add_sub_cancel, Nat.div_one] + refine Hoare.pre + (Hoare.forIn_list _ _ _ + (fun pre b v o => + o = [] + /\ (P + pre.length <= cutOf U K /\ b = (none, #[]) /\ v = U + \/ cutOf U K < P + pre.length + /\ Not (silentOf U K) + /\ b.fst = none + /\ b.snd.toList = items payload P (cutOf U K + 1) (P + pre.length) + /\ core v + = addRc (cCut U K) (rcOf payload P (cutOf U K + 1) (P + pre.length)))) + _ ?_ ?_) + fun v o ⟨hv, ho⟩ => ⟨ho, Or.inl ⟨by simpa using hcut, rfl, hv⟩⟩ + · intro pre a rest b he + have hlen : pre.length < n := by + have := congrArg List.length he; simp at this; omega + have ha : a = P + pre.length + 1 := by + have h1 : (List.range' (P + 1) n)[pre.length]'(by simpa using hlen) = a := by + simp only [he, List.getElem_append_right (Nat.le_refl _), Nat.sub_self, + List.getElem_cons_zero] + simp at h1; omega + generalize hm : P + pre.length = m at ha + subst ha + have hL : P + (pre ++ [m + 1]).length = m + 1 := by simp; omega + have hmn : m < P + n := by omega + have hPm : P <= m := by omega + have hE : payload[m + 1 - P - 1]? = some (ent payload P (m + 1)) := by + have : m + 1 - P - 1 = pre.length := by omega + simp [ent, this, hsize, hlen] + have hT : (ent payload P (m + 1)).term = τ := by + have : m + 1 - P - 1 = pre.length := by omega + simp only [ent, this, getElem?_pos payload pre.length (by omega), Option.get!_some] + exact hτ _ _ + refine Hoare.pin fun v0 o0 ⟨ho, h⟩ => ?_ + subst ho + unfold scanBody + extract_lets toApply entry? entry jp push + have hE' : entry? = some (ent payload P (m + 1)) := by + simp only [entry?, hPd]; exact hE + have hentry : entry = ent payload P (m + 1) := by + simp only [entry, hE', Option.get!_some] + have hpush : forall C, Hoare env (fun v o => core v = C /\ o = []) (push ()) + (fun st v o => st = .yield (none, toApply.push (m + 1, ent payload P (m + 1), true)) + /\ core v = addRc C (rc1 (m + 1) (ent payload P (m + 1))) /\ o = []) := by + intro C + have hb : (entry.term == aeTermOfIdx r) = true := by rw [hentry, hT, hτd]; simp + refine Hoare.post (hoare_push C [] (m + 1) entry toApply (aeTermOfIdx r)) ?_ + intro st v o ⟨h1, h2, h3⟩ + exact ⟨by rw [h1, hb, hentry], by rw [h2, hentry], h3⟩ + refine Hoare.ite (fun hn => absurd hn (by simp [hE'])) fun _ => ?_ + refine Hoare.getV_bind fun s => Hoare.pin fun v1 o1 ⟨⟨hv1, ho1⟩, hs⟩ => ?_ + subst ho1 s v1 + rcases h with ⟨hmc, rfl, hU⟩ | ⟨hmc, hns, hb1, hb2, hb3⟩ + · subst v0 + have hcl : cutOf U K <= U.lastIdx := by + cases K with + | none => exact Nat.le_refl _ + | some k => simp only [cutOf]; have := hK.2.1; omega + refine Hoare.ite (fun hle => ?_) (fun hgt => ?_) + · refine Hoare.ite (fun hc => ?_) (fun hc => ?_) + · have hc' : U.viewAt (m + 1) ≠ τ := by + rw [← hτd]; intro h; simp [h] at hc + cases K with + | none => exact absurd (hK (m + 1) (by omega) hle (by omega)) hc' + | some k => + obtain ⟨hPk, hkl, hkn, hkne, hbef⟩ := hK + simp only [cutOf] at hmc + rcases Nat.lt_or_ge (m + 1) k with hlt | hge + · exact absurd (hbef _ (by omega) hlt) hc' + have hk : k = m + 1 := by omega + subst hk + refine Hoare.ite (fun hnf => ?_) (fun hnf => ?_) + · refine Hoare.bind (Hoare.pre (hoare_rollback (core U) [] (m + 1 - 1) + (show U.commitIdx <= _ by omega) hnl) fun v o ⟨hv, ho⟩ => ⟨by rw [hv], ho⟩) + fun _ => ?_ + refine Hoare.bind + (R := fun _ v o => core v = cCut U (some (m + 1)) /\ o = []) + (Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨?_, ho⟩) fun _ => ?_ + · show _ = { rbCore (core U) (m + 1 - 1) with isNewFollower := false } + rw [← hv]; rfl + refine Hoare.post (hpush _) fun st v o ⟨h1, h2, h3⟩ => ?_ + subst h1 + refine ⟨h3, Or.inr ⟨by simp only [cutOf]; omega, ?_, rfl, ?_, ?_⟩⟩ + · simp [silentOf, hnf] + · simp only [hL, cutOf, Nat.add_sub_cancel, toApply, Array.toList_push] + rw [items_snoc _ _ _ _ (Nat.le_refl _), items_empty _ _ _ _ (by omega)] + · simp only [hL, cutOf, Nat.add_sub_cancel, h2] + rw [rcOf_snoc _ _ _ _ (Nat.le_refl _), rcOf_empty _ _ _ _ (by omega)]; rfl + · exact Hoare.pure _ fun v o ⟨hv, ho⟩ => + ⟨ho, Or.inl ⟨⟨rfl, by simpa using hnf⟩, rfl, hv⟩⟩ + · refine Hoare.pure _ fun v o ⟨hv, ho⟩ => ⟨ho, Or.inl ⟨?_, rfl, hv⟩⟩ + have hc' : U.viewAt (m + 1) = τ := by + simp only [bne_iff_ne, ne_eq, Decidable.not_not] at hc; rw [← hτd, hc] + rw [hL] + cases K with + | none => exact hle + | some k => + obtain ⟨hPk, hkl, hkn, hkne, hbef⟩ := hK + simp only [cutOf] at hmc ⊢ + have : k ≠ m + 1 := fun h => hkne (h ▸ hc') + omega + · have hmc' : m = U.lastIdx := by omega + cases K with + | some k => have := hK.1; have := hK.2.1; simp only [cutOf] at hmc; omega + | none => + refine Hoare.post + (Hoare.pre (hpush (core U)) fun v o ⟨hv, ho⟩ => ⟨by rw [hv], ho⟩) + fun st v o ⟨h1, h2, h3⟩ => ?_ + subst h1 + refine ⟨ + h3, + Or.inr + ⟨ + by simp only [cutOf, hL]; omega, + fun h => by simp [silentOf] at h, + rfl, + ?_, + ?_ + ⟩ + ⟩ + · simp only [hL, cutOf, ← hmc', toApply, Array.toList_push] + rw [items_snoc _ _ _ _ (Nat.le_refl _), items_empty _ _ _ _ (by omega)] + · simp only [hL, cutOf, ← hmc', h2] + rw [rcOf_snoc _ _ _ _ (Nat.le_refl _), rcOf_empty _ _ _ _ (by omega)]; rfl + · have hvl : v0.lastIdx = cutOf U K := (congrArg Core.lastIdx hb3).trans (cCut_lastIdx U K) + refine Hoare.ite (fun hle => absurd hle (by omega)) fun _ => ?_ + refine Hoare.post (Hoare.pre (hpush (core v0)) fun v o ⟨hv, ho⟩ => ⟨by rw [hv], ho⟩) + fun st v o ⟨h1, h2, h3⟩ => ?_ + subst h1 + refine ⟨h3, Or.inr ⟨by rw [hL]; omega, hns, rfl, ?_, ?_⟩⟩ + · simp only [hL, toApply, Array.toList_push, hb2] + rw [items_snoc _ _ _ _ (by omega)] + · rw [hL, h2, hb3, rcOf_snoc _ _ _ _ (by omega)] + simp [addRc] + · intro b v o ⟨ho, h⟩ + simp only [List.length_range'] at h + refine ⟨ho, ?_⟩ + rcases h with ⟨h1, rfl, rfl⟩ | ⟨h1, h2, h3, h4, h5⟩ + · cases K with + | some k => have := hK.1; have := hK.2.2.1; simp only [cutOf] at h1; omega + | none => + refine Or.inr ⟨fun h => by simp [silentOf] at h, rfl, ?_, ?_⟩ + · rw [items_empty _ _ _ _ (by omega)] + · rw [rcOf_empty _ _ _ _ (by omega)]; simp [addRc, cCut] + · exact Or.inr ⟨h2, h3, h4, h5⟩ + +theorem cutOf_le {U : State} {P n τ : Nat} {K : Option Nat} (hP : P <= U.lastIdx) + (hK : ConflictSpec U P n τ K) + : P <= cutOf U K /\ cutOf U K <= U.lastIdx := by + cases K with + | none => exact ⟨hP, Nat.le_refl _⟩ + | some k => have := hK.1; have := hK.2.1; simp only [cutOf]; omega + +theorem good_addRc {p : Par} {C : Core} {l : List (Nat × List NodeId)} (g : Good p C) + (h : forall x, x ∈ l -> p.c0 < x.1) + : Good p (addRc C l) := + { + g with + rc := + fun x hx => by + simp only [addRc, List.mem_append] at hx + exact hx.elim (g.rc x) (h x) + } + +theorem rcOf_gt {payload : Array Exec.Entry} {P a b : Nat} + : forall x, x ∈ rcOf payload P a b -> a <= x.1 := by + intro x hx + simp only [rcOf, List.mem_flatMap, List.mem_range'] at hx + obtain ⟨i, ⟨j, _, rfl⟩, hx⟩ := hx + simp only [rc1] at hx + split at hx + · simp at hx + · simp only [List.mem_singleton] at hx; subst hx; simp + +theorem hoare_apply {env : Env} (from_ : NodeId) (r : AppendEntriesRequest) + (payload : Array Exec.Entry) (U : State) (K : Option Nat) (p : Par) + (hsize : payload.size = r.entries.length) + (hτ : forall j (h : j < payload.size), payload[j].term = aeTermOfIdx r) + (hP : r.prevLogIndex <= U.lastIdx) (hci : U.commitIdx <= r.prevLogIndex) + (hnl : U.leadership ≠ .leader) + (hK : ConflictSpec U r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + (hsz : U.ledger.size = U.lastIdx) + (hG : Good p (cCut U K)) + (hlx + : p.lx + = U.ledger.toList.take (cutOf U K) + ++ payload.toList.drop (cutOf U K - r.prevLogIndex)) + (hc0 : p.c0 <= r.prevLogIndex) + (hv1 : r.term <= p.view) (hv2 : aeTermOfIdx r <= p.view) + (hlim : min r.primaryCommit (aeIdx r) = p.lim) + : Hoare env (fun v o => v = U /\ o = []) (aeApply from_ r payload) + (fun _ v o => + silentOf U K /\ v = U /\ o = [] + \/ Not (silentOf U K) + /\ GN p p.lx.length (core v) + /\ v.commitIdx = p.bd + /\ o = ack env from_ r v) := by + have ⟨hc1, hc2⟩ := cutOf_le hP hK + unfold aeApply + refine Hoare.bind (hoare_scan from_ r payload U K hsize hτ hP hci hnl hK) fun s => ?_ + refine Hoare.pin fun v o ⟨ho, h⟩ => ?_ + subst ho + rcases h with ⟨hs, h1, hv⟩ | ⟨hs, h1, h2, h3⟩ + · rw [h1] + exact Hoare.pure _ fun v' o' ⟨hv', ho'⟩ => Or.inl ⟨hs, hv'.trans hv, ho'⟩ + · rw [h1] + simp only + rw [← Array.forIn_toList, h2] + have hW : Work p (cutOf U K) (items payload r.prevLogIndex (cutOf U K + 1) (aeIdx r)) := by + intro k hk + simp only [items, List.length_map, List.length_range'] at hk + simp only [items, List.getElem_map, List.getElem_range'] + refine ⟨by omega, ?_, by simp, ?_⟩ + · rw [hlx, List.getElem?_append_right (by simp; omega)] + simp only [List.length_take, Array.length_toList, List.getElem?_drop, ent] + have : cutOf U K - r.prevLogIndex + (cutOf U K + k - min (cutOf U K) U.ledger.size) + = cutOf U K + 1 + k - r.prevLogIndex - 1 := by omega + rw [this, Array.getElem?_toList] + have hlt : cutOf U K + 1 + k - r.prevLogIndex - 1 < payload.size := by + simp only [aeIdx] at hk; omega + simp [hlt] + · simp only [ent] + have hlt : cutOf U K + 1 + k - r.prevLogIndex - 1 < payload.size := by + simp only [aeIdx] at hk; omega + simp only [Nat.one_mul, getElem?_pos payload (cutOf U K + 1 + k - r.prevLogIndex - 1) hlt, + Option.get!_some, hτ _ hlt] + exact hv2 + refine Hoare.bind (Hoare.pre (gt_execLoop from_ r _ _ hW hv1 hlim []) fun v' o' ⟨hv', ho'⟩ => + ⟨⟨by rw [hv', h3]; exact good_addRc hG fun x hx => by have := rcOf_gt x hx; omega, + by rw [hv', h3]; exact cCut_lastIdx U K⟩, ho'⟩) fun t => ?_ + refine Hoare.pin fun v1 o1 ⟨⟨ht, hg⟩, ho1⟩ => ?_ + subst ho1 + rw [ht] + simp only + have hlen : cutOf U K + (items payload r.prevLogIndex (cutOf U K + 1) (aeIdx r)).length + = p.lx.length := by + simp only [items, List.length_map, List.length_range', hlx, List.length_append, + List.length_take, Array.length_toList, List.length_drop, hsize, aeIdx] + omega + rw [hlen] at hg + exact Hoare.post (Hoare.pre (hoare_finish from_ r hv1 hv2 hlim) fun v' o' ⟨hv', ho'⟩ => + ⟨hv' ▸ hg, ho'⟩) fun _ v' o' h => Or.inr ⟨hs, h⟩ + +theorem sigsIn_trunc (ledger : Array Exec.Entry) {lo m hi : Nat} (h1 : lo <= m) + (h2 : m <= hi) + : (sigsIn ledger lo hi).filter (fun x => decide (x <= m)) + = sigsIn (ledger.extract 0 m) lo m := by + unfold sigsIn + rw [show hi - lo = (m - lo) + (hi - m) by omega, ← List.range'_append_1] + simp only [List.filter_append, List.filter_filter] + rw [(List.filter_eq_nil_iff (l := List.range' (lo + 1 + (m - lo)) (hi - m))).mpr ?_, + List.append_nil] + · apply List.filter_congr + intro x hx + simp only [List.mem_range'_1] at hx + have : x - 1 < m := by omega + simp only [Array.getElem?_extract, show x <= m by omega, decide_true, Bool.true_and, + Nat.zero_add] + by_cases hs : x - 1 < ledger.size + · have : x - 1 < min m ledger.size := Nat.lt_min.mpr ⟨this, hs⟩ + simp [hs, this] + · have : ¬ x - 1 < min m ledger.size := fun h => hs (Nat.lt_min.mp h).2 + simp [hs, this] + · intro x hx + simp only [List.mem_range'_1] at hx + simp; omega + +/-- The hold's parameters for the execute phase. -/ +def aePar (names : Names) (from_ : NodeId) (r : AppendEntriesRequest) + (payload : Array Exec.Entry) (U : State) (K : Option Nat) + : Par where + names := names + nid := U.nodeId + view := U.currentView + vf := U.votedFor + nf := (cCut U K).isNewFollower + lt := U.leadership + ldr := from_ + rciT := U.retiredCommittedIdx + c0 := U.commitIdx + lim := min r.primaryCommit (aeIdx r) + lx := + U.ledger.toList.take (cutOf U K) ++ payload.toList.drop (cutOf U K - r.prevLogIndex) + +theorem good_cCut (names : Names) (from_ : NodeId) (r : AppendEntriesRequest) + (payload : Array Exec.Entry) (U : State) (K : Option Nat) + (hP : r.prevLogIndex <= U.lastIdx) (hci : U.commitIdx <= r.prevLogIndex) + (hnl : U.leadership ≠ .leader) + (hK : ConflictSpec U r.prevLogIndex r.entries.length (aeTermOfIdx r) K) + (hsz : U.ledger.size = U.lastIdx) + (hcomm : U.committable = sigsIn U.ledger U.commitIdx U.lastIdx) + (hviews : U.views.size <= U.currentView) + (hrc : forall x, x ∈ U.rcEntries -> U.commitIdx < x.1) + (hld : U.leaderId = some from_) + : Good (aePar names from_ r payload U K) (cCut U K) := by + have ⟨hc1, hc2⟩ := cutOf_le hP hK + have hlx : (U.ledger.toList.take (cutOf U K)).length = cutOf U K := by simp; omega + cases K with + | none => + simp only [cutOf] at hlx hc1 hc2 + exact { + nodeId := rfl, + view := rfl, + vf := rfl, + nf := rfl, + size := hsz + ledger := by + simp only [cCut, core, aePar, cutOf] + rw [List.take_append_of_le_length (by omega), List.take_take, Nat.min_self, + List.take_of_length_le (by simp; omega)] + last := by simp [aePar, cutOf, core, cCut]; omega + committable := hcomm + c0 := Nat.le_refl _ + bd := Nat.le_max_left _ _ + ci := by simp only [cCut, core]; omega + views := hviews + rc := hrc + lt := hnl + d := Or.inl ⟨rfl, rfl, hld⟩ + } + | some k => + obtain ⟨hPk, hkl, -⟩ := hK + simp only [cutOf] at hlx hc1 hc2 + exact { + nodeId := rfl, + view := rfl, + vf := rfl, + nf := rfl + size := by simp [cCut, rbCore, core]; omega + ledger := by + simp only [cCut, core, aePar, cutOf, rbCore] + rw [List.take_append_of_le_length (by omega), List.take_take, Nat.min_self] + simp [Array.toList_extract] + last := by simp [aePar, cutOf, core, cCut, rbCore]; omega + committable := by + simp only [cCut, core, rbCore] + rw [hcomm] + exact sigsIn_trunc _ (by omega) (by omega) + c0 := Nat.le_refl _ + bd := Nat.le_max_left _ _ + ci := by simp only [cCut, core, rbCore]; omega + views := Nat.le_trans Array.size_filter_le hviews + rc := + fun x hx => by + simp only [cCut, core, rbCore, List.mem_filter] at hx + exact hrc x hx.1 + lt := hnl + d := Or.inl ⟨rfl, rfl, hld⟩ + } + +end Consensus.TraceValidation.Proofs.Ae diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntries.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntries.lean new file mode 100644 index 000000000000..e9abec1b0d70 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntries.lean @@ -0,0 +1,239 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeAgree +public import Consensus.TraceValidation.Proofs.Handlers.AeMatch + +@[expose] public section + +/-! +# Obligation: `recv_append_entries` (not reviewed) + +`hoare_recv` (AeRecv) lists the ends of the hold from the released state; each is matched by +the clean receive of the request alone, whose ends `handle_nack`, `handle_silent` and +`handle_accept` (AeAgree) are taken after the term phase: + +- a stale request is refused in the node's view, as by the clean model, which leaves the + state unchanged; +- past the term phase (`aeMid`, clean `cleanMid`), a request whose previous term does not + match is refused with cft.h's `find_highest_possible_match`, the clean + `findHighestPossibleMatch` under `inv` (`highestMatch_eq`); +- a matching request before the commit index, or whose first conflict may not be rolled + back, only records the leader; +- otherwise the node truncates at the first conflict, appends, commits and answers; the end + state agrees with the clean `handleAppendEntiresFromPrimary` on the cut state + (`accept_agrees`). + +The conflict index the program scans for is the clean `firstTermConflictIndex` +(`ae_conflict`), and `msgInv` of the request gives the entry terms and the round trip of its +entries through the declared ledger (`ae_msg`). +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) +open Ae + +theorem ae_rc {names : Names} {d : State} (h : inv names d = true) + : forall x, x ∈ d.rcEntries -> d.commitIdx < x.1 := by + have hc : d.rcEntries + = (List.range' (d.commitIdx + 1) (d.lastIdx - d.commitIdx)).filterMap + fun i => d.ledger[i - 1]?.bind + fun e => if e.retired.isEmpty then none else some (i, e.retired) := by + inv_conj h "rc_entries" + intro x hx + rw [hc, List.mem_filterMap] at hx + obtain ⟨i, hi, he⟩ := hx + rw [List.mem_range'_1] at hi + cases hl : d.ledger[i - 1]? with + | none => simp [hl] at he + | some e => + simp only [hl, Option.bind_some] at he + split at he + · cases he + · cases he; simp only; omega + +theorem ae_conflict {names : Names} {d : State} (h : inv names d = true) + (r : AppendEntriesRequest) (τ : Nat) (hτ : forall e, e ∈ r.entries -> e.term = τ) + : ConflictSpec d r.prevLogIndex r.entries.length τ + (firstTermConflictIndex (abs names d) r) := by + have hs := ftci_spec (abs names d) r τ hτ + obtain ⟨h1, -⟩ := inv_parts h + have hlen := abs_log_length (names := names) h1 + have ht : forall j, 0 < j -> j <= d.lastIdx -> termAt (abs names d).log j = d.viewAt j := by + intro j h0 hj + rw [← getTerm_eq h] + simp [State.getTerm]; omega + rw [hlen] at hs + cases hk : firstTermConflictIndex (abs names d) r with + | none => + rw [hk] at hs + intro j a b c + rw [← ht j (by omega) b]; exact hs j a b c + | some k => + rw [hk] at hs + obtain ⟨a, b, c, e, f⟩ := hs + refine ⟨a, b, c, ?_, fun j x y => ?_⟩ + · rw [← ht k (by omega) b]; exact e + · rw [← ht j (by omega) (by omega)]; exact f j x y + +theorem appendEntriesSound (env : Env) : AppendEntriesSound env := by + intro node source r saved actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have request := msgOk source _ rfl + have hsrc : env.names.id (env.names.name source) = source := msgInv_source request + have hnode : env.names.id (env.names.name node) = node := by rw [← savedName]; exact savedId + obtain ⟨hτe, hprev, hrt⟩ := ae_msg request + obtain ⟨hsz, -, hcomm, -, -, hviews, -⟩ := inv_parts invSaved + have hτ : forall j (h : j < ((r.entries.map (Exec.toExecEntry env)).toArray).size), + ((r.entries.map (Exec.toExecEntry env)).toArray)[j].term = Exec.aeTermOfIdx r := by + intro j h + simp only [List.getElem_toArray, List.getElem_map] + have := (hτe _ (List.getElem_mem (by simpa using h))).1 + rw [← this] + unfold Exec.toExecEntry + split <;> rfl + have hv2 : Not (saved.currentView > r.term) + -> (aeMid r saved).getTerm r.prevLogIndex = r.prevLogTerm + -> Exec.aeTermOfIdx r <= r.term := by + intro hns hm + unfold Exec.aeTermOfIdx + cases hl : r.entries.getLast? with + | some e => exact (hτe e (List.mem_of_getLast? hl)).2.2 + | none => + simp only [Option.map_none, Option.getD_none] + rw [← hm, aeMid_getTerm] + have := viewAt_le_size' (v := saved) r.prevLogIndex + simp only [State.getTerm] + split <;> omega + have hout := Hoare.run (hoare_recv (env := env) (env.names.name source) r + (firstTermConflictIndex (abs env.names saved) r) saved hsz hcomm hviews (ae_rc invSaved) hτ + (ae_conflict invSaved r _ fun e he => (hτe e he).1) hv2) ⟨rfl, rfl⟩ ran + have hK := ae_conflict invSaved r _ fun e he => (hτe e he).1 + generalize hKdef : firstTermConflictIndex (abs env.names saved) r = K at hout hK + have hUnid : (aeMid r saved).nodeId = saved.nodeId := (aeMid_frame r saved).2.2.2.2.2.2.1 + have hnid : c.vars.nodeId = saved.nodeId := by + rcases hout with ⟨-, hv, -⟩ | ⟨-, -, ⟨-, hv, -⟩ | ⟨-, ⟨-, hv, -⟩ | ⟨-, -, ⟨-, hv, -⟩ + | ⟨-, hg, -, -⟩⟩⟩⟩ + · rw [hv] + · rw [hv]; exact hUnid + · rw [hv]; exact hUnid + · rw [hv]; exact hUnid + · have := hg.1.nodeId + simp only [core, aePar] at this + rw [this]; exact hUnid + refine ⟨hnid, fun clean _ agreed unmatched => ?_⟩ + have reply : forall m : Message, (forall q, m ≠ .appendEntriesRequest q) + -> c.outbox = [⟨node, source, m⟩] + -> forall envelope, envelope ∈ c.outbox -> msgInv env.names envelope = true := by + intro m hm hout envelope member + rw [hout, List.mem_singleton] at member + subst member + exact msgInv_reply hnode request hm + have run := fun clean' (out : CCF.Outputs NodeID Message Notification) step => + LocalRun.cons (protocol := protocol env) (node := node) (state := clean) (middle := clean') + (action := (protocol env).receive source (.appendEntriesRequest r)) (effects := out) step + (LocalRun.nil _) + have step := clean_ae node source clean r + obtain ⟨hterm, hlog⟩ := agrees_term_log agreed + have hlen : clean.log.length = saved.lastIdx := by rw [hlog, abs_log_length hsz] + rcases hout with ⟨stale, hv, ho⟩ | ⟨hns, hnl, hrest⟩ + · have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + have hcm : cleanMid clean r = clean := by + unfold cleanMid + split + · rename_i h; omega + · rfl + rw [hu, handle_nack node source clean r (Or.inl (by rw [hcm]; omega)), hcm] at step + simp only [show r.term < clean.currentTerm by omega, true_or, ↓reduceIte] at step + have hout : c.outbox = [⟨node, source, aerMsg clean.currentTerm clean.log.length false⟩] := by + rw [ho]; simp [aerOut, aerMsg, savedId, hsrc, hterm, hlen] + refine ⟨[], clean, ?_, ?_, unmatched, by simp, reply _ (by simp [aerMsg]) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [hv]; exact agreed + · have hagm := cleanMid_agrees (r := r) agreed hns + have hN := handle_nack node source (updateTerm clean r.term) r + have hS := handle_silent node source (updateTerm clean r.term) r + have hA := handle_accept node source (updateTerm clean r.term) r + generalize hcmdef : cleanMid (updateTerm clean r.term) r = cm at hagm hN hS hA + obtain ⟨hterm', hlog'⟩ := agrees_term_log hagm + rw [abs_aeMid_log] at hlog' + obtain ⟨hlI, -, -, hciU, -, -, -, -⟩ := aeMid_frame r saved + have h1 : Not (r.term < cm.currentTerm) := by rw [hterm', aeMid_view r saved hns]; omega + have hgt : forall i, (aeMid r saved).getTerm i = termAt cm.log i := by + intro i; rw [aeMid_getTerm, getTerm_eq invSaved, hlog'] + have hcmlen : cm.log.length = saved.lastIdx := by rw [hlog', abs_log_length hsz] + have hrole : cm.role ≠ .primary := by rw [agrees_role hagm]; exact absRole_ne_primary hnl + have hcci : cm.commitIndex = saved.commitIdx := by rw [(agrees_rci hagm).2.1, hciU] + rcases hrest with ⟨hmis, hv, ho⟩ | ⟨hmatch, hrest⟩ + · have h2 : Not (appendEntryMatchesLog cm r) := fun ⟨_, h⟩ => hmis (by rw [hgt]; exact h) + rw [hN (Or.inr h2)] at step + simp only [h1, false_or] at step + rw [hv] at invVars + have hout : c.outbox = [⟨node, source, + if termAt cm.log r.prevLogIndex = 0 then + aerMsg cm.currentTerm cm.log.length false + else + aerMsg (termAt cm.log (findHighestPossibleMatch cm.log r.prevLogIndex r.prevLogTerm)) + (findHighestPossibleMatch cm.log r.prevLogIndex r.prevLogTerm) false⟩] := by + rw [ho] + unfold nackOut + rw [highestMatch_eq invVars, abs_aeMid_log, ← hlog', hgt, hgt] + split <;> simp [aerOut, aerMsg, hUnid, savedId, hsrc, hterm', hcmlen, hlI] + refine ⟨[], cm, ?_, ?_, unmatched_of_role hrole, by simp, + reply _ (by split <;> simp [aerMsg]) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [hv]; exact hagm + · have hP : r.prevLogIndex <= saved.lastIdx := by + apply Classical.byContradiction + intro hgt' + have h0 : (aeMid r saved).getTerm r.prevLogIndex = 0 := by + simp only [State.getTerm, hlI]; split + · rfl + · omega + omega + have h2 : appendEntryMatchesLog cm r := ⟨by omega, by rw [← hgt]; exact hmatch⟩ + have hkn := agrees_known (env.names.name source) hagm + have hrole' : ({ cm with primaryKnown := true } : NodeState).role ≠ .primary := hrole + have hK' : firstTermConflictIndex cm r = K := by + rw [← hKdef]; unfold firstTermConflictIndex; rw [hlog'] + have hnfc : cm.isNewFollower = (aeMid r saved).isNewFollower := (agrees_rci hagm).2.2 + rcases hrest with ⟨hlt, hv, ho⟩ | ⟨hci, -, hrest⟩ + · rw [hS h1 h2 (Or.inl (by omega))] at step + refine ⟨[], _, ?_, ?_, unmatched_of_role hrole', by simp, by simp [ho]⟩ + · simpa [cleanActions, ho] using run _ _ step + · rw [hv]; exact hkn + · rcases hrest with ⟨hsil, hv, ho⟩ | ⟨hnsil, hg, hbd, ho⟩ + · rw [hS h1 h2 (Or.inr ⟨by rw [hK']; exact hsil.1, by + have := hsil.2; simp only [aeU] at this; simp [hnfc, this]⟩)] at step + refine ⟨[], _, ?_, ?_, unmatched_of_role hrole', by simp, by simp [ho]⟩ + · simpa [cleanActions, ho] using run _ _ step + · rw [hv]; exact hkn + · have h3 : Not (r.prevLogIndex < cm.commitIndex + \/ ((firstTermConflictIndex cm r).isSome /\ !cm.isNewFollower)) := by + rw [hK', hnfc, hcci] + intro h + rcases h with h | ⟨ha, hb⟩ + · omega + · exact hnsil ⟨ha, by simpa [aeU] using hb⟩ + rw [hA h1 h2 h3, hK'] at step + have hKU : ConflictSpec (aeU (env.names.name source) r saved) r.prevLogIndex + r.entries.length (Exec.aeTermOfIdx r) K := + conflictSpec_congr (aeMid_frame r saved).1 (aeMid_frame r saved).2.2.1 hK + obtain ⟨hres, hag⟩ := accept_agrees env (env.names.name source) r saved c.vars K cm + invSaved invVars hkn hns hP hci hKU hrt hg hbd + rw [savedId] at hres hag + have hout : c.outbox = [⟨node, source, + .appendEntriesResponse (handleAppendEntiresFromPrimary node (cutClean cm K) r).2⟩] := by + rw [ho, hres]; simp [ack, hnid, savedId, hsrc] + refine ⟨[], _, ?_, hag, unmatched_of_role ?_, by simp, reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [agrees_role hag]; exact absRole_ne_primary hg.1.nl + +end Consensus.TraceValidation.Proofs From 750fe5a0082aca06137f696cb41af42eb25a7d1b Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:11 +0000 Subject: [PATCH 11/25] Prove the vote obligations RequestVote, RequestPreVote, their responses and ProposeRequestVote refine the clean vote steps, including becoming leader when a quorum is reached in every active configuration. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 7 +- .../Proofs/Handlers/ProposeRequestVote.lean | 31 + .../Proofs/Handlers/RequestPreVote.lean | 77 ++ .../Handlers/RequestPreVoteResponse.lean | 32 + .../Proofs/Handlers/RequestVote.lean | 92 ++ .../Proofs/Handlers/RequestVoteResponse.lean | 32 + .../Proofs/Handlers/VoteBecomeLeader.lean | 989 ++++++++++++++++++ .../Proofs/Handlers/VoteCandidate.lean | 651 ++++++++++++ .../Proofs/Handlers/VotePropose.lean | 205 ++++ .../Proofs/Handlers/VoteResponse.lean | 573 ++++++++++ .../Proofs/Handlers/VoteTally.lean | 527 ++++++++++ 11 files changed, 3214 insertions(+), 2 deletions(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ProposeRequestVote.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVote.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVoteResponse.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVote.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVoteResponse.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteBecomeLeader.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteCandidate.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VotePropose.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteResponse.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteTally.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 8c5f6bdffaaa..2f81d5d3d4e0 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -10,7 +10,10 @@ import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup import Consensus.TraceValidation.Proofs.Handlers.OutOfLockHook -import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit -import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas +import Consensus.TraceValidation.Proofs.Handlers.ProposeRequestVote +import Consensus.TraceValidation.Proofs.Handlers.RequestPreVote +import Consensus.TraceValidation.Proofs.Handlers.RequestPreVoteResponse +import Consensus.TraceValidation.Proofs.Handlers.RequestVote +import Consensus.TraceValidation.Proofs.Handlers.RequestVoteResponse import Consensus.TraceValidation.Proofs.Section import Consensus.TraceValidation.Proofs.Validator diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ProposeRequestVote.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ProposeRequestVote.lean new file mode 100644 index 000000000000..d348e151993a --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ProposeRequestVote.lean @@ -0,0 +1,31 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VotePropose + +@[expose] public section + +/-! +# Obligation: `recv_propose_request_vote` (not reviewed) + +The hold is matched by the clean receive of the proposal alone (`propose_spec`). +-/ + +namespace Consensus.TraceValidation.Proofs + +open Vote + +theorem proposeRequestVoteSound (env : Env) : ProposeRequestVoteSound env := by + intro node source t saved _ actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + obtain ⟨nid, cl⟩ := Ae.Hoare.run (propose_spec env (source := source) t savedId invSaved) + ⟨rfl, rfl⟩ ran + refine ⟨nid, fun clean _ ag um => ?_⟩ + obtain ⟨clean', em, ag', um', mi⟩ := cl clean ag um invVars + exact ⟨[], clean', localRun_receive env em, ag', um', by simp, mi⟩ + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVote.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVote.lean new file mode 100644 index 000000000000..ef792be60fd4 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVote.lean @@ -0,0 +1,77 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas + +@[expose] public section + +/-! +# Obligation: `recv_request_vote` for a pre-vote (not reviewed) + +As `RequestVote`, without recording a vote: a stale request is refused in the node's view; +otherwise the node adopts a newer view and grants iff the candidate's log is at least as up +to date. It is matched by the clean receive of the request alone. +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) +open Vote + +theorem requestPreVoteSound (env : Env) : RequestPreVoteSound env := by + intro node source r saved actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished _ + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + obtain ⟨hv, ho⟩ := Det.run (det_recvRequestVote env (env.names.name source) true r) ran + have request := msgOk source _ rfl + have hsrc : env.names.id (env.names.name source) = source := msgInv_source request + have hnode : env.names.id (env.names.name node) = node := by rw [← savedName]; exact savedId + refine ⟨by rw [hv]; exact rvVars_nodeId .., fun clean _ agreed unmatched => ?_⟩ + have step := clean_preVote node source clean r + have hrun := LocalRun.cons (protocol := protocol env) (node := node) (state := clean) + (action := (protocol env).receive source (.requestPreVoteRequest r)) step (LocalRun.nil _) + have reply : forall m : Message, (forall q, m ≠ .appendEntriesRequest q) + -> c.outbox = [⟨node, source, m⟩] + -> forall envelope, envelope ∈ c.outbox -> msgInv env.names envelope = true := by + intro m hm hout envelope member + rw [hout, List.mem_singleton] at member + subst member + exact msgInv_reply hnode request hm + obtain ⟨hterm, hlog⟩ := agrees_term_log agreed + by_cases stale : saved.currentView > r.term + · have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + have hout : c.outbox + = [⟨node, source, .requestPreVoteResponse + { term := (updateTerm clean r.term).currentTerm, + voteGranted := decide (r.term = (updateTerm clean r.term).currentTerm) + && cleanLogOk (updateTerm clean r.term) r }⟩] := by + rw [ho, hu] + simp [rvOut, stale, rvResp, savedId, hsrc, hterm] + omega + refine ⟨[], _, ?_, ?_, unmatched_updateTerm r.term unmatched, by simp, + reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using hrun + · rw [hv, hu]; simpa [rvVars, stale] using agreed + · obtain ⟨ha, ht⟩ := rvMid_agrees (r := r) agreed stale + obtain ⟨hterm', hlog'⟩ := agrees_term_log ha + obtain ⟨hlc, hgt, hal, -⟩ := rvMid_frame (names := env.names) r saved + rw [hal] at hlog' + have hok := logOk_eq invSaved hlog' r + have hout : c.outbox + = [⟨node, source, .requestPreVoteResponse + { term := (updateTerm clean r.term).currentTerm, + voteGranted := decide (r.term = (updateTerm clean r.term).currentTerm) + && cleanLogOk (updateTerm clean r.term) r }⟩] := by + rw [ho, ← hok, hterm', ht] + simp [rvOut, stale, rvResp, savedId, hsrc, rvGrant, hlc, hgt, ht] + refine ⟨[], _, ?_, ?_, unmatched_updateTerm r.term unmatched, by simp, + reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using hrun + · rw [hv]; simpa [rvVars, stale] using ha + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVoteResponse.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVoteResponse.lean new file mode 100644 index 000000000000..f4cca9d79edb --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestPreVoteResponse.lean @@ -0,0 +1,32 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteResponse + +@[expose] public section + +/-! +# Obligation: `recv_request_vote_response` of a pre-vote (not reviewed) + +The hold is matched by the clean receive of the pre-vote response alone (`voteResponse_spec`). +-/ + +namespace Consensus.TraceValidation.Proofs + +open Vote + +theorem requestPreVoteResponseSound (env : Env) : RequestPreVoteResponseSound env := by + intro node source r saved init actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have hsrc := msgInv_source (msgOk source _ rfl) + obtain ⟨nid, cl⟩ := Ae.Hoare.run (voteResponse_spec env true r savedId hsrc invSaved init) + ⟨rfl, rfl⟩ ran + refine ⟨nid, fun clean _ ag um => ?_⟩ + obtain ⟨clean', em, ag', um', mi⟩ := cl clean ag um invVars + exact ⟨[], clean', localRun_receive env em, ag', um', by simp, mi⟩ + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVote.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVote.lean new file mode 100644 index 000000000000..48cd3ad406a0 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVote.lean @@ -0,0 +1,92 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas + +@[expose] public section + +/-! +# Obligation: `recv_request_vote` (not reviewed) + +The hold is deterministic (`det_recvRequestVote`): a stale request is refused in the node's +view; otherwise the node adopts a newer view (`become_aware_of_new_term`), grants if it has +no leader, has not voted for another node and the candidate's log is at least as up to date, +records the vote, and answers. It is matched by the clean receive of the request alone: +`observeTerm` is `become_aware_of_new_term`, and the clean grant is M_tv's (`rvGrant_eq`, +through `lastCommittable_eq` and `getTerm_eq`). +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (State) +open Vote + +theorem requestVoteSound (env : Env) : RequestVoteSound env := by + intro node source r saved actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished _ + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + obtain ⟨hv, ho⟩ := Det.run (det_recvRequestVote env (env.names.name source) false r) ran + have request := msgOk source _ rfl + have hsrc : env.names.id (env.names.name source) = source := msgInv_source request + have hnode : env.names.id (env.names.name node) = node := by rw [← savedName]; exact savedId + refine ⟨by rw [hv]; exact rvVars_nodeId .., fun clean _ agreed unmatched => ?_⟩ + have reply : forall m : Message, (forall q, m ≠ .appendEntriesRequest q) + -> c.outbox = [⟨node, source, m⟩] + -> forall envelope, envelope ∈ c.outbox -> msgInv env.names envelope = true := by + intro m hm hout envelope member + rw [hout, List.mem_singleton] at member + subst member + exact msgInv_reply hnode request hm + have run := fun clean' (out : CCF.Outputs NodeID Message Notification) step => + LocalRun.cons (protocol := protocol env) (node := node) (state := clean) (middle := clean') + (action := (protocol env).receive source (.requestVoteRequest r)) (effects := out) step + (LocalRun.nil _) + have step := clean_vote node source clean r + obtain ⟨hterm, hlog⟩ := agrees_term_log agreed + by_cases stale : saved.currentView > r.term + · have hu : updateTerm clean r.term = clean := updateTerm_of_ge (by omega) + have refused : cleanGrant clean r source = false := by + simp [cleanGrant, hterm]; omega + rw [hu, refused] at step + simp only [Bool.false_eq_true, ite_false] at step + have hout : c.outbox + = [⟨node, source, .requestVoteResponse + { term := clean.currentTerm, voteGranted := false }⟩] := by + rw [ho]; simp [rvOut, stale, rvResp, savedId, hsrc, hterm] + refine ⟨[], clean, ?_, ?_, unmatched, by simp, reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [hv]; simpa [rvVars, stale] using agreed + · obtain ⟨ha, ht⟩ := rvMid_agrees (r := r) agreed stale + have grant := rvGrant_eq invSaved ha ht hsrc + obtain ⟨hterm', -⟩ := agrees_term_log ha + have hout : c.outbox + = [⟨node, source, .requestVoteResponse + { term := (updateTerm clean r.term).currentTerm, + voteGranted := cleanGrant (updateTerm clean r.term) r source }⟩] := by + rw [ho]; simp [rvOut, stale, rvResp, savedId, hsrc, hterm', grant] + have unmatched' := unmatched_updateTerm r.term unmatched + cases granted : cleanGrant (updateTerm clean r.term) r source + · rw [granted] at step hout + simp only [Bool.false_eq_true, ite_false] at step + refine ⟨[], _, ?_, ?_, unmatched', by simp, reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [hv]; simpa [rvVars, stale, grant, granted] using ha + · rw [granted] at step hout + simp only [ite_true] at step + have hl : (rvMid r saved).leaderId = none := by + rw [← grant] at granted + simp only [rvGrant, Bool.and_eq_true] at granted + cases h : (rvMid r saved).leaderId <;> simp_all + refine ⟨[], { updateTerm clean r.term with votedFor := some source }, ?_, ?_, + unmatched_frame unmatched' fun p => ⟨p, rfl, rfl⟩, by simp, + reply _ (by simp) hout⟩ + · simpa [cleanActions, hout] using run _ _ step + · rw [hv] + simpa [rvVars, stale, grant, granted] using agrees_vote ha hl hsrc + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVoteResponse.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVoteResponse.lean new file mode 100644 index 000000000000..712898fea282 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/RequestVoteResponse.lean @@ -0,0 +1,32 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteResponse + +@[expose] public section + +/-! +# Obligation: `recv_request_vote_response` of a vote (not reviewed) + +The hold is matched by the clean receive of the vote response alone (`voteResponse_spec`). +-/ + +namespace Consensus.TraceValidation.Proofs + +open Vote + +theorem requestVoteResponseSound (env : Env) : RequestVoteResponseSound env := by + intro node source r saved init actions c vars others cleanOthers savedName savedId invSaved + msgOk _ ran _ finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have hsrc := msgInv_source (msgOk source _ rfl) + obtain ⟨nid, cl⟩ := Ae.Hoare.run (voteResponse_spec env false r savedId hsrc invSaved init) + ⟨rfl, rfl⟩ ran + refine ⟨nid, fun clean _ ag um => ?_⟩ + obtain ⟨clean', em, ag', um', mi⟩ := cl clean ag um invVars + exact ⟨[], clean', localRun_receive env em, ag', um', by simp, mi⟩ + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteBecomeLeader.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteBecomeLeader.lean new file mode 100644 index 000000000000..b094b6fececd --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteBecomeLeader.lean @@ -0,0 +1,989 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteLemmas +public import Consensus.TraceValidation.Proofs.Handlers.AeHoare +public import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit + +@[expose] public section + +/-! +# `become_leader` refines the clean `becomePrimary` (not reviewed) + +`becomeLeader_spec`: from a declared non-leader `d` that a clean state `c` agrees with, and +whose ledger has no entry in its current view (`LeaderPre`), M_tv's `becomeLeader` either +stops at once (the node is retired-committed, as `c` is) or ends as a leader that, if it +satisfies `inv`, the clean `primaryState c` agrees with, having sent exactly what the clean +`becomePrimary c` sends: an empty AppendEntries at the end of the log to each eligible peer, +in order. + +With no entry in the current view neither side can commit at election: the clean +`highestCommittableIndex` only commits an entry of the current term, and cft.h's +`update_commit` only one in the current view. A node that has just become candidate has +incremented its view past every view of its ledger. + +On the M_tv side (`becomeLeader_tv`): the election rollback to the last committable index is +the clean `primaryState`'s truncation; `create_and_remove_node_state` after it only changes +peers (the node is not leader yet); `update_commit` commits nothing; and each +`send_append_entries` from one past the last index is one empty AppendEntries. The peers are +the clean eligible peers: after a rollback by the explicit check in `becomeLeader`, and +without one by `LeaderPre.peers` (from the `peers` conjuncts of `inv`); a node with an empty +ledger has none, by the `empty_leader_alone` conjunct of the final `inv`. +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae (Hoare) + +/-! ## Clean effects that succeed and append known sends -/ + +/-- `x` succeeds from any outputs with result `a`, appending exactly `sends`. -/ +def Emits {α : Type} (x : NodeEffect α) (a : α) + (sends : List (CCF.Envelope NodeID Message)) + : Prop := + forall out : CCF.Outputs NodeID Message Notification, + x.run out = some (a, { out with outgoing := out.outgoing ++ sends }) + +theorem emits_pure {α : Type} (a : α) : Emits (pure a : NodeEffect α) a [] := by + intro out + cases out + simp [StateT.run, pure, StateT.pure] + +theorem emits_bind {α β : Type} {x : NodeEffect α} {f : α -> NodeEffect β} {a : α} {b : β} + {first later : List (CCF.Envelope NodeID Message)} + (hx : Emits x a first) (hf : Emits (f a) b later) + : Emits (x >>= f) b (first ++ later) := by + intro out + have := hx out + simp only [StateT.run, bind, StateT.bind] at this ⊢ + rw [this] + simp only [Option.bind] + have := hf { out with outgoing := out.outgoing ++ first } + simp only [StateT.run, List.append_assoc] at this + exact this + +theorem emits_congr {α : Type} {x : NodeEffect α} {a b : α} + {first later : List (CCF.Envelope NodeID Message)} + (h : Emits x a first) (same : a = b) (sends : first = later) + : Emits x b later := by + subst same sends + exact h + +theorem emits_send {node : NodeID} (message : Message) (target : NodeID) + : Emits ((CCF.Capabilities.record node).send message target) () + [⟨node, target, message⟩] := by + intro out + rfl + +theorem emits_forIn {node : NodeID} (peers : List NodeID) (f : NodeID -> Message) + : Emits + (forIn peers PUnit.unit + fun peer _ => do + (CCF.Capabilities.record node).send (f peer) peer + pure (ForInStep.yield PUnit.unit) + : NodeEffect PUnit) + PUnit.unit (peers.map fun peer => ⟨node, peer, f peer⟩) := by + induction peers with + | nil => exact emits_pure _ + | cons peer rest ih => + rw [List.forIn_cons] + refine emits_congr (emits_bind + (x := do (CCF.Capabilities.record node).send (f peer) peer; pure (ForInStep.yield PUnit.unit)) + (a := ForInStep.yield PUnit.unit) + (emits_bind (f := fun _ => pure (ForInStep.yield PUnit.unit)) (emits_send _ _) + (emits_pure _)) ih) rfl ?_ + simp + +/-! ## The clean election -/ + +/-- The empty AppendEntries a new primary in state `s` sends to `peer`. -/ +def heartbeat (self : NodeID) (s : NodeState) (peer : NodeID) + : CCF.Envelope NodeID Message := + ⟨ + self, + peer, + .appendEntriesRequest + { + term := s.currentTerm, + prevLogIndex := s.log.length, + prevLogTerm := termAt s.log s.log.length, + entries := [], + primaryCommit := s.commitIndex + } + ⟩ + +theorem foldl_stuck {f : Nat -> Nat -> Nat} (h : forall a i, f a i = a) (l : List Nat) + (init : Nat) + : l.foldl f init = init := by + induction l generalizing init with + | nil => rfl + | cons x xs ih => simp only [List.foldl_cons, h, ih] + +theorem highestCommittableIndex_stuck {s : NodeState} (self : NodeID) + (noTerm : forall i, termAt s.log i ≠ s.currentTerm) + : highestCommittableIndex s self = s.commitIndex := by + unfold highestCommittableIndex + exact foldl_stuck (fun a i => by simp [noTerm]) _ _ + +/-- +The clean election from `c` when no entry of the truncated log is in the current term: the +primary state, and a heartbeat to each eligible peer. +-/ +theorem emits_becomePrimary (self : NodeID) (c : NodeState) + (noTerm : forall i, termAt (primaryState c).log i ≠ c.currentTerm) + : Emits (becomePrimary (CCF.Capabilities.record self) self c) (primaryState c) + (((eligiblePeers (primaryState c) self).sort).map + (heartbeat self (primaryState c))) := by + unfold becomePrimary + have stuck : highestCommittableIndex (primaryState c) self = (primaryState c).commitIndex := + highestCommittableIndex_stuck self noTerm + have adv : advanceCommit (CCF.Capabilities.record self) (primaryState c) self + = pure (primaryState c) := by + unfold advanceCommit + simp [stuck] + simp only [adv] + refine emits_congr (emits_bind (emits_pure _) + (emits_bind (emits_forIn _ _) (emits_pure _))) rfl ?_ + simp only [List.nil_append, List.append_nil] + apply List.map_congr_left + intro peer _ + simp [heartbeat, makeAppendEntriesRequest, messageEntries, primaryState] + +/-! ## `update_commit` commits nothing without an entry in the current view -/ + +theorem getTerm_ne_view {v : State} (h : v.views.size < v.currentView) (i : Nat) + : v.getTerm i ≠ v.currentView := by + have := ReplUpdateCommit.viewAt_le_size v i + unfold State.getTerm + split <;> omega + +theorem highestCommittableIdxOf_term {v : State} {first nc : Nat} + (h : highestCommittableIdxOf v first = .ok (some nc)) + : v.getTerm nc = v.currentView := by + unfold highestCommittableIdxOf at h + simp only [bind, Except.bind, pure, Except.pure] at h + repeat' (split at h <;> try simp_all [throw, throwThe, MonadExceptOf.throw]) + +theorem updateCommitOf_none {v : State} (h : v.views.size < v.currentView) + {first fuel : Nat} {r : Option Nat} + (run : ReplUpdateCommit.updateCommitOf v first none fuel = .ok r) + : r = none := by + cases fuel with + | zero => simp [ReplUpdateCommit.updateCommitOf] at run + | succ fuel => + simp only [ReplUpdateCommit.updateCommitOf] at run + split at run + · cases run + · cases run; rfl + · rename_i i found + exact absurd (highestCommittableIdxOf_term found) (getTerm_ne_view h i) + +/-- A leader without an entry in its current view: `update_commit` changes nothing. -/ +theorem updateCommit_noop (env : Env) {u : State} {o0 : Outbox} + (h : u.views.size < u.currentView) + : Hoare env (fun v o => v = u /\ o = o0) Exec.updateCommit + (fun _ v o => v = u /\ o = o0) := by + unfold Exec.updateCommit + refine Ae.Hoare.getV_bind fun s => ?_ + dsimp only + refine Ae.Hoare.ite (fun _ => ?_) (fun _ => ?_) + · refine Ae.Hoare.bind (Ae.Hoare.of_spec (ReplUpdateCommit.updateCommitGo_spec _ _ _) + (Q := fun r v o => v = u /\ o = o0 /\ r = none) + fun v o r v' o' ⟨⟨hv, ho⟩, hs⟩ ⟨e1, e2, run⟩ => ?_) fun r => ?_ + · subst hv hs e1 e2 ho + exact ⟨rfl, rfl, updateCommitOf_none h run⟩ + · split + · exact Ae.Hoare.false_pre fun _ _ ⟨_, _, e⟩ => by cases e + · exact Ae.Hoare.pure _ fun _ _ ⟨hv, ho, _⟩ => ⟨hv, ho⟩ + · exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) fun _ => + Ae.Hoare.false_pre fun _ _ f => f + +/-! ## Peer bookkeeping on a non-leader -/ + +/-- The outbox is `o0` and the state is `v0` up to its peers. -/ +def PeersOnly (v0 : State) (o0 : Outbox) (v : State) (o : Outbox) : Prop := + o = o0 /\ exists p, v = { v0 with allOtherNodes := p } + +theorem createAndRemove_peers (env : Env) {v0 : State} {o0 : Outbox} + (nl : v0.leadership ≠ .leader) + : Hoare env (PeersOnly v0 o0) Exec.createAndRemoveNodeState + (fun _ => PeersOnly v0 o0) := by + unfold Exec.createAndRemoveNodeState + refine Ae.Hoare.getV_bind fun s => ?_ + dsimp only + refine Ae.Hoare.bind + (Ae.Hoare.pre + (Ae.Hoare.forIn_list _ _ _ (fun _ _ => PeersOnly v0 o0) + (fun _ => PeersOnly v0 o0) ?_ fun _ _ _ p => p) + fun _ _ p => p.1) + fun _ => Ae.Hoare.pure _ fun _ _ p => p + intro pre id rest b _ + split + · exact Ae.Hoare.pure _ fun _ _ p => p + · refine Ae.Hoare.getV_bind fun s' => ?_ + split + · refine Ae.Hoare.bind (R := fun _ v o => PeersOnly v0 o0 v o /\ s'.leadership = v0.leadership) + (Ae.Hoare.setV _ ?_) fun _ => ?_ + · rintro v o ⟨⟨ho, p, rfl⟩, rfl⟩ + exact ⟨⟨ho, _, rfl⟩, rfl⟩ + · split + · rename_i hl + exact Ae.Hoare.false_pre fun _ _ ⟨_, e⟩ => nl (by rw [← e]; simpa using hl) + · exact Ae.Hoare.pure _ fun _ _ p => p.1 + · exact Ae.Hoare.pure _ fun _ _ p => p.1 + +/-! ## The election rollback -/ + +/-- +`v` is `d` rolled back to `e`: the ledger, view history, committable indexes and pending +retired-committed records are cut at `e`; configurations are a subset of `d`'s; peers and +retirement phases other than retired-committed may change. +-/ +def RolledTo (e : Nat) (d v : State) : Prop := + exists (cfg : List Config) (p : List (NodeId × Peer)) (rt : Bool) (rp + : Option Phase) (rci ri + : Option + Nat), + v + = { + d with + rcEntries := d.rcEntries.filter (·.1 <= e), + ledger := d.ledger.extract 0 e, + lastIdx := e, + views := d.views.filter (· <= e), + committable := d.committable.filter (· <= e), + configurations := cfg, + allOtherNodes := p, + retired := rt, + retirementPhase := rp, + retirementCommittableIdx := rci, + retirementIdx := ri + } + /\ (forall x, x ∈ cfg -> x ∈ d.configurations) + /\ (rt && rp == some .retiredCommitted) = false + +theorem rollback_spec (env : Env) {d : State} {o0 : Outbox} {e : Nat} + (nl : d.leadership ≠ .leader) (ce : d.commitIdx <= e) + (nrc : d.isRetiredCommitted = false) + : Hoare env (fun v o => v = d /\ o = o0) (Exec.rollback e) + (fun _ v o => o = o0 /\ RolledTo e d v) := by + unfold Exec.rollback + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.ite (fun lt => Ae.Hoare.false_pre fun v o ⟨⟨hv, _⟩, hs⟩ => ?_) + fun _ => ?_ + · subst hv hs; omega + refine Ae.Hoare.bind + (R := fun _ v o => o = o0 /\ RolledTo e d v /\ v.leadership = d.leadership) + (Ae.Hoare.setV _ ?_) fun _ => ?_ + · rintro v o ⟨⟨rfl, rfl⟩, -⟩ + simp only [State.isRetiredCommitted, Bool.and_eq_false_iff] at nrc + refine ⟨rfl, ?_, ?_⟩ + · dsimp only + split <;> split + all_goals exact ⟨_, _, _, _, _, _, rfl, fun _ h => h, by + first | (simp_all; done) | (simp_all; intro h; cases nrc <;> simp_all)⟩ + · dsimp only + split <;> split <;> rfl + refine Ae.Hoare.getV_bind fun w => ?_ + dsimp only + refine Ae.Hoare.ite (fun _ => ?_) fun _ => Ae.Hoare.pure _ fun _ _ p => ⟨p.1.1, p.1.2.1⟩ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨ho, rt, hl⟩, hw⟩ => ?_ + subst ho hw + refine Ae.Hoare.bind + (R := fun _ v o => PeersOnly + { v1 with configurations := v1.configurations.filter (fun c => c.idx <= e) } o1 v o) + (Ae.Hoare.setV _ ?_) fun _ => ?_ + · rintro v o ⟨rfl, rfl⟩ + exact ⟨rfl, _, rfl⟩ + refine Ae.Hoare.post (Ae.Hoare.pre (createAndRemove_peers env ?_) fun _ _ p => p) ?_ + · simpa using hl ▸ nl + · obtain ⟨cfg, p, rt', rp, rci, ri, rfl, hcfg, hrc⟩ := rt + rintro _ v o ⟨rfl, p', rfl⟩ + exact ⟨rfl, _, p', rt', rp, rci, ri, rfl, + fun x h => hcfg x (List.mem_filter.1 h).1, hrc⟩ + +/-! ## The election heartbeat -/ + +/-- Step over an operation that keeps the state and outbox. -/ +macro "keep_step" : tactic => + `(tactic| first + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.trace _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.emit _ _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.emitStr _ _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps Spec.look fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.use _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.liftE _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps (Spec.note _) fun _ _ _ p => p) fun _ => ?_ + | refine Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => ?_) + +/-- The empty `AppendEntries` a new leader sends each peer from its ledger end. -/ +def hbMsg (w : State) : Message := + .appendEntriesRequest + { + term := w.currentView, + prevLogIndex := w.lastIdx, + prevLogTerm := w.getTerm w.lastIdx, + entries := [], + primaryCommit := w.commitIdx + } + +theorem viewAt_end {w : State} (h : forall x, x ∈ w.views.toList -> x <= w.lastIdx + 1) + : w.viewAt (w.lastIdx + 1) = w.views.size := by + simp only [State.viewAt] + rw [List.filter_eq_self.2 (by simpa using h), Array.length_toList] + +theorem sendRange_hb (env : Env) {w : State} {o1 : Outbox} (id : NodeId) + : Hoare env (fun v o => v = w /\ o = o1) + (Exec.sendAppendEntriesRange id (w.lastIdx + 1) w.lastIdx false) + (fun _ v o => + exists p : Peer, + w.peer? id = some p + /\ v = w.setPeer id { p with sentIdx := w.lastIdx } + /\ o + = o1 + ++ [CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) + (hbMsg w)]) := by + unfold Exec.sendAppendEntriesRange + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o2 ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst h1 h2 h3 + dsimp only + split + rotate_left + · exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => Ae.Hoare.fail _ + rename_i node hnode + keep_step + keep_step + refine Ae.Hoare.bind (Ae.Hoare.of_spec Spec.names + (Q := fun a v o => a = env.names /\ v = v1 /\ o = o2) + fun v o a v' o' p ⟨ha, hv, ho⟩ => ⟨ha, hv ▸ p.1, ho ▸ p.2⟩) fun nm => ?_ + refine Ae.Hoare.lift fun hn => ?_ + subst hn + refine Ae.Hoare.bind + (Ae.Hoare.send _ _ + (Q := + fun _ v o => + v = v1 + /\ o + = o2 + ++ [CCF.Envelope.mk (env.names.id v1.nodeId) (env.names.id id) + (hbMsg v1)]) + fun v o ⟨hv, ho⟩ => ⟨hv, by subst hv ho; simp [hbMsg]⟩) + fun _ => ?_ + keep_step + exact Ae.Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨node, hv ▸ hnode, by subst hv; rfl, ho⟩ + +theorem sendHeartbeat (env : Env) {w : State} {o1 : Outbox} (id : NodeId) + (nrc : w.isRetiredCommitted = false) + (vle : forall x, x ∈ w.views.toList -> x <= w.lastIdx + 1) + : Hoare env (fun v o => v = w /\ o = o1) (Exec.sendAppendEntries id (w.lastIdx + 1)) + (fun _ v o => + exists p : Peer, + w.peer? id = some p + /\ v = w.setPeer id { p with sentIdx := w.lastIdx } + /\ o + = o1 + ++ [CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) + (hbMsg w)]) := by + unfold Exec.sendAppendEntries + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v0 o0' ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst h1 h2 h3 + rw [Exec.sendAppendEntries.loop] + refine Ae.Hoare.getV_bind fun s => ?_ + have h0 : v0.endOfView (v0.viewAt (v0.lastIdx + 1)) = 0 := by + rw [viewAt_end vle] + simp [State.endOfView] + refine Ae.Hoare.pin fun v1 o1 ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst h1 h2 h3 + dsimp only + simp only [h0, nrc, Bool.false_and, Bool.false_eq_true, ↓reduceIte, Option.any_none, + Nat.lt_add_one, gt_iff_lt] + keep_step + keep_step + keep_step + keep_step + refine Ae.Hoare.bind (R := fun _ v o => v = v1 /\ o = o1) + (Ae.Hoare.pure _ fun _ _ p => p) fun e => ?_ + refine Ae.Hoare.ite (fun he => ?_) fun _ => + Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) fun _ => + Ae.Hoare.false_pre fun _ _ f => f + obtain rfl : e = v1.lastIdx := by simpa using he + refine Ae.Hoare.ite (fun he => absurd he (Nat.lt_irrefl _)) fun _ => ?_ + refine Ae.Hoare.bind (R := fun _ v o => v = v1 /\ o = o1) + (Ae.Hoare.pure _ fun _ _ p => p) fun _ => ?_ + refine Ae.Hoare.bind (sendRange_hb env id) fun _ => ?_ + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.ite (fun _ => Ae.Hoare.pure _ fun _ _ p => p.1) fun hn => ?_ + refine Ae.Hoare.false_pre fun v o ⟨⟨p, _, hv, _⟩, hs⟩ => hn ?_ + subst hs hv + simp [State.setPeer] + +/-! ## Peer resets -/ + +/-- Every peer is in `L`, and those that `S` selects are reset to `P`. -/ +def PeerInv (L : List NodeId) (P : Peer) (S : NodeId -> Prop) (ps : List (NodeId × Peer)) + : Prop := + forall x, x ∈ ps -> x.1 ∈ L /\ (S x.1 -> x.2 = P) + +theorem mem_setPeer {v : State} {id : NodeId} {P : Peer} {x : NodeId × Peer} + (h : x ∈ (v.setPeer id P).allOtherNodes) + : (x ∈ v.allOtherNodes /\ x.1 ≠ id) \/ x = (id, P) := by + simp only [State.setPeer, List.mem_mergeSort, List.mem_append, List.mem_filter, + List.mem_singleton, bne_iff_ne, ne_eq] at h + exact h + +theorem peerInv_setPeer {L : List NodeId} {P : Peer} {S S' : NodeId -> Prop} {v : State} + {id : NodeId} (h : PeerInv L P S v.allOtherNodes) (hid : id ∈ L) + (hS : forall y, S' y -> S y \/ y = id) + : PeerInv L P S' (v.setPeer id P).allOtherNodes := by + intro x hx + rcases mem_setPeer hx with ⟨hx, hne⟩ | rfl + · exact ⟨(h x hx).1, fun s => (h x hx).2 ((hS _ s).resolve_right hne)⟩ + · exact ⟨hid, fun _ => rfl⟩ + +/-- Every id of `L` has an entry in `ps`. -/ +def Covers (L : List NodeId) (ps : List (NodeId × Peer)) : Prop := + forall y, y ∈ L -> exists q, (y, q) ∈ ps + +theorem covers_setPeer {L : List NodeId} {v : State} {id : NodeId} (P : Peer) + (h : Covers L v.allOtherNodes) + : Covers (L ++ [id]) (v.setPeer id P).allOtherNodes := by + intro y hy + simp only [State.setPeer, List.mem_mergeSort, List.mem_append, List.mem_filter, + List.mem_singleton, bne_iff_ne, ne_eq] + by_cases hyi : y = id + · exact ⟨P, Or.inr (by rw [hyi])⟩ + · obtain ⟨q, hq⟩ := h y (by simpa [hyi] using hy) + exact ⟨q, Or.inl ⟨hq, hyi⟩⟩ + +theorem covers_mono {L L' : List NodeId} {ps : List (NodeId × Peer)} (h : Covers L ps) + (sub : forall y, y ∈ L' -> y ∈ L) + : Covers L' ps := + fun y hy => h y (sub y hy) + +theorem peer_setPeer (v : State) (id : NodeId) (P : Peer) + : (v.setPeer id P).peer? id = some P := by + cases h : (v.setPeer id P).peer? id with + | none => + simp only [State.peer?, List.lookup_eq_none_iff] at h + exact absurd (h (id, P) (by simp [State.setPeer])) (by simp) + | some b => + obtain ⟨l1, l2, hl, -⟩ := List.lookup_eq_some_iff.mp h + have hm : (id, b) ∈ (v.setPeer id P).allOtherNodes := by rw [hl]; simp + rcases mem_setPeer hm with ⟨-, hne⟩ | he + · exact absurd rfl hne + · cases he; rfl + +/-! ## `become_leader` on M_tv -/ + +/-- `becomeLeader` after the election rollback: verbatim, so that it unfolds to the same term. -/ +def leaderTail : M Bool := do + setV fun v => { v with leadership := .leader, leaderId := some v.nodeId } + trace "become_leader" + if (← getV).otherNodesInActiveConfigs.isEmpty then updateCommit + let next := (← getV).lastIdx + 1 + for id in ← otherNodesSorted do + setV fun v => v.setPeer id { matchIdx := 0, sentIdx := next - 1 } + sendAppendEntries id next + return true + +/-- The new leader's sends: one heartbeat to each peer of `w`, in order. -/ +def hbs (names : Names) (w : State) : Outbox := + w.allOtherNodes.map + fun x => CCF.Envelope.mk (names.id w.nodeId) (names.id x.1) (hbMsg w) + +/-- A peer reset by the new leader. -/ +def resetPeer (w : State) : Peer := { sentIdx := w.lastIdx, matchIdx := 0 } + +theorem leaderLoop (env : Env) {w : State} {o1 : Outbox} + (nrc : w.isRetiredCommitted = false) + (vle : forall x, x ∈ w.views.toList -> x <= w.lastIdx + 1) + : let u : State := { w with leadership := .leader, leaderId := some w.nodeId } + Hoare env (fun v o => v = u /\ o = o1) + (do + let l ← otherNodesSorted + forIn l PUnit.unit + fun id _ => do + setV fun v => v.setPeer id { sentIdx := u.lastIdx + 1 - 1, matchIdx := 0 } + sendAppendEntries id (u.lastIdx + 1) + pure (ForInStep.yield PUnit.unit) + pure true) + (fun b v o => + b = true + /\ exists peers, + v + = { + w with + leadership := .leader, + leaderId := some w.nodeId, + allOtherNodes := peers + } + /\ PeerInv (w.allOtherNodes.map Prod.fst) (resetPeer w) (fun _ => True) + peers + /\ Covers (w.allOtherNodes.map Prod.fst) peers + /\ o = o1 ++ hbs env.names w) := by + intro u + let L := w.allOtherNodes.map Prod.fst + let f : NodeId -> CCF.Envelope NodeID Message := + fun id => CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) (hbMsg w) + refine Ae.Hoare.bind (R := fun l v o => l = L /\ v = u /\ o = o1) ?_ fun l => ?_ + · unfold Exec.otherNodesSorted + exact Ae.Hoare.getV_bind fun s => + Ae.Hoare.pure _ fun v o ⟨⟨hv, ho⟩, hs⟩ => ⟨by subst hs hv; rfl, hv, ho⟩ + refine Ae.Hoare.pin fun v3 o3 ⟨hl, hv, ho⟩ => ?_ + subst l v3 o3 + refine Ae.Hoare.bind (Ae.Hoare.pre (Ae.Hoare.forIn_list _ _ _ + (fun pre _ v o => exists ps, v = { u with allOtherNodes := ps } + /\ PeerInv L (resetPeer w) (· ∈ pre) ps /\ Covers pre ps /\ o = o1 ++ pre.map f) + (fun _ v o => exists ps, v = { u with allOtherNodes := ps } + /\ PeerInv L (resetPeer w) (· ∈ L) ps /\ Covers L ps /\ o = o1 ++ L.map f) ?_ + fun _ _ _ p => p) + fun v o ⟨hv, ho⟩ => ⟨w.allOtherNodes, hv, fun x hx => ⟨List.mem_map_of_mem hx, by simp⟩, + fun _ h => by simp at h, by simp [ho]⟩) fun _ => Ae.Hoare.pure _ + fun v o ⟨ps, hv, hinv, hcov, ho⟩ => + ⟨rfl, ps, hv, fun x hx => ⟨(hinv x hx).1, fun _ => (hinv x hx).2 (hinv x hx).1⟩, hcov, + by rw [ho]; simp [hbs, L, f]⟩ + intro pre id rest _ hl + have hid : id ∈ L := by rw [hl]; simp + refine Ae.Hoare.pin fun v4 o4 ⟨ps, hv, hinv, hcov, ho⟩ => ?_ + subst hv ho + let X1 := ({ u with allOtherNodes := ps } : State).setPeer id (resetPeer w) + refine Ae.Hoare.bind (R := fun _ v o => v = X1 /\ o = o1 ++ pre.map f) + (Ae.Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨by subst hv; rfl, ho⟩) fun _ => ?_ + refine Ae.Hoare.bind + (Ae.Hoare.pre (sendHeartbeat env (w := X1) id nrc vle) fun _ _ p => p) + fun _ => Ae.Hoare.pure _ fun v o ⟨p, hp, hv, ho⟩ => ?_ + rw [peer_setPeer] at hp + cases hp + refine ⟨(X1.setPeer id (resetPeer w)).allOtherNodes, by rw [hv]; rfl, ?_, ?_, ?_⟩ + · refine peerInv_setPeer (peerInv_setPeer hinv hid fun y h => ?_) hid fun y h => Or.inl h + simpa using h + · exact covers_mono (covers_setPeer (L := pre ++ [id]) (id := id) _ + (covers_setPeer (v := { u with allOtherNodes := ps }) _ hcov)) fun y hy => by simp_all + · rw [ho]; simp only [List.map_append, List.map_cons, List.map_nil, List.append_assoc]; rfl + +theorem leaderTail_spec (env : Env) {w : State} {o1 : Outbox} + (nrc : w.isRetiredCommitted = false) (vlt : w.views.size < w.currentView) + (vle : forall x, x ∈ w.views.toList -> x <= w.lastIdx + 1) + : Hoare env (fun v o => v = w /\ o = o1) leaderTail + (fun b v o => + b = true + /\ exists peers, + v + = { + w with + leadership := .leader, + leaderId := some w.nodeId, + allOtherNodes := peers + } + /\ PeerInv (w.allOtherNodes.map Prod.fst) (resetPeer w) (fun _ => True) + peers + /\ Covers (w.allOtherNodes.map Prod.fst) peers + /\ o = o1 ++ hbs env.names w) := by + unfold leaderTail + let u : State := { w with leadership := .leader, leaderId := some w.nodeId } + refine Ae.Hoare.bind (R := fun _ v o => v = u /\ o = o1) + (Ae.Hoare.setV _ fun v o ⟨hv, ho⟩ => ⟨by subst hv; rfl, ho⟩) fun _ => ?_ + keep_step + refine Ae.Hoare.getV_bind fun s => ?_ + dsimp only + refine Ae.Hoare.ite + (fun _ => + Ae.Hoare.bind (Ae.Hoare.pre (updateCommit_noop env (u := u) vlt) fun _ _ p => p.1) + fun _ => ?_) + fun _ => Ae.Hoare.pre ?_ fun _ _ p => p.1 + all_goals + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v2 o2 ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst h1 h2 h3 + exact leaderLoop env nrc vle + +/-- What `becomeLeader` needs of the declared state it starts from. -/ +structure TvPre (d : State) : Prop where + notLeader : d.leadership ≠ .leader + viewsLt : d.views.size < d.currentView + viewsLe : forall x, x ∈ d.views.toList -> x <= d.lastIdx + 1 + commitLe : d.commitIdx <= d.lastCommittable + +/-- The state after the election rollback, which only happens with a positive commit index. -/ +def Rolled (d w : State) : Prop := + if 0 < d.commitIdx then RolledTo d.lastCommittable d w else w = d + +theorem becomeLeader_tv (env : Env) {d : State} {o0 : Outbox} (pre : TvPre d) + : Hoare env (fun v o => v = d /\ o = o0) Exec.becomeLeader + (fun b v o => + (d.isRetiredCommitted = true /\ b = false /\ v = d /\ o = o0) + \/ (d.isRetiredCommitted = false + /\ b = true + /\ exists w peers, + Rolled d w + /\ (0 < d.commitIdx + -> w.allOtherNodes.map (fun x => env.names.id x.1) + = (eligiblePeers (abs env.names w) + (env.names.id w.nodeId)).sort) + /\ v + = { + w with + leadership := .leader, + leaderId := some w.nodeId, + allOtherNodes := peers + } + /\ PeerInv (w.allOtherNodes.map Prod.fst) (resetPeer w) (fun _ => True) + peers + /\ Covers (w.allOtherNodes.map Prod.fst) peers + /\ o = o0 ++ hbs env.names w)) := by + unfold Exec.becomeLeader + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst h1 h2 h3 + refine Ae.Hoare.ite + (fun hr => Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => Or.inl ⟨hr, rfl, hv, ho⟩) fun hr => ?_ + simp only [Bool.not_eq_true] at hr + dsimp only + refine Ae.Hoare.ite (fun hc => ?_) fun hc => ?_ + · refine Ae.Hoare.bind (rollback_spec env pre.notLeader pre.commitLe hr) fun _ => ?_ + refine Ae.Hoare.bind (Ae.Hoare.of_spec Spec.names + (Q := fun a v o => a = env.names /\ o = o1 /\ RolledTo v1.lastCommittable v1 v) + fun v o a v' o' p ⟨ha, hv, ho⟩ => ⟨ha, ho ▸ p.1, hv ▸ p.2⟩) fun nm => ?_ + refine Ae.Hoare.lift fun hn => ?_ + subst hn + refine Ae.Hoare.getV_bind fun w => ?_ + refine Ae.Hoare.pin fun v2 o2 ⟨⟨ho, rt⟩, hw⟩ => ?_ + subst hw ho + have rt' := rt + obtain ⟨cfg, p, rtd, rp, rci, ri, hv2, -, hrc⟩ := rt' + have nrc : v2.isRetiredCommitted = false := by rw [hv2]; exact hrc + have vlt : v2.views.size < v2.currentView := by + rw [hv2]; exact Nat.lt_of_le_of_lt Array.size_filter_le pre.viewsLt + have vle : forall x, x ∈ v2.views.toList -> x <= v2.lastIdx + 1 := by + rw [hv2]; intro x hx; simp only [Array.toList_filter, List.mem_filter, + decide_eq_true_eq] at hx + show x <= v1.lastCommittable + 1 + omega + refine Ae.Hoare.ite (fun hp => ?_) fun _ => + Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) fun _ => + Ae.Hoare.false_pre fun _ _ f => f + refine Ae.Hoare.post (leaderTail_spec env (w := v2) (o1 := o2) nrc vlt vle) + fun b v o ⟨hb, peers, hv, hinv, hcov, ho⟩ => + Or.inr ⟨hr, hb, v2, peers, ?_, fun _ => ?_, hv, hinv, hcov, ho⟩ + · simpa [Rolled, hc] using rt + · simpa using hp + · refine Ae.Hoare.post (leaderTail_spec env (w := v1) (o1 := o1) hr pre.viewsLt pre.viewsLe) + fun b v o ⟨hb, peers, hv, hinv, hcov, ho⟩ => + Or.inr ⟨hr, hb, v1, peers, by simp [Rolled, hc], fun h => absurd h hc, hv, hinv, hcov, ho⟩ + +/-! ## The clean side of the election -/ + +theorem retirement_congr {a b : NodeState} (hl : a.log = b.log) + (hc : a.commitIndex = b.commitIndex) + (hr : a.retiredCommittedIndex = b.retiredCommittedIndex) (n : NodeID) + : a.retirement n = b.retirement n := by + simp only [NodeState.retirement, hl, hc, hr] + +theorem termAt_take_le (l : List Model.Node.Entry) (n i : Nat) + : termAt (l.take n) i <= termAt l i := by + unfold termAt entryAt? + split + · simp + · rw [List.getElem?_take] + split <;> simp + +theorem lastCommittable_bounds {d : State} (h2 : d.commitIdx <= d.lastIdx) + (h3 : d.committable = signaturesIn d d.commitIdx d.lastIdx) + : d.commitIdx <= d.lastCommittable /\ d.lastCommittable <= d.lastIdx := by + unfold State.lastCommittable + cases hl : d.committable.getLast? with + | none => exact ⟨Nat.le_refl _, h2⟩ + | some x => + have hx := List.mem_of_getLast? hl + rw [h3] at hx + simp only [signaturesIn, List.mem_filter, List.mem_range'] at hx + obtain ⟨⟨k, hk, rfl⟩, -⟩ := hx + simp only [Option.getD_some] + omega + +theorem abs_log_rolled {names : Names} {e : Nat} {d w : State} (h : RolledTo e d w) + (he : e <= d.lastIdx) + : (abs names w).log = (abs names d).log.take e := by + obtain ⟨cfg, p, rt, rp, rci, ri, rfl, -, -⟩ := h + simp only [abs, Array.toList_extract, List.extract, List.drop_zero, List.take_take, + List.map_take, Nat.min_eq_left he, Nat.sub_zero, Nat.min_self] + +theorem eligiblePeers_empty {s : NodeState} (hl : s.log = []) (hc : s.commitIndex = 0) + (self : NodeID) + : (eligiblePeers s self).sort = [] := by + unfold eligiblePeers NodeState.activeMembers NodeState.retirementCompletedNodes + NodeState.activeConfigurations NodeState.committedLog + rw [hl, hc] + rfl + +theorem agrees_frame {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.currentTerm = d.currentView + /\ c.log = (abs names d).log + /\ c.commitIndex = d.commitIdx + /\ c.isNewFollower = d.isNewFollower + /\ c.votedFor = d.votedFor.map names.id + /\ c.retiredCommittedIndex = d.retiredCommittedIdx := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨-, h2⟩, h3⟩, h4⟩, -⟩, h6⟩, h7⟩, -⟩, -⟩, -⟩, h11⟩ := h + exact ⟨h2, h3, h4, h6, h7, h11⟩ + +/-- What the clean election needs of the declared state `becomeLeader` starts from. -/ +structure LeaderPre (names : Names) (d : State) : Prop where + notLeader : d.leadership ≠ .leader + /-- No ledger entry is in the current view. -/ + viewsLt : d.views.size < d.currentView + viewsLe : forall x, x ∈ d.views.toList -> x <= d.lastIdx + 1 + size : d.ledger.size = d.lastIdx + commitLe : d.commitIdx <= d.lastIdx + committable : d.committable = signaturesIn d d.commitIdx d.lastIdx + commitSig : d.commitIdx = 0 \/ d.ledger[d.commitIdx - 1]?.any (·.sig) = true + terms + : forall i, + 1 <= i -> i <= d.lastIdx -> d.ledger[i - 1]?.map (·.term) = some (d.viewAt i) + retired + : d.isRetiredCommitted = decide ((abs names d).isRetiredCommitted (names.id d.nodeId)) + /-- The peers are the clean eligible peers (the `peers` conjuncts of `inv`). -/ + peers + : d.lastIdx = 0 + \/ d.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (abs names d) (names.id d.nodeId)).sort + +theorem LeaderPre.tv {names : Names} {d : State} (pre : LeaderPre names d) : TvPre d := + ⟨ + pre.notLeader, + pre.viewsLt, + pre.viewsLe, + (lastCommittable_bounds pre.commitLe pre.committable).1 + ⟩ + +/-- The new leader's state after `becomeLeader`, with the peers it reset. -/ +def leaderState (w : State) (peers : List (NodeId × Peer)) : State := + { w with leadership := .leader, leaderId := some w.nodeId, allOtherNodes := peers } + +/-- What the election rollback keeps. -/ +theorem rolled_frame {d w : State} (rolled : Rolled d w) + : w.nodeId = d.nodeId + /\ w.currentView = d.currentView + /\ w.commitIdx = d.commitIdx + /\ w.isNewFollower = d.isNewFollower + /\ w.votedFor = d.votedFor + /\ w.retiredCommittedIdx = d.retiredCommittedIdx + /\ (forall x, x ∈ w.configurations -> x ∈ d.configurations) := by + unfold Rolled at rolled + split at rolled + · obtain ⟨cfg, p, rt, rp, rci, ri, rfl, sub, -⟩ := rolled + exact ⟨rfl, rfl, rfl, rfl, rfl, rfl, sub⟩ + · subst rolled; exact ⟨rfl, rfl, rfl, rfl, rfl, rfl, fun _ h => h⟩ + +theorem leader_clean {names : Names} {c : NodeState} {d w : State} + {peers : List (NodeId × Peer)} + (pre : LeaderPre names d) (ag : agrees names c d = true) (rolled : Rolled d w) + (chk + : 0 < d.commitIdx + -> w.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (abs names w) (names.id w.nodeId)).sort) + (pinv : PeerInv (w.allOtherNodes.map Prod.fst) (resetPeer w) (fun _ => True) peers) + (cov : Covers (w.allOtherNodes.map Prod.fst) peers) + (hinv : inv names (leaderState w peers) = true) + : Emits + (becomePrimary (CCF.Capabilities.record (names.id d.nodeId)) (names.id d.nodeId) + c) + (primaryState c) (hbs names w) + /\ agrees names (primaryState c) (leaderState w peers) = true + /\ forall e, e ∈ hbs names w -> msgInv names e = true := by + obtain ⟨ht, hl, hcm, hnf, hvf, hrc⟩ := agrees_frame ag + have bounds := lastCommittable_bounds pre.commitLe pre.committable + obtain ⟨wn, wv, wc, wnf, wvf, wrc, -⟩ := rolled_frame rolled + obtain ⟨f1, -, -, -, f5, -, -⟩ := inv_parts hinv + have hlogw : (abs names w).log = (primaryState c).log := by + unfold Rolled at rolled + split at rolled + · rename_i hc + rw [abs_log_rolled rolled bounds.2] + have hlc : lastCommittableIndex c = d.lastCommittable := by + unfold lastCommittableIndex + rw [hl, ← lastCommittable_eq_of pre.size pre.committable pre.commitSig, hcm] + exact Nat.max_eq_right bounds.1 + simp only [primaryState, hcm, hc, ite_true, hlc, hl] + · rename_i hc + subst rolled + simp only [primaryState, hcm, gt_iff_lt, hc, ite_false, hl] + have hlen : (primaryState c).log.length = w.lastIdx := by + rw [← hlogw] + simp only [abs, List.length_map, List.length_take, Array.length_toList] + exact Nat.min_eq_left (Nat.le_of_eq f1.symm) + have htl : termAt (primaryState c).log w.lastIdx = w.getTerm w.lastIdx := by + rw [← hlogw] + exact (getTerm_eq hinv w.lastIdx).symm + have peersEq : w.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (primaryState c) (names.id d.nodeId)).sort := by + rw [eligiblePeers_congr (b := abs names w) hlogw.symm + (by simp only [primaryState, abs, hcm, wc])] + by_cases hc : 0 < d.commitIdx + · rw [← wn]; exact chk hc + · have hw : w = d := by simpa [Rolled, hc] using rolled + subst hw + rcases pre.peers with h0 | h + · have hemp : peers = [] := by + have e := hinv + have : (w.lastIdx != 0 || (Leadership.leader != .leader) || peers.isEmpty) = true := by + inv_conj e "empty_leader_alone" + simpa [h0] using this + have hw0 : w.allOtherNodes = [] := by + cases hw : w.allOtherNodes with + | nil => rfl + | cons x xs => + obtain ⟨q, hq⟩ := cov x.1 (by simp [hw]) + simp [hemp] at hq + rw [hw0, eligiblePeers_empty (by simp [abs, h0]) (by simp only [abs]; omega)] + rfl + · exact h + have noTerm : forall i, termAt (primaryState c).log i ≠ (primaryState c).currentTerm := by + intro i + have h1 : termAt (primaryState c).log i <= termAt c.log i := by + simp only [primaryState] + split + · exact termAt_take_le _ _ _ + · exact Nat.le_refl _ + have h2 : termAt c.log i < c.currentTerm := by + rw [hl, termAt_abs pre.size, ht] + have vl := pre.viewsLt + split + · omega + · by_cases hi : i <= d.lastIdx + · rw [pre.terms i (by omega) hi] + have := ReplUpdateCommit.viewAt_le_size d i + simp only [Option.getD_some] + omega + · have hn : d.ledger[i - 1]? = none := by + simp only [Array.getElem?_eq_none_iff, pre.size]; omega + simp only [hn, Option.map_none, Option.getD_none] + omega + have : (primaryState c).currentTerm = c.currentTerm := rfl + omega + refine ⟨emits_congr (emits_becomePrimary _ c noTerm) rfl ?_, ?_, ?_⟩ + · rw [← peersEq] + simp only [hbs, List.map_map] + apply List.map_congr_left + intro x _ + simp only [Function.comp, heartbeat, hbMsg, hlen, htl, wn] + simp only [primaryState, ht, wv, hcm, wc] + · simp only [agrees, Bool.and_eq_true, beq_iff_eq] + refine ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨rfl, ?_⟩, hlogw.symm⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩, rfl⟩, rfl⟩, rfl⟩, ?_⟩ + · show c.currentTerm = w.currentView + rw [ht, wv] + · show c.commitIndex = w.commitIdx + rw [hcm, wc] + · rw [List.all_eq_true] + intro n hn + simp only [trackedPeers, leaderState, BEq.rfl, ite_true, List.mem_map] at hn + obtain ⟨x, hx, rfl⟩ := hn + simp only [abs, leaderState, Bool.and_eq_true, beq_iff_eq] + split + · rename_i y q hf + have hy := List.mem_of_find?_eq_some hf + have hq := (pinv _ hy).2 trivial + simp only at hq + subst hq + exact ⟨hlen, rfl⟩ + · rename_i hf + have := List.find?_eq_none.mp hf x hx + simp at this + · show c.isNewFollower = w.isNewFollower + rw [hnf, wnf] + · show c.votedFor = w.votedFor.map names.id + rw [hvf, wvf] + · show c.retiredCommittedIndex = w.retiredCommittedIdx + rw [hrc, wrc] + · intro e he + simp only [hbs, List.mem_map] at he + obtain ⟨x, hx, rfl⟩ := he + have sn : (names.name (names.id w.nodeId) == w.nodeId) = true := by + have e := hinv + inv_conj e "self_named" + have pt : (leaderState w peers).ledger.all (0 < ·.term) = true := by + have e := hinv + inv_conj e "positive_terms" + have hm : names.id x.1 ∈ (eligiblePeers (primaryState c) (names.id d.nodeId)).sort := by + rw [← peersEq]; exact List.mem_map_of_mem hx + simp only [eligiblePeers, CCF.Finset.erase, CCF.Finset.filter, CCF.Finset.sort, + List.mem_filter, decide_eq_true_eq] at hm + have hpos : w.lastIdx = 0 \/ 0 < w.getTerm w.lastIdx := by + by_cases h0 : w.lastIdx = 0 + · exact Or.inl h0 + · right + have := f5 w.lastIdx (by omega) (Nat.le_refl _) + change Option.map (·.term) w.ledger[w.lastIdx - 1]? = some (w.viewAt w.lastIdx) at this + simp only [leaderState] at pt + cases hg : w.ledger[w.lastIdx - 1]? with + | none => simp [hg] at this + | some en => + simp only [hg, Option.map_some, Option.some.injEq] at this + have hp := (Array.all_eq_true_iff_forall_mem.mp pt) en (Array.mem_of_getElem? hg) + simp only [decide_eq_true_eq] at hp + simp only [State.getTerm, gt_iff_lt, Nat.lt_irrefl, ite_false] + omega + simp only [beq_iff_eq] at sn + have hne : names.id w.nodeId ≠ names.id x.1 := by rw [wn]; exact fun h => hm.2 h.symm + simp only [msgInv, hbMsg, List.all_nil, Bool.and_true, sn] + rcases hpos with h | h <;> simp [h, hne] + +theorem unmatched_primaryState (node : NodeID) (c : NodeState) + : UnnamedUnmatched node (primaryState c) := + fun _ _ _ _ => rfl + +/-- +`becomeLeader` from a declared state `d` that `c` agrees with: it stops at once if and only +if `c` is retired-committed; otherwise it ends as a leader that, if it satisfies `inv`, the +clean `primaryState c` agrees with, having sent exactly what the clean `becomePrimary` sends. +-/ +theorem becomeLeader_spec (env : Env) {c : NodeState} {d : State} {o0 : Outbox} + (pre : LeaderPre env.names d) (ag : agrees env.names c d = true) + : Hoare env (fun v o => v = d /\ o = o0) Exec.becomeLeader + (fun b v o => + (c.isRetiredCommitted (env.names.id d.nodeId) /\ b = false /\ v = d /\ o = o0) + \/ (Not (c.isRetiredCommitted (env.names.id d.nodeId)) + /\ b = true + /\ exists sends, + o = o0 ++ sends + /\ v.nodeId = d.nodeId + /\ v.currentView = d.currentView + /\ v.leadership = .leader + /\ (forall x, x ∈ v.configurations -> x ∈ d.configurations) + /\ (inv env.names v = true + -> Emits + (becomePrimary + (CCF.Capabilities.record (env.names.id d.nodeId)) + (env.names.id d.nodeId) c) + (primaryState c) sends + /\ agrees env.names (primaryState c) v = true + /\ forall e, e ∈ sends -> msgInv env.names e = true))) := by + obtain ⟨-, hl, hcm, -, -, hrc⟩ := agrees_frame ag + have hret : d.isRetiredCommitted = decide (c.isRetiredCommitted (env.names.id d.nodeId)) := by + have := retirement_congr (b := abs env.names d) hl hcm hrc (env.names.id d.nodeId) + rw [pre.retired] + simp only [NodeState.isRetiredCommitted, this] + refine Ae.Hoare.post (becomeLeader_tv env pre.tv) fun b v o h => ?_ + rcases h with ⟨hr, hb, hv, ho⟩ | ⟨hr, hb, w, peers, rolled, chk, hv, pinv, cov, ho⟩ + · exact Or.inl ⟨of_decide_eq_true (hret ▸ hr), hb, hv, ho⟩ + · obtain ⟨wn, wv, -, -, -, -, sub⟩ := rolled_frame rolled + refine Or.inr ⟨fun h => ?_, hb, hbs env.names w, ho, ?_, ?_, ?_, ?_, fun hinv => ?_⟩ + · rw [hret] at hr; simp [h] at hr + all_goals subst hv + · exact wn + · exact wv + · rfl + · exact sub + · exact leader_clean pre ag rolled chk pinv cov hinv + +end Consensus.TraceValidation.Proofs.Vote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteCandidate.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteCandidate.lean new file mode 100644 index 000000000000..296b4523ba6a --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteCandidate.lean @@ -0,0 +1,651 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteTally + +@[expose] public section + +/-! +# `become_candidate` against the clean `becomeCandidate` (not reviewed) + +M_tv's `becomeCandidate` resets the vote records, increments the view, records the self-vote +and, if that alone is a quorum, calls `becomeLeader`; it then asks every other member of the +active configurations for a vote, in string order. The clean `becomeCandidate` grants itself +the vote, elects itself on a quorum, and broadcasts to the other active members in id +order. The orders agree because every member is in the strictly sorted name table +(`inv`'s `members_known` and `names_sorted`), where `names.id` is the position +(`others_eq`). +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae (Hoare) +open Consensus.TraceValidation (Names) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (Named named_inj absConfig) + +/-! ## The name table orders ids as their names -/ + +theorem pairwise_of_adjacent + : forall {l : List String}, + (l.zip l.tail).all (fun (x, y) => decide (x < y)) = true -> l.Pairwise (· < ·) + | [], _ => List.Pairwise.nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: rest, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true, + decide_eq_true_eq] at h + have tail := pairwise_of_adjacent (l := b :: rest) (by simpa using h.2) + refine List.Pairwise.cons (fun z mz => ?_) tail + rcases List.mem_cons.mp mz with rfl | mz + · exact h.1 + · exact String.lt_trans h.1 (List.rel_of_pairwise_cons tail mz) + +theorem id_known {names : Names} {x : NodeId} (m : x ∈ names.known) + : exists h : names.id x < names.known.size, names.known[names.id x] = x := by + have hs : (names.known.findIdx? (· == x)).isSome = true := by + rw [Array.findIdx?_isSome, Array.any_eq_true] + obtain ⟨i, hi, e⟩ := Array.mem_iff_getElem.mp m + exact ⟨i, hi, by simp [e]⟩ + obtain ⟨i, hi⟩ := Option.isSome_iff_exists.mp hs + obtain ⟨h, e, -⟩ := Array.findIdx?_eq_some_iff_getElem.mp hi + have hid : names.id x = i := by simp [Names.id, hi] + subst hid + exact ⟨h, by simpa using e⟩ + +theorem named_of_known {names : Names} {x : NodeId} (m : x ∈ names.known) + : Named names x := by + obtain ⟨h, e⟩ := id_known m + show names.name (names.id x) = x + simp only [Names.name, Array.getElem?_eq_getElem h, e, Option.getD_some] + +theorem id_lt {names : Names} (sorted : names.known.toList.Pairwise (· < ·)) + {x y : NodeId} (mx : x ∈ names.known) (my : y ∈ names.known) (lt : x < y) + : names.id x < names.id y := by + obtain ⟨hx, ex⟩ := id_known mx + obtain ⟨hy, ey⟩ := id_known my + rcases Nat.lt_trichotomy (names.id x) (names.id y) with h | h | h + · exact h + · have : x = y := by rw [← ex, ← ey]; simp only [h] + subst this + exact absurd lt (String.lt_irrefl _) + · have := List.pairwise_iff_getElem.mp sorted (names.id y) (names.id x) + (by simpa using hy) (by simpa using hx) h + simp only [Array.getElem_toList, ex, ey] at this + exact absurd lt (String.lt_asymm this) + +theorem pairwise_eraseDups {α : Type} [BEq α] [LawfulBEq α] {R : α -> α -> Prop} + : forall (n : Nat) (l : List α), + l.length <= n -> l.Pairwise R -> l.eraseDups.Pairwise fun a b => R a b /\ a ≠ b + | _, [], _, _ => by simp [List.eraseDups] + | 0, _ :: _, hl, _ => by simp at hl + | n + 1, a :: as, hl, h => by + rw [List.eraseDups_cons] + have hp := List.pairwise_cons.mp h + refine List.Pairwise.cons (fun b mb => ?_) + (pairwise_eraseDups n _ ?_ (hp.2.filter _)) + · rw [List.mem_eraseDups, List.mem_filter] at mb + refine ⟨hp.1 b mb.1, fun e => ?_⟩ + subst e + simp at mb + · have := List.length_filter_le (fun b => !b == a) as + simp only [List.length_cons] at hl + omega + +/-- The other members of the active configurations, as M_tv lists them. -/ +theorem mem_others {v : State} {x : NodeId} + : x ∈ v.otherNodesInActiveConfigs + <-> (exists c, c ∈ v.configurations /\ x ∈ c.nodes.map Prod.fst) + /\ x ≠ v.nodeId := by + unfold State.otherNodesInActiveConfigs + rw [List.mem_eraseDups, (List.mergeSort_perm _ _).mem_iff, List.mem_filter, List.mem_flatMap] + simp + +theorem others_sorted {names : Names} {v : State} + (sorted : names.known.toList.Pairwise (· < ·)) + (known : forall c, c ∈ v.configurations -> forall a, a ∈ c.nodes -> a.1 ∈ names.known) + : (v.otherNodesInActiveConfigs.map names.id).Pairwise (· < ·) := by + have sortedS := List.pairwise_mergeSort (le := fun a b : String => decide (a <= b)) + (fun a b c hab hbc => by simp only [decide_eq_true_eq] at *; exact String.le_trans hab hbc) + (fun a b => by simpa using String.le_total a b) + ((v.configurations.flatMap (·.nodes.map Prod.fst)).filter (· != v.nodeId)) + have strict := pairwise_eraseDups _ _ (Nat.le_refl _) sortedS + have isKnown : forall x, x ∈ v.otherNodesInActiveConfigs -> x ∈ names.known := by + intro x mx + obtain ⟨⟨c, mc, mx⟩, -⟩ := mem_others.mp mx + obtain ⟨a, ma, rfl⟩ := List.mem_map.mp mx + exact known c mc a ma + rw [List.pairwise_map] + refine strict.imp_of_mem + fun {a b} ma mb ⟨le, ne⟩ => id_lt sorted (isKnown a ma) (isKnown b mb) ?_ + simp only [decide_eq_true_eq] at le + refine Classical.byContradiction fun nlt => ne ?_ + exact String.le_antisymm le (String.not_lt.mp nlt) + +theorem mem_members {cs : List Configuration} {n : NodeID} + : n ∈ configurationMembers cs <-> exists c, c ∈ cs /\ n ∈ c.nodes := by + unfold configurationMembers + suffices h : forall (acc : CCF.Finset NodeID), + n ∈ cs.foldl (fun nodes configuration => nodes ∪ configuration.nodes) acc + <-> n ∈ acc \/ exists c, c ∈ cs /\ n ∈ c.nodes by + rw [h] + simp [CCF.Finset.notMem_empty] + induction cs with + | nil => simp + | cons head tail ih => + intro acc + simp only [List.foldl_cons, ih, CCF.Finset.mem_union, List.mem_cons] + constructor + · rintro ((old | new) | ⟨c, member, present⟩) + · exact Or.inl old + · exact Or.inr ⟨head, Or.inl rfl, new⟩ + · exact Or.inr ⟨c, Or.inr member, present⟩ + · rintro (old | ⟨c, rfl | member, present⟩) + · exact Or.inl (Or.inl old) + · exact Or.inl (Or.inr present) + · exact Or.inr ⟨c, member, present⟩ + +/-- M_tv's vote targets are the clean broadcast's, in the same order. -/ +theorem others_eq {names : Names} {v : State} {D : List Config} + (sorted : names.known.toList.Pairwise (· < ·)) + (known : forall c, c ∈ v.configurations -> forall a, a ∈ c.nodes -> a.1 ∈ names.known) + (selfNamed : Named names v.nodeId) + (nodesEq : D.map (·.nodes) = v.configurations.map (·.nodes)) + : v.otherNodesInActiveConfigs.map names.id + = ((configurationMembers (D.map (absConfig names))).erase + (names.id v.nodeId)).sort := by + refine CCF.Finset.eq_of_sorted_of_mem_iff (others_sorted sorted known) + (CCF.Finset.sorted _) fun n => ?_ + have members : forall ns, ns ∈ D.map (·.nodes) <-> ns ∈ v.configurations.map (·.nodes) := by + rw [nodesEq]; exact fun _ => Iff.rfl + rw [CCF.Finset.mem_sort, CCF.Finset.mem_erase, mem_members, List.mem_map] + constructor + · rintro ⟨y, my, rfl⟩ + obtain ⟨⟨c, mc, myc⟩, ne⟩ := mem_others.mp my + obtain ⟨c', mc', nodes⟩ := List.mem_map.mp ((members c.nodes).mpr (List.mem_map_of_mem mc)) + obtain ⟨a, ma, rfl⟩ := List.mem_map.mp myc + refine ⟨fun e => ne (named_inj (known c mc a ma |> named_of_known) selfNamed e), ?_⟩ + refine ⟨absConfig names c', List.mem_map_of_mem mc', ?_⟩ + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, nodes] + exact List.mem_map_of_mem (List.mem_map_of_mem ma) + · rintro ⟨ne, _, mx, hn⟩ + obtain ⟨c', mc', rfl⟩ := List.mem_map.mp mx + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, List.mem_map] at hn + obtain ⟨y, ⟨a, ma, rfl⟩, rfl⟩ := hn + obtain ⟨c, mc, nodes⟩ := + List.mem_map.mp ((members c'.nodes).mp (List.mem_map_of_mem mc')) + refine ⟨a.1, mem_others.mpr ⟨⟨c, mc, ?_⟩, fun e => ne (by rw [e])⟩, rfl⟩ + rw [nodes] + exact List.mem_map_of_mem ma + +/-! ## The self-vote -/ + +theorem tally_reset + : forall cs : List Config, + Tally cs (cs.map fun c => (c.idx, [], State.quorum c.nodes.length)) [] + | [] => ⟨rfl, fun _ _ mem => by simp at mem⟩ + | c :: cs => by + obtain ⟨len, all⟩ := tally_reset cs + refine ⟨by simp [len], fun r x mem => ?_⟩ + simp only [List.map_cons, List.zip_cons_cons, List.mem_cons, Prod.mk.injEq] at mem + rcases mem with ⟨rfl, rfl⟩ | mem + · simp + · exact all r x mem + +/-- A configuration in which the self-vote alone is a quorum has only the node itself. -/ +theorem alone_of_quorum {cs : List Config} {votes : List VoteRec} {self : NodeId} + (t : Tally cs votes [self]) + (q : (votes.all fun r => decide (r.2.1.length >= r.2.2)) = true) + : forall c, c ∈ cs -> forall x, x ∈ c.nodes.map Prod.fst -> x = self := by + intro c mc x mx + obtain ⟨r, mem⟩ := exists_zip_right t.1 c mc + obtain ⟨-, hq, nd, hm⟩ := t.2 r c mem + have big := List.all_eq_true.mp q r (List.of_mem_zip mem).1 + simp only [decide_eq_true_eq, hq, State.quorum] at big + have small : r.2.1.length <= 1 := + nd.length_le_of_subset (l₂ := [self]) fun y my => ((hm y).mp my).2 + obtain ⟨w, mw⟩ := List.exists_mem_of_length_pos (l := r.2.1) (by omega) + have ws := (hm w).mp mw + have len : (c.nodes.map Prod.fst).length <= 1 := by simp only [List.length_map]; omega + have hw : w = self := List.mem_singleton.mp ws.2 + subst hw + match h : c.nodes.map Prod.fst, len, mx, ws.1 with + | [], _, mx, _ => simp at mx + | [u], _, mx, mw => rw [List.mem_singleton.mp mx, List.mem_singleton.mp mw] + +theorem others_nil {v : State} + (alone + : forall c, + c ∈ v.configurations -> forall x, x ∈ c.nodes.map Prod.fst -> x = v.nodeId) + : v.otherNodesInActiveConfigs = [] := by + refine List.eq_nil_iff_forall_not_mem.mpr fun x mx => ?_ + obtain ⟨⟨c, mc, mx⟩, ne⟩ := mem_others.mp mx + exact ne (alone c mc x mx) + +theorem hoare_discard {env : Env} {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : Unit -> State -> Outbox -> Prop} (h : Hoare env P x fun _ => Q ()) + : Hoare env P (Functor.discard x) Q := by + have : Hoare env P ((fun _ => PUnit.unit) <$> x) Q := by + rw [map_eq_pure_bind] + exact Ae.Hoare.bind h fun _ => Ae.Hoare.pure _ fun _ _ p => p + exact this + +theorem hoare_discard_ex {env : Env} {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} (h : Hoare env P x Q) + : Hoare env P (Functor.discard x) fun _ v o => exists a, Q a v o := + hoare_discard (Ae.Hoare.post h fun a _ _ p => ⟨a, p⟩) + +/-- The vote request a candidate in state `w` sends. -/ +def rvMsg (w : State) : Message := + .requestVoteRequest + { + term := w.currentView, + lastCommittableTerm := w.getTerm w.lastCommittable, + lastCommittableIndex := w.lastCommittable + } + +theorem sendVotes_spec (env : Env) {w : State} {o1 : Outbox} (ids : List NodeId) + : Hoare env (fun v o => v = w /\ o = o1) + (forIn ids PUnit.unit + fun id _ => do + Exec.sendRequestVote false id + pure (ForInStep.yield PUnit.unit)) + (fun _ v o => + v = w + /\ o + = o1 + ++ ids.map + fun id => + CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) + (rvMsg w)) := by + let f : NodeId -> CCF.Envelope NodeID Message := + fun id => CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) (rvMsg w) + refine Ae.Hoare.pre + (Ae.Hoare.forIn_list _ _ _ (fun pre _ v o => v = w /\ o = o1 ++ pre.map f) + (fun _ v o => v = w /\ o = o1 ++ ids.map f) ?_ fun _ _ _ p => p) + fun v o ⟨hv, ho⟩ => ⟨hv, by simp [ho]⟩ + intro pre id rest _ _ + refine Ae.Hoare.pin fun v4 o4 ⟨hv, ho⟩ => ?_ + subst v4 o4 + refine Ae.Hoare.bind (R := fun _ v o => v = w /\ o = o1 ++ (pre ++ [id]).map f) ?_ + fun _ => Ae.Hoare.pure _ fun _ _ p => p + unfold Exec.sendRequestVote + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v2 o2 ⟨⟨h1, h2⟩, h3⟩ => ?_ + subst v2 o2 s + dsimp only + split + · keep_step + exact Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) + fun _ => Ae.Hoare.false_pre fun _ _ h => h + · keep_step + keep_step + keep_step + exact Ae.Hoare.send _ _ fun v o ⟨hv, ho⟩ => ⟨hv, by subst hv ho; simp [f, rvMsg]⟩ + +/-! ## The candidate states -/ + +/-- The declared state after `becomeCandidate`'s reset and view increment. -/ +def candState (d : State) : State := + { + d with + leadership := .candidate, + leaderId := none, + votedFor := some d.nodeId, + votesForMe := + d.configurations.map fun c => (c.idx, [], State.quorum c.nodes.length), + currentView := d.currentView + 1 + } + +/-- The declared state after the self-vote. -/ +def candVoted (d : State) : State := + { candState d with votesForMe := recorded d.nodeId (candState d) } + +/-- The clean candidate before `electIfQuorum`. -/ +def cleanCand (self : NodeID) (c : NodeState) : NodeState := + { + c with + role := .candidate + currentTerm := c.currentTerm + 1 + votedFor := some self + primaryKnown := false + votesGranted := {self} + preVotesGranted := ∅ + } + +theorem emits_becomeCandidate {self : NodeID} {c s : NodeState} + {first : List (CCF.Envelope NodeID Message)} + (h + : Emits (electIfQuorum (CCF.Capabilities.record self) self (cleanCand self c)) s + first) + : Emits (Model.Node.becomeCandidate (CCF.Capabilities.record self) c self) s + (first + ++ (((cleanCand self c).activeMembers.erase self).sort.map + fun p => + ⟨ + self, + p, + .requestVoteRequest (makeRequestVoteRequest (cleanCand self c)) + ⟩)) := by + unfold Model.Node.becomeCandidate broadcastToOthers + refine emits_congr (emits_bind h (emits_bind (emits_bind (emits_forIn _ _) (emits_pure _)) + (emits_pure _))) rfl ?_ + simp only [List.append_nil] + rfl + +/-- A node with a ledger has exactly the clean eligible peers (`inv`'s `peers` conjuncts). -/ +theorem peers_of_inv {names : Names} {d : State} (h : inv names d = true) + (L0 : 0 < d.lastIdx) + : d.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (abs names d) (names.id d.nodeId)).sort := by + have p1 : (d.lastIdx == 0 || d.leadership == .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names d) (names.id d.nodeId)).sort) = true := by + inv_conj h "peers" + have p2 : (d.lastIdx == 0 || d.leadership != .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names d) (names.id d.nodeId)).sort) = true := by + inv_conj h "peers_without_role" + have L0' : d.lastIdx ≠ 0 := by omega + simp only [Bool.or_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, L0', false_or] at p1 p2 + by_cases r : d.leadership = .none + · simpa [r] using p2 + · simpa [r] using p1 + +theorem leaderPre_cand {names : Names} {e : State} (h : inv names e = true) + (L0 : 0 < e.lastIdx) + : LeaderPre names (candVoted e) := by + obtain ⟨s1, s2, s3, s4, s5, s6, -⟩ := inv_parts h + have vle : e.views.all (· <= e.lastIdx + 1) = true := by inv_conj h "views_le_last" + have ret : e.isRetiredCommitted + = decide ((abs names e).isRetiredCommitted (names.id e.nodeId)) := by + have hc : (e.isRetiredCommitted + == decide ((abs names e).isRetiredCommitted (names.id e.nodeId))) = true := by + inv_conj h "retired_committed" + simpa using hc + refine ⟨ + by simp [candVoted, candState], + by simp only [candVoted, candState]; omega, + fun x hx => ?_, + s1, + s2, + s3, + s4, + s5, + ret, + Or.inr ?_ + ⟩ + · have := Array.all_eq_true_iff_forall_mem.mp vle x (by simpa [candVoted, candState] using hx) + simpa [candVoted, candState] using this + · rw [eligiblePeers_congr (a := abs names (candVoted e)) (b := abs names e) rfl rfl] + exact peers_of_inv (d := e) h L0 + +/-- The name table is strictly sorted once the node knows a configuration. -/ +theorem known_sorted {names : Names} {d : State} (h : inv names d = true) + (ne : d.configurations ≠ []) + : names.known.toList.Pairwise (· < ·) := by + have hc : ((d.configurations.isEmpty && d.allOtherNodes.isEmpty) + || (names.known.toList.zip names.known.toList.tail).all fun (x, y) => decide (x < y)) + = true := by + inv_conj h "names_sorted" + have : d.configurations.isEmpty = false := by simpa using ne + rw [this, Bool.false_and, Bool.false_or] at hc + exact pairwise_of_adjacent hc + +theorem members_known {names : Names} {d : State} (h : inv names d = true) + : forall c, c ∈ d.configurations -> forall a, a ∈ c.nodes -> a.1 ∈ names.known := by + have hc : (d.configurations.flatMap (·.nodes.map Prod.fst)).all names.known.contains = true := by + inv_conj h "members_known" + intro c mc a ma + have := List.all_eq_true.mp hc a.1 + (List.mem_flatMap.mpr ⟨c, mc, List.mem_map_of_mem ma⟩) + simpa using this + +theorem set_single {names : Names} (x : NodeId) : names.set [x] = {names.id x} := + CCF.Finset.ext fun a => by simp [Names.set, CCF.Finset.mem_singleton] + +/-- The vote-request broadcast that ends `becomeCandidate`. -/ +theorem votesTail (env : Env) {w : State} {o1 : Outbox} + {Q : Unit -> State -> Outbox -> Prop} + (q + : Q () w + (o1 + ++ w.otherNodesInActiveConfigs.map + fun id => + CCF.Envelope.mk (env.names.id w.nodeId) (env.names.id id) (rvMsg w))) + : Hoare env (fun v o => v = w /\ o = o1) + (do + let l ← Exec.getV + forIn l.otherNodesInActiveConfigs PUnit.unit + fun id _ => do + Exec.sendRequestVote false id + pure (ForInStep.yield PUnit.unit) + pure ()) Q := by + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o2 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o2 + refine Ae.Hoare.bind (sendVotes_spec env _) fun _ => Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + exact q + +/-- +`becomeCandidate` from a node `e` with a ledger and an active configuration, whatever its vote +records: it ends as the clean `becomeCandidate` from any clean state with `e`'s term, log, commit +index, follower flag and retirement latch, having sent the same messages. +-/ +theorem becomeCandidate_spec (env : Env) {c : NodeState} {e : State} {X : List VoteRec} + {o0 : Outbox} (h : inv env.names e = true) (L0 : 0 < e.lastIdx) + (ne : e.configurations ≠ []) + (ht : c.currentTerm = e.currentView) (hl : c.log = (abs env.names e).log) + (hc : c.commitIndex = e.commitIdx) (hnf : c.isNewFollower = e.isNewFollower) + (hrc : c.retiredCommittedIndex = e.retiredCommittedIdx) + (unmatched : UnnamedUnmatched (env.names.id e.nodeId) c) + : Hoare env (fun v o => v = { e with votesForMe := X } /\ o = o0) Exec.becomeCandidate + (fun _ v o => + exists sends, + o = o0 ++ sends + /\ v.nodeId = e.nodeId + /\ (inv env.names v = true + -> exists c', + Emits + (Model.Node.becomeCandidate + (CCF.Capabilities.record (env.names.id e.nodeId)) c + (env.names.id e.nodeId)) + c' sends + /\ agrees env.names c' v = true + /\ UnnamedUnmatched (env.names.id e.nodeId) c' + /\ forall m, m ∈ sends -> msgInv env.names m = true)) := by + have hy := ReplUpdateCommit.Hyps.ofInv h + obtain ⟨D, hD, sh⟩ := hy.configs L0 + have sorted := hy.sorted L0 + have t3 : Tally e.configurations (recorded e.nodeId (candState e)) [e.nodeId] := + tally_record e.nodeId (tally_reset e.configurations) sorted + have quorum : (!e.configurations.isEmpty + && (recorded e.nodeId (candState e)).all fun r => decide (r.2.1.length >= r.2.2)) + = decide (hasQuorum (D.map (absConfig env.names)) {env.names.id e.nodeId}) := by + rw [← set_single] + exact quorum_tally t3 hy.membersNamed + (fun w mw => by rw [List.mem_singleton.mp mw]; exact hy.selfNamed) hy.distinct + (shifted_nodes sh) + have votes : (abs env.names (candVoted e)).votesGranted = {env.names.id e.nodeId} := by + rw [← set_single] + show env.names.set (voters (candVoted e)) = _ + apply set_congr + intro x + have := mem_flat_tally (x := x) t3 + simp only [voters, candVoted, candState, List.mem_cons, List.not_mem_nil, or_false] + at this ⊢ + rw [this] + constructor + · rintro (e | ⟨e, -⟩) <;> exact e + · exact Or.inl + have active : (cleanCand (env.names.id e.nodeId) c).activeConfigurations + = D.map (absConfig env.names) := by + show activeConfigurations c.log c.commitIndex = _ + rw [hl, hc] + exact hD + have ag3 : agrees env.names (cleanCand (env.names.id e.nodeId) c) (candVoted e) = true := by + have tp : trackedPeers env.names (candVoted e) = [] := by + simp [trackedPeers, candVoted, candState] + have e2 : (abs env.names (candVoted e)).currentTerm = c.currentTerm + 1 := by + show e.currentView + 1 = _ + rw [ht] + have e3 : (abs env.names (candVoted e)).log = c.log := hl.symm + have e4 : (abs env.names (candVoted e)).commitIndex = c.commitIndex := hc.symm + have e6 : (abs env.names (candVoted e)).isNewFollower = c.isNewFollower := hnf.symm + have e11 : (abs env.names (candVoted e)).retiredCommittedIndex = c.retiredCommittedIndex := + hrc.symm + simp only [agrees, tp, List.all_nil, e2, e3, e4, e6, e11, votes] + simp [cleanCand, abs, absRole, candVoted, candState] + obtain ⟨-, s2, s3, -⟩ := inv_parts h + have bounds := lastCommittable_bounds s2 s3 + have lci : lastCommittableIndex (cleanCand (env.names.id e.nodeId) c) = e.lastCommittable := by + show max c.commitIndex (maxCommittableIndex c.log) = _ + rw [hc, hl, ← lastCommittable_eq h] + exact Nat.max_eq_right bounds.1 + have msg : rvMsg (candVoted e) + = .requestVoteRequest (makeRequestVoteRequest (cleanCand (env.names.id e.nodeId) c)) := by + simp only [rvMsg, makeRequestVoteRequest, lastCommittableTerm, lci] + show Message.requestVoteRequest + { term := e.currentView + 1, lastCommittableTerm := e.getTerm e.lastCommittable, + lastCommittableIndex := e.lastCommittable } = _ + rw [getTerm_eq h] + simp only [cleanCand, ht, hl] + have bcast : (candVoted e).otherNodesInActiveConfigs.map env.names.id + = ((cleanCand (env.names.id e.nodeId) c).activeMembers.erase (env.names.id e.nodeId)).sort := by + rw [others_eq (v := candVoted e) (known_sorted h ne) (members_known (d := e) h) hy.selfNamed + (shifted_nodes sh)] + show _ = ((configurationMembers (cleanCand _ c).activeConfigurations).erase _).sort + rw [active] + rfl + have rvInv : forall id, id ∈ (candVoted e).otherNodesInActiveConfigs + -> msgInv env.names + ⟨env.names.id e.nodeId, env.names.id id, rvMsg (candVoted e)⟩ = true := by + intro id mid + obtain ⟨⟨x, mx, ma⟩, ne'⟩ := mem_others.mp mid + obtain ⟨a, ma2, rfl⟩ := List.mem_map.mp ma + have named := named_of_known (members_known h x mx a ma2) + have neq : env.names.id e.nodeId ≠ env.names.id a.1 := + fun same => ne' (named_inj hy.selfNamed named same).symm + have self := hy.selfNamed + simp only [Named] at self + simp [msgInv, rvMsg, self, neq] + have um3 : UnnamedUnmatched (env.names.id e.nodeId) (cleanCand (env.names.id e.nodeId) c) := + unmatched_frame unmatched fun hp => absurd hp (by simp [cleanCand]) + have sendsEq : ((cleanCand (env.names.id e.nodeId) c).activeMembers.erase + (env.names.id e.nodeId)).sort.map (fun p => + (⟨env.names.id e.nodeId, p, .requestVoteRequest + (makeRequestVoteRequest (cleanCand (env.names.id e.nodeId) c))⟩ + : CCF.Envelope NodeID Message)) + = (candVoted e).otherNodesInActiveConfigs.map fun id => + CCF.Envelope.mk (env.names.id (candVoted e).nodeId) (env.names.id id) (rvMsg (candVoted e)) := by + rw [← bcast, List.map_map, msg] + rfl + have stay : Not ((cleanCand (env.names.id e.nodeId) c).role = .candidate + /\ hasQuorum (cleanCand (env.names.id e.nodeId) c).activeConfigurations + (cleanCand (env.names.id e.nodeId) c).votesGranted + /\ Not ((cleanCand (env.names.id e.nodeId) c).isRetiredCommitted (env.names.id e.nodeId))) + -> Emits (Model.Node.becomeCandidate (CCF.Capabilities.record (env.names.id e.nodeId)) c + (env.names.id e.nodeId)) (cleanCand (env.names.id e.nodeId) c) + ((candVoted e).otherNodesInActiveConfigs.map fun id => + CCF.Envelope.mk (env.names.id (candVoted e).nodeId) (env.names.id id) + (rvMsg (candVoted e))) := by + intro no + have := emits_becomeCandidate (first := []) + (show Emits (electIfQuorum (CCF.Capabilities.record (env.names.id e.nodeId)) + (env.names.id e.nodeId) (cleanCand (env.names.id e.nodeId) c)) + (cleanCand (env.names.id e.nodeId) c) [] by + unfold electIfQuorum + simp only [no, ↓reduceIte] + exact emits_pure _) + rw [List.nil_append, sendsEq] at this + exact this + unfold Exec.becomeCandidate + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + refine Ae.Hoare.ite (fun he => absurd (List.isEmpty_iff.mp he) ne) fun _ => ?_ + refine Ae.Hoare.bind + (Ae.Hoare.setV _ + (Q := + fun _ v o => + v + = { + e with + votesForMe := X + leadership := .candidate + leaderId := none + votedFor := some e.nodeId + } + /\ o = o0) fun v o ⟨hv, ho⟩ => ⟨by subst hv; rfl, ho⟩) + fun _ => ?_ + refine Ae.Hoare.bind + (Ae.Hoare.setV _ + (Q := fun _ v o => v = { candState e with currentView := e.currentView } /\ o = o0) + fun v o ⟨hv, ho⟩ => ⟨by subst hv; rfl, ho⟩) + fun _ => ?_ + refine Ae.Hoare.bind + (Ae.Hoare.setV _ (Q := fun _ v o => v = candState e /\ o = o0) + fun v o ⟨hv, ho⟩ => ⟨by subst hv; rfl, ho⟩) + fun _ => ?_ + keep_step + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + refine Ae.Hoare.bind (recordVote_spec env (candState e).nodeId (candState e) o0) + fun b => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨hb, hv, ho⟩ => ?_ + subst v1 o1 b + dsimp only + refine Ae.Hoare.ite (fun hq => ?_) fun hq => ?_ + · have qd : decide (hasQuorum (D.map (absConfig env.names)) {env.names.id e.nodeId}) = true := by + rw [← quorum]; exact hq + have q2 : ((recorded e.nodeId (candState e)).all fun r => decide (r.2.1.length >= r.2.2)) + = true := ((Bool.and_eq_true _ _).mp hq).2 + have alone := alone_of_quorum t3 q2 + have none3 : (candVoted e).otherNodesInActiveConfigs = [] := others_nil alone + refine Ae.Hoare.bind (hoare_discard_ex + (becomeLeader_spec (d := candVoted e) env (leaderPre_cand h L0) ag3)) + fun _ => Ae.Hoare.pin fun v1 o1 ⟨b, p⟩ => ?_ + rcases p with ⟨hr, -, hv, ho⟩ | ⟨hr, -, sends, ho, wn, -, -, sub, cl⟩ + · subst v1 o1 + refine votesTail env ⟨_, rfl, rfl, fun _ => ⟨_, stay fun ⟨_, _, n⟩ => n hr, ag3, um3, + fun m mm => ?_⟩⟩ + obtain ⟨id, mid, rfl⟩ := List.mem_map.mp mm + exact rvInv id mid + · subst o1 + have none1 : v1.otherNodesInActiveConfigs = [] := + others_nil fun x mx y my => wn ▸ alone x (sub x mx) y my + refine votesTail env ⟨sends, by rw [none1, List.map_nil, List.append_nil], wn, + fun hinv => ?_⟩ + obtain ⟨em, ag, mi⟩ := cl hinv + have elect := emits_becomeCandidate (first := sends) + (show Emits (electIfQuorum (CCF.Capabilities.record (env.names.id e.nodeId)) + (env.names.id e.nodeId) (cleanCand (env.names.id e.nodeId) c)) + (primaryState (cleanCand (env.names.id e.nodeId) c)) sends by + unfold electIfQuorum + have yes : (cleanCand (env.names.id e.nodeId) c).role = .candidate + /\ hasQuorum (cleanCand (env.names.id e.nodeId) c).activeConfigurations + (cleanCand (env.names.id e.nodeId) c).votesGranted + /\ Not ((cleanCand (env.names.id e.nodeId) c).isRetiredCommitted + (env.names.id e.nodeId)) := + ⟨rfl, by rw [active]; exact of_decide_eq_true qd, hr⟩ + rw [ite_eq_left yes] + exact em) + rw [sendsEq, none3, List.map_nil, List.append_nil] at elect + exact ⟨_, elect, ag, unmatched_primaryState _ _, mi⟩ + · have qd : Not (hasQuorum (D.map (absConfig env.names)) {env.names.id e.nodeId}) := by + intro hq' + exact hq (quorum.trans (decide_eq_true hq')) + refine votesTail env ⟨_, rfl, rfl, fun _ => ⟨_, stay fun ⟨_, hq', _⟩ => qd ?_, ag3, um3, + fun m mm => ?_⟩⟩ + · rw [active] at hq'; exact hq' + · obtain ⟨id, mid, rfl⟩ := List.mem_map.mp mm + exact rvInv id mid + +end Consensus.TraceValidation.Proofs.Vote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VotePropose.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VotePropose.lean new file mode 100644 index 000000000000..43dd1115b7cf --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VotePropose.lean @@ -0,0 +1,205 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteResponse + +@[expose] public section + +/-! +# `recv_propose_request_vote` against the clean receive (not reviewed) + +M_tv starts an election on a proposal in its view when it is ticking and not retired-committed +(its election guard is the clean `canStartElection`); otherwise it ignores the proposal, and the +clean node does not start an election either: the view differs, the node is retired-committed +(`inv`'s `retired_committed`), or the node is not ticking and cannot start one. +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae (Hoare) +open Consensus.TraceValidation (Names) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (Named named_inj absConfig) + +theorem receive_propose (caps : Caps) (self source : NodeID) (state : NodeState) (t : Nat) + : Model.Node.receive caps self source state (.proposeRequestVoteRequest t) + = handleProposeRequestVoteRequest caps state self t := by + simp [Model.Node.receive, observeTerm] + +theorem canStart_agrees {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) (n : NodeID) + : canStartElection c n <-> canStartElection (abs names d) n := by + have hr : c.role = (abs names d).role := agrees_role h + obtain ⟨-, hl, hc, -, -, hrc⟩ := agrees_frame h + have hc' : c.commitIndex = (abs names d).commitIndex := hc + have hrc' : c.retiredCommittedIndex = (abs names d).retiredCommittedIndex := hrc + simp only [canStartElection, NodeState.signedActiveConfigurations, NodeState.activeConfigurations, + NodeState.retirementCompletedNodes, NodeState.committedLog, NodeState.isRetiredCommitted, + NodeState.retirement, hr, hl, hc', hrc'] + +theorem history_nil_of_active {log : List Model.Node.Entry} {ci : Nat} + (h : activeConfigurations log ci = []) + : configurationHistory log = [] := by + unfold activeConfigurations at h + simp only [List.drop_eq_nil_iff] at h + have := List.length_filter_le (fun x : Configuration => decide (x.index <= ci)) + (configurationHistory log) + exact List.eq_nil_of_length_eq_zero (by omega) + +theorem history_take_nil {log : List Model.Node.Entry} (k : Nat) + (h : configurationHistory log = []) + : configurationHistory (log.take k) = [] := by + rw [← List.take_append_drop k log] at h + unfold configurationHistory at h ⊢ + rw [List.zipIdx_append, List.filterMap_append, List.append_eq_nil_iff] at h + exact h.1 + +/-- A node that can start an election has an active configuration. -/ +theorem active_of_canStart {s : NodeState} {n : NodeID} (h : canStartElection s n) + : s.activeConfigurations ≠ [] := by + intro hnil + obtain ⟨-, mem, -⟩ := h + have hist := history_nil_of_active hnil + rcases mem with m | m + · simp [NodeState.signedActiveConfigurations, hnil, configurationMembers] at m + · have : configurationHistory s.committedLog = [] := history_take_nil _ hist + simp [NodeState.retirementCompletedNodes, this, configurationMembers] at m + +theorem electionGuard_spec (env : Env) {d : State} {o0 : Outbox} + : Hoare env (fun v o => v = d /\ o = o0) Exec.electionGuard + fun _ v o => + v = d + /\ o = o0 + /\ canStartElection (abs env.names d) (env.names.id d.nodeId) := by + unfold Exec.electionGuard + refine Ae.Hoare.bind (Ae.Hoare.of_spec Spec.names + (Q := fun a v o => a = env.names /\ v = d /\ o = o0) + fun v o a v' o' p ⟨ha, hv, ho⟩ => ⟨ha, hv ▸ p.1, ho ▸ p.2⟩) fun nm => ?_ + refine Ae.Hoare.lift fun hn => ?_ + subst hn + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + refine Ae.Hoare.ite (fun yes => Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => + ⟨hv, ho, of_decide_eq_true yes⟩) fun _ => ?_ + exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => Ae.Hoare.fail _ + +/-- What the obligation needs of a proposal hold that ends in `v` having sent `o`. -/ +def ProposePost (env : Env) (node source : NodeID) (t : Nat) (saved : State) (v : State) + (o : Outbox) + : Prop := + v.nodeId = saved.nodeId + /\ forall clean, + agrees env.names clean saved = true + -> UnnamedUnmatched node clean + -> inv env.names v = true + -> exists clean', + Emits + (Model.Node.receive (CCF.Capabilities.record node) node source clean + (.proposeRequestVoteRequest t)) + clean' o + /\ agrees env.names clean' v = true + /\ UnnamedUnmatched node clean' + /\ forall m, m ∈ o -> msgInv env.names m = true + +theorem propose_spec (env : Env) {node source : NodeID} (t : Nat) {saved : State} + (savedId : env.names.id saved.nodeId = node) (h : inv env.names saved = true) + : Hoare env (fun v o => v = saved /\ o = []) + (Exec.recvProposeRequestVote (env.names.name source) t) + fun _ v o => ProposePost env node source t saved v o := by + unfold Exec.recvProposeRequestVote + refine Ae.Hoare.bind + (Ae.Hoare.of_spec (det_traceRecv env _ _ _) + (Q := fun _ v o => v = saved /\ o = []) + fun v o _ v' o' ⟨hv, ho⟩ ⟨h1, h2⟩ => ⟨by rw [h1, hv]; rfl, by rw [h2, ho]; rfl⟩) + fun _ => ?_ + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + have ignored : forall {x : M Unit}, (forall clean, agrees env.names clean saved = true + -> Not (t = clean.currentTerm /\ canStartElection clean node)) + -> Hoare env (fun v o => v = saved /\ o = []) x (fun _ v o => v = saved /\ o = []) + -> Hoare env (fun v o => v = saved /\ o = []) x + fun _ v o => ProposePost env node source t saved v o := by + intro x no hx + refine Ae.Hoare.post hx fun _ v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ⟨clean, ?_, ag, um, by simp⟩⟩ + rw [receive_propose, handleProposeRequestVoteRequest] + simp only [no clean ag, ↓reduceIte] + exact emits_pure _ + have hy := ReplUpdateCommit.Hyps.ofInv h + have canStart : forall clean, agrees env.names clean saved = true + -> (canStartElection clean node + <-> canStartElection (abs env.names saved) (env.names.id saved.nodeId)) := + fun clean ag => by rw [canStart_agrees ag, savedId] + refine Ae.Hoare.ite (fun c1 => ?_) fun c1 => ?_ + · have c1' := c1 + simp only [Bool.and_eq_true, Bool.not_eq_true', beq_iff_eq] at c1' + obtain ⟨-, ht⟩ := c1' + dsimp only + refine Ae.Hoare.ite (fun _ => ?_) fun _ => ?_ + · exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) fun _ => + Ae.Hoare.false_pre fun _ _ f => f + refine Ae.Hoare.bind (electionGuard_spec env) fun _ => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨hv, ho, cs⟩ => ?_ + subst v1 o1 + have act := active_of_canStart cs + have L0 : 0 < saved.lastIdx := by + refine Nat.pos_of_ne_zero fun z => act ?_ + show activeConfigurations (abs env.names saved).log saved.commitIdx = [] + simp [abs, z, activeConfigurations, configurationHistory] + have ne : saved.configurations ≠ [] := by + intro e + obtain ⟨D, hD, sh⟩ := hy.configs L0 + have := shifted_nodes sh + rw [e, List.map_nil, List.map_eq_nil_iff] at this + rw [this, List.map_nil] at hD + exact act hD + refine Ae.Hoare.post (Ae.Hoare.pre + (becomeCandidate_all env (X := saved.votesForMe) (o0 := []) h L0 ne) + fun v o ⟨hv, ho⟩ => ⟨hv, ho⟩) fun _ v o p => ?_ + have nid : v.nodeId = saved.nodeId := by + obtain ⟨_, _, wn, _⟩ := p { abs env.names saved with role := .follower } + ⟨rfl, rfl, rfl, rfl, rfl, fun hp => absurd hp (by simp)⟩ + exact wn + refine ⟨nid, fun clean ag um hinv => ?_⟩ + obtain ⟨ht', hl, hc, hnf, -, hrc⟩ := agrees_frame ag + obtain ⟨sends, ho, -, cl⟩ := p clean ⟨ht', hl, hc, hnf, hrc, by rw [savedId]; exact um⟩ + obtain ⟨c', em, ag', um', mi⟩ := cl hinv + rw [savedId] at em um' + rw [receive_propose, handleProposeRequestVoteRequest, + ite_eq_left ⟨ht.trans ht'.symm, (canStart clean ag).mpr cs⟩] + subst o + exact ⟨c', em, ag', um', mi⟩ + · refine Ae.Hoare.ite (fun c2 => ?_) fun c2 => ?_ + · refine Ae.Hoare.bind (Ae.Hoare.of_spec Spec.names + (Q := fun a v o => a = env.names /\ v = saved /\ o = []) + fun v o a v' o' p ⟨ha, hv, ho⟩ => ⟨ha, hv ▸ p.1, ho ▸ p.2⟩) fun nm => ?_ + refine Ae.Hoare.lift fun hn => ?_ + subst hn + refine Ae.Hoare.ite (fun _ => ?_) fun no => ?_ + · exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.fail _ + · refine ignored (fun clean ag ⟨_, cs⟩ => no ?_) (Ae.Hoare.pure _ fun _ _ p => p) + exact decide_eq_true ((canStart clean ag).mp cs) + · refine ignored (fun clean ag ⟨ht, cs⟩ => ?_) (Ae.Hoare.pure _ fun _ _ p => p) + have ht' : t = saved.currentView := ht.trans (agrees_term_log ag).1 + have ret : saved.isRetiredCommitted + = decide ((abs env.names saved).isRetiredCommitted (env.names.id saved.nodeId)) := by + have hc : (saved.isRetiredCommitted + == decide ((abs env.names saved).isRetiredCommitted (env.names.id saved.nodeId))) + = true := by + inv_conj h "retired_committed" + simpa using hc + obtain ⟨-, -, nr⟩ := (canStart clean ag).mp cs + cases tk : saved.ticking <;> cases rc : saved.isRetiredCommitted <;> + simp_all + +end Consensus.TraceValidation.Proofs.Vote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteResponse.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteResponse.lean new file mode 100644 index 000000000000..552bbece95a0 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteResponse.lean @@ -0,0 +1,573 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteCandidate + +@[expose] public section + +/-! +# `recv_request_vote_response` against the clean receive (not reviewed) + +M_tv ignores a response from a node that is not a peer, adopts a newer view, ignores a stale +or unrequested response and, for a granted (pre-)vote from a member of its configurations, +records it; on a quorum a candidate becomes leader and a pre-vote candidate becomes candidate. +The clean receive does the same: a peer is an eligible peer (`peer_iff_eligible`), the +recorded voters are the clean (pre-)votes granted plus the voter (`voters_record`), and +M_tv's quorum is the clean `hasQuorum` (`quorum_tally`). +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae (Hoare) +open Consensus.TraceValidation (Names) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (Named named_inj absConfig) + +/-- A postcondition for every clean state with a property, from one such state. -/ +theorem hoare_all {env : Env} {α ι : Type} {H : ι -> Prop} {P : State -> Outbox -> Prop} + {x : M α} {Q : ι -> α -> State -> Outbox -> Prop} (i0 : ι) (h0 : H i0) + (h : forall i, H i -> Hoare env P x (Q i)) + : Hoare env P x fun a v o => forall i, H i -> Q i a v o := + fun c a c' e p r => ⟨(h i0 h0 c a c' e p r).1, fun i hi => (h i hi c a c' e p r).2⟩ + +theorem agrees_abs (names : Names) (d : State) : agrees names (abs names d) d = true := by + simp [agrees] + +/-- An initialised node with a peer has a ledger (`inv`'s `empty_ledger_alone`). -/ +theorem pos_of_peer {names : Names} {d : State} (h : inv names d = true) + (init : initialised d = true) (peer : d.allOtherNodes ≠ []) + : 0 < d.lastIdx := by + have alone : (d.currentView == 0 && d.leadership == .none) || d.lastIdx != 0 + || d.allOtherNodes.isEmpty := by + inv_conj h "empty_ledger_alone" + unfold initialised at init + simp only [bne_iff_ne, ne_eq, Bool.or_eq_true] at init + simp only [Bool.or_eq_true, Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, + List.isEmpty_iff] at alone + rcases alone with (⟨a, b⟩ | a) | a + · rcases init with i | i <;> contradiction + · omega + · exact absurd a peer + +/-- The (pre-)vote response message. -/ +def respMsg (pre : Bool) (r : RequestVoteResponse) : Message := + if pre then .requestPreVoteResponse r else .requestVoteResponse r + +theorem receive_resp (caps : Caps) (self source : NodeID) (state : NodeState) (pre : Bool) + (r : RequestVoteResponse) + : Model.Node.receive caps self source state (respMsg pre r) + = if source ∉ eligiblePeers state self then + pure state + else if pre then + handleRequestPreVoteResponse caps self (updateTerm state r.term) source r + else + handleRequestVoteResponse caps self (updateTerm state r.term) source r := by + cases pre <;> simp [respMsg, Model.Node.receive, observeTerm, Message.term] + +theorem localRun_receive (env : Env) {node source : NodeID} {m : Message} + {clean clean' : NodeState} {sends : List (CCF.Envelope NodeID Message)} + (h + : Emits (Model.Node.receive (CCF.Capabilities.record node) node source clean m) + clean' sends) + : CCF.Sections.LocalRun (protocol env) node clean + (cleanActions env (some (source, m)) []) clean' sends := by + have run := CCF.Sections.LocalRun.cons (protocol := protocol env) (node := node) + (state := clean) (action := (protocol env).receive source m) (h {}) + (CCF.Sections.LocalRun.nil _) + simpa [cleanActions] using run + +theorem leaderPre_votes {names : Names} {e : State} (h : inv names e = true) + (L0 : 0 < e.lastIdx) (cand : e.leadership = .candidate) (X : List VoteRec) + : LeaderPre names { e with votesForMe := X } := by + obtain ⟨s1, s2, s3, s4, s5, s6, -⟩ := inv_parts h + have vle : e.views.all (· <= e.lastIdx + 1) = true := by inv_conj h "views_le_last" + have vlt : (e.leadership != .candidate || e.views.size < e.currentView) = true := by + inv_conj h "candidate_views" + have ret : e.isRetiredCommitted + = decide ((abs names e).isRetiredCommitted (names.id e.nodeId)) := by + have hc : (e.isRetiredCommitted + == decide ((abs names e).isRetiredCommitted (names.id e.nodeId))) = true := by + inv_conj h "retired_committed" + simpa using hc + simp only [cand, bne_self_eq_false, Bool.false_or, decide_eq_true_eq] at vlt + refine ⟨by simp [cand], vlt, fun x hx => ?_, s1, s2, s3, s4, s5, ret, Or.inr ?_⟩ + · have := Array.all_eq_true_iff_forall_mem.mp vle x (by simpa using hx) + simpa using this + · rw [eligiblePeers_congr (a := abs names { e with votesForMe := X }) (b := abs names e) rfl rfl] + exact peers_of_inv (d := e) h L0 + +theorem becomeLeader_all (env : Env) {d : State} {o0 : Outbox} + (pre : LeaderPre env.names d) + : Hoare env (fun v o => v = d /\ o = o0) Exec.becomeLeader + (fun b v o => + forall c, + agrees env.names c d = true + -> (c.isRetiredCommitted (env.names.id d.nodeId) + /\ b = false + /\ v = d + /\ o = o0) + \/ (Not (c.isRetiredCommitted (env.names.id d.nodeId)) + /\ b = true + /\ exists sends, + o = o0 ++ sends + /\ v.nodeId = d.nodeId + /\ v.currentView = d.currentView + /\ v.leadership = .leader + /\ (forall x, x ∈ v.configurations -> x ∈ d.configurations) + /\ (inv env.names v = true + -> Emits + (becomePrimary + (CCF.Capabilities.record (env.names.id d.nodeId)) + (env.names.id d.nodeId) c) + (primaryState c) sends + /\ agrees env.names (primaryState c) v = true + /\ forall e, e ∈ sends -> msgInv env.names e = true))) := + hoare_all (abs env.names d) (agrees_abs _ _) fun _ ag => becomeLeader_spec env pre ag + +/-- The clean facts `becomeCandidate_spec` needs of `c`. -/ +def CandFrame (names : Names) (e : State) (c : NodeState) : Prop := + c.currentTerm = e.currentView + /\ c.log = (abs names e).log + /\ c.commitIndex = e.commitIdx + /\ c.isNewFollower = e.isNewFollower + /\ c.retiredCommittedIndex = e.retiredCommittedIdx + /\ UnnamedUnmatched (names.id e.nodeId) c + +theorem becomeCandidate_all (env : Env) {e : State} {X : List VoteRec} {o0 : Outbox} + (h : inv env.names e = true) (L0 : 0 < e.lastIdx) (ne : e.configurations ≠ []) + : Hoare env (fun v o => v = { e with votesForMe := X } /\ o = o0) Exec.becomeCandidate + (fun _ v o => + forall c, + CandFrame env.names e c + -> exists sends, + o = o0 ++ sends + /\ v.nodeId = e.nodeId + /\ (inv env.names v = true + -> exists c', + Emits + (Model.Node.becomeCandidate + (CCF.Capabilities.record (env.names.id e.nodeId)) c + (env.names.id e.nodeId)) + c' sends + /\ agrees env.names c' v = true + /\ UnnamedUnmatched (env.names.id e.nodeId) c' + /\ forall m, m ∈ sends -> msgInv env.names m = true)) := + hoare_all { abs env.names e with role := .follower } + ⟨rfl, rfl, rfl, rfl, rfl, fun hp => absurd hp (by simp)⟩ + fun _ ⟨ht, hl, hc, hnf, hrc, um⟩ => + becomeCandidate_spec env h L0 ne ht hl hc hnf hrc um + +/-! ## The clean receive of a response -/ + +/-- A response the clean handler acts on: a granted (pre-)vote in the current term. -/ +def Counted (pre : Bool) (state : NodeState) (r : RequestVoteResponse) : Prop := + (if pre then state.role = .preVoteCandidate else state.role = .candidate) + /\ r.term = state.currentTerm + /\ r.voteGranted = true + +theorem receive_notPeer {caps : Caps} {self source : NodeID} {state : NodeState} + {pre : Bool} {r : RequestVoteResponse} (np : source ∉ eligiblePeers state self) + : Model.Node.receive caps self source state (respMsg pre r) = pure state := by + rw [receive_resp] + simp [np] + +theorem receive_newer {caps : Caps} {self source : NodeID} {state : NodeState} + {pre : Bool} {r : RequestVoteResponse} (el : source ∈ eligiblePeers state self) + (lt : state.currentTerm < r.term) + : Model.Node.receive caps self source state (respMsg pre r) + = pure (Model.Node.becomeAwareOfNewTerm state r.term) := by + rw [receive_resp, updateTerm_of_lt lt] + cases pre <;> simp [el, handleRequestVoteResponse, handleRequestPreVoteResponse, + Model.Node.becomeAwareOfNewTerm] + +theorem receive_ignored {caps : Caps} {self source : NodeID} {state : NodeState} + {pre : Bool} {r : RequestVoteResponse} (el : source ∈ eligiblePeers state self) + (ge : ¬ state.currentTerm < r.term) (no : ¬ Counted pre state r) + : Model.Node.receive caps self source state (respMsg pre r) = pure state := by + rw [receive_resp, updateTerm_of_ge ge] + cases pre <;> simp only [Counted, Bool.false_eq_true, ite_true, ite_false] at no <;> + simp only [el, not_true_eq_false, ite_false, Bool.false_eq_true, ite_true, + handleRequestVoteResponse, handleRequestPreVoteResponse, no] + +theorem receive_vote {caps : Caps} {self source : NodeID} {state : NodeState} + {r : RequestVoteResponse} (el : source ∈ eligiblePeers state self) + (yes : Counted false state r) + : Model.Node.receive caps self source state (respMsg false r) + = electIfQuorum caps self + { state with votesGranted := insert source state.votesGranted } := by + obtain ⟨hr, ht, hg⟩ := yes + rw [receive_resp, updateTerm_of_ge (by omega)] + simp at hr + simp [el, handleRequestVoteResponse, hr, ht, hg] + +theorem receive_preVote {caps : Caps} {self source : NodeID} {state : NodeState} + {r : RequestVoteResponse} (el : source ∈ eligiblePeers state self) + (yes : Counted true state r) + : Model.Node.receive caps self source state (respMsg true r) + = let s := { state with preVotesGranted := insert source state.preVotesGranted } + if hasQuorum s.activeConfigurations s.preVotesGranted then + Model.Node.becomeCandidate caps s self + else + pure s := by + obtain ⟨hr, ht, hg⟩ := yes + rw [receive_resp, updateTerm_of_ge (by omega)] + simp at hr + simp [el, handleRequestPreVoteResponse, hr, ht, hg] + +theorem set_cons (names : Names) (x : NodeId) (l : List NodeId) + : names.set (x :: l) = insert (names.id x) (names.set l) := + CCF.Finset.ext + fun a => by simp [Names.set, CCF.Finset.mem_ofList, CCF.Finset.mem_insert] + +theorem agrees_role {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c.role = absRole d.leadership := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + exact h.1.1.1.1.1.1.1.1.1.1 + +theorem agrees_votes {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : (d.leadership = .candidate -> c.votesGranted = names.set (voters d)) + /\ (d.leadership = .preVoteCandidate + -> c.preVotesGranted = names.set (voters d)) := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨-, h9⟩, h10⟩, -⟩ := h + refine ⟨fun l => ?_, fun l => ?_⟩ + · simpa [abs, absRole, l, voters] using h9 + · simpa [abs, absRole, l, voters] using h10 + +theorem eligible_agrees {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) (n : NodeID) + : eligiblePeers c n = eligiblePeers (abs names d) n := by + obtain ⟨-, hl, hc, -⟩ := agrees_frame h + exact eligiblePeers_congr hl hc n + +theorem agrees_votesGranted {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) (cand : d.leadership = .candidate) (X : List VoteRec) + : agrees names + { c with votesGranted := names.set (voters { d with votesForMe := X }) } + { d with votesForMe := X } + = true := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, -⟩, h10⟩, h11⟩ := h + simp only [abs, trackedPeers, cand, absRole] at h1 h2 h3 h4 h5 h6 h7 h8 h10 h11 ⊢ + simp_all [voters] + +theorem agrees_preVotesGranted {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) (cand : d.leadership = .preVoteCandidate) + (X : List VoteRec) + : agrees names + { c with preVotesGranted := names.set (voters { d with votesForMe := X }) } + { d with votesForMe := X } + = true := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, h9⟩, -⟩, h11⟩ := h + simp only [abs, trackedPeers, cand, absRole] at h1 h2 h3 h4 h5 h6 h7 h8 h9 h11 ⊢ + simp_all [voters] + +/-- The (pre-)candidate role a counted response needs. -/ +def wantRole (pre : Bool) : Leadership := if pre then .preVoteCandidate else .candidate + +/-- What the obligation needs of a (pre-)vote response hold that ends in `v` having sent `o`. -/ +def RespPost (env : Env) (node source : NodeID) (pre : Bool) (r : RequestVoteResponse) + (saved : State) (v : State) (o : Outbox) + : Prop := + v.nodeId = saved.nodeId + /\ forall clean, + agrees env.names clean saved = true + -> UnnamedUnmatched node clean + -> inv env.names v = true + -> exists clean', + Emits + (Model.Node.receive (CCF.Capabilities.record node) node source clean + (respMsg pre r)) + clean' o + /\ agrees env.names clean' v = true + /\ UnnamedUnmatched node clean' + /\ forall m, m ∈ o -> msgInv env.names m = true + +theorem voteResponse_spec (env : Env) {node source : NodeID} (pre : Bool) + (r : RequestVoteResponse) {saved : State} + (savedId : env.names.id saved.nodeId = node) + (hsrc : env.names.id (env.names.name source) = source) + (h : inv env.names saved = true) (init : initialised saved = true) + : Hoare env (fun v o => v = saved /\ o = []) + (Exec.recvRequestVoteResponse (env.names.name source) pre r) + fun _ v o => RespPost env node source pre r saved v o := by + unfold Exec.recvRequestVoteResponse + refine Ae.Hoare.bind + (Ae.Hoare.of_spec (det_traceRecv env _ _ _) + (Q := fun _ v o => v = saved /\ o = []) + fun v o _ v' o' ⟨hv, ho⟩ ⟨h1, h2⟩ => ⟨by rw [h1, hv]; rfl, by rw [h2, ho]; rfl⟩) + fun _ => ?_ + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + dsimp only + have elig : forall clean, agrees env.names clean saved = true + -> eligiblePeers clean node = eligiblePeers (abs env.names saved) (env.names.id saved.nodeId) := + fun clean ag => by rw [eligible_agrees ag, savedId] + refine Ae.Hoare.ite (fun np => ?_) fun pp => ?_ + · refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ⟨clean, ?_, ag, um, by simp⟩⟩ + have np' : source ∉ eligiblePeers clean node := by + rw [elig clean ag, ← peer_iff_eligible h init hsrc] + simpa using np + rw [receive_notPeer np'] + exact emits_pure _ + have el : forall clean, agrees env.names clean saved = true -> source ∈ eligiblePeers clean node := + fun clean ag => by + rw [elig clean ag, ← peer_iff_eligible h init hsrc] + simpa [Option.isSome_iff_ne_none] using pp + refine Ae.Hoare.ite (fun lt => ?_) fun ge => ?_ + · refine Ae.Hoare.bind (Ae.Hoare.of_spec (det_becomeAware env r.term) + (Q := fun _ v o => v = bant r.term saved /\ o = []) + fun v o _ v' o' ⟨hv, ho⟩ ⟨h1, h2⟩ => ⟨by rw [h1, hv], by rw [h2, ho]; rfl⟩) fun _ => ?_ + refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ⟨_, ?_, agrees_bant r.term ag, ?_, by simp⟩⟩ + · have lt' : clean.currentTerm < r.term := by rw [(agrees_term_log ag).1]; exact lt + rw [receive_newer (el clean ag) lt'] + exact emits_pure _ + · have lt' : clean.currentTerm < r.term := by rw [(agrees_term_log ag).1]; exact lt + have := unmatched_updateTerm r.term um + rwa [updateTerm_of_lt lt'] at this + have ign : Not (saved.leadership = wantRole pre /\ r.term = saved.currentView + /\ r.voteGranted = true) + -> Hoare env (fun v o => v = saved /\ o = []) (pure ()) + fun _ v o => RespPost env node source pre r saved v o := by + intro no + refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ⟨clean, ?_, ag, um, by simp⟩⟩ + have ge' : Not (clean.currentTerm < r.term) := by rw [(agrees_term_log ag).1]; exact ge + have no' : Not (Counted pre clean r) := by + rintro ⟨hr, ht, hg⟩ + refine no ⟨?_, by rw [ht, (agrees_term_log ag).1], hg⟩ + rw [agrees_role ag] at hr + cases pre <;> cases hl : saved.leadership <;> simp_all [wantRole, absRole] + rw [receive_ignored (el clean ag) ge' no'] + exact emits_pure _ + refine Ae.Hoare.ite (fun ne => ign ?_) fun eq => ?_ + · rintro ⟨-, ht, -⟩ + simp [ht] at ne + refine Ae.Hoare.ite (fun c1 => ign ?_) fun c1 => ?_ + · rintro ⟨hl, -⟩ + cases pre <;> simp [hl, wantRole] at c1 + refine Ae.Hoare.ite (fun c2 => ign ?_) fun c2 => ?_ + · rintro ⟨hl, -⟩ + cases pre <;> simp [hl, wantRole] at c2 + refine Ae.Hoare.ite (fun c3 => ign ?_) fun c3 => ?_ + · rintro ⟨hl, -⟩ + cases pre <;> simp [hl, wantRole] at c3 + refine Ae.Hoare.ite (fun c4 => ign ?_) fun c4 => ?_ + · rintro ⟨-, -, hg⟩ + simp [hg] at c4 + refine Ae.Hoare.ite (fun mem => ?_) fun _ => ?_ + rotate_left + · exact Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => + Ae.Hoare.bind (R := fun _ _ _ => False) (Ae.Hoare.fail _) fun _ => + Ae.Hoare.false_pre fun _ _ f => f + have role : saved.leadership = wantRole pre := by + cases pre <;> cases hl : saved.leadership <;> simp_all [wantRole] + have ht : r.term = saved.currentView := by simp at eq; omega + have hg : r.voteGranted = true := by simpa using c4 + have counted : forall clean, agrees env.names clean saved = true -> Counted pre clean r := by + intro clean ag + refine ⟨?_, by rw [ht, (agrees_term_log ag).1], hg⟩ + rw [agrees_role ag, role] + cases pre <;> rfl + have ge' : forall clean, agrees env.names clean saved = true + -> Not (clean.currentTerm < r.term) := + fun clean ag => by rw [(agrees_term_log ag).1]; exact ge + have others : saved.allOtherNodes ≠ [] := by + intro e + simp [State.peer?, e] at pp + have L0 := pos_of_peer h init others + have hy := ReplUpdateCommit.Hyps.ofInv h + obtain ⟨D, hD, sh⟩ := hy.configs L0 + have sorted := hy.sorted L0 + have cand : saved.leadership = .candidate \/ saved.leadership = .preVoteCandidate := by + cases pre <;> simp [role, wantRole] + have t := tally_of_inv h cand + have member : exists c, c ∈ saved.configurations + /\ env.names.name source ∈ c.nodes.map Prod.fst := by + simp only [List.any_eq_true, beq_iff_eq] at mem + obtain ⟨c, mc, a, ma, e⟩ := mem + exact ⟨c, mc, List.mem_map.mpr ⟨a, ma, e⟩⟩ + have quorum := quorum_tally (names := env.names) (D := D) (tally_record (env.names.name source) t sorted) + hy.membersNamed (fun w mw => by + rcases List.mem_cons.mp mw with rfl | mw + · obtain ⟨c, mc, ma⟩ := member + obtain ⟨a, ma2, e⟩ := List.mem_map.mp ma + rw [← e] + exact hy.membersNamed c mc a ma2 + · rcases List.mem_cons.mp mw with rfl | mw + · exact hy.selfNamed + · obtain ⟨-, c, mc, ma⟩ := (mem_flat_tally t).mp mw + obtain ⟨a, ma2, e⟩ := List.mem_map.mp ma + rw [← e] + exact hy.membersNamed c mc a ma2) + hy.distinct (shifted_nodes sh) + have votes : env.names.set (voters { saved with votesForMe := recorded (env.names.name source) saved }) + = insert source (env.names.set (voters saved)) := by + rw [set_congr (voters_record t sorted member), set_cons, hsrc] + have active : forall clean, agrees env.names clean saved = true + -> clean.activeConfigurations = D.map (absConfig env.names) := by + intro clean ag + obtain ⟨-, hl, hc, -⟩ := agrees_frame ag + show activeConfigurations clean.log clean.commitIndex = _ + rw [hl, hc] + exact hD + unfold Exec.addVoteForMe + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + refine Ae.Hoare.bind (recordVote_spec env _ saved []) fun b => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨hb, hv, ho⟩ => ?_ + subst v1 o1 + rw [set_cons, hsrc] at quorum + have qb : b = decide (hasQuorum (D.map (absConfig env.names)) + (insert source (env.names.set (voters saved)))) := by + rw [hb] + exact quorum + have notPrimary : forall clean, agrees env.names clean saved = true -> clean.role ≠ .primary := by + intro clean ag hp + rw [agrees_role ag] at hp + cases pre <;> simp [role, wantRole, absRole] at hp + have failed : forall {Q : Unit -> State -> Outbox -> Prop} {P : State -> Outbox -> Prop}, + Hoare env P (do + let l ← curLoc + fail (toString l ++ toString ": add_vote_for_me() while not a candidate")) Q := + Ae.Hoare.bind (Ae.Hoare.keeps Spec.curLoc fun _ _ _ p => p) fun _ => Ae.Hoare.fail _ + cases pre + · have hcand : saved.leadership = .candidate := role + have agS : forall clean, agrees env.names clean saved = true + -> agrees env.names { clean with votesGranted := insert source clean.votesGranted } + { saved with votesForMe := recorded (env.names.name source) saved } = true := by + intro clean ag + have := agrees_votesGranted ag hcand (recorded (env.names.name source) saved) + rwa [votes, ← (agrees_votes ag).1 hcand] at this + have unS : forall clean, agrees env.names clean saved = true -> UnnamedUnmatched node clean + -> UnnamedUnmatched node { clean with votesGranted := insert source clean.votesGranted } := + fun clean ag um => unmatched_frame um fun hp => absurd hp (notPrimary clean ag) + have qS : forall clean, agrees env.names clean saved = true + -> (hasQuorum { clean with votesGranted := insert source clean.votesGranted }.activeConfigurations + { clean with votesGranted := insert source clean.votesGranted }.votesGranted + <-> b = true) := by + intro clean ag + rw [qb, decide_eq_true_iff, (agrees_votes ag).1 hcand] + show hasQuorum clean.activeConfigurations _ <-> _ + rw [active clean ag] + refine Ae.Hoare.ite (fun yes => ?_) fun no => ?_ + · split + · rename_i e + rw [hcand] at e + cases e + rotate_left + · exact failed + refine hoare_discard (Ae.Hoare.post (becomeLeader_all env (o0 := []) + (leaderPre_votes h L0 hcand (recorded (env.names.name source) saved))) + fun _ v o p => ?_) + have nid : v.nodeId = saved.nodeId := by + rcases p _ (agrees_abs _ _) with ⟨-, -, hv, -⟩ | ⟨-, -, sends, -, wn, -⟩ + · rw [hv] + · exact wn + refine ⟨nid, fun clean ag um hinv => ?_⟩ + rw [receive_vote (el clean ag) (counted clean ag)] + unfold electIfQuorum + rcases p _ (agS clean ag) with ⟨hr, -, hv, ho⟩ | ⟨hr, -, sends, ho, wn, -, -, -, cl⟩ + · subst v o + have no : Not ({ clean with votesGranted := insert source clean.votesGranted }.role = .candidate + /\ hasQuorum { clean with votesGranted := insert source clean.votesGranted }.activeConfigurations + { clean with votesGranted := insert source clean.votesGranted }.votesGranted + /\ Not ({ clean with votesGranted := insert source clean.votesGranted }.isRetiredCommitted node)) := + fun ⟨_, _, n⟩ => n (savedId ▸ hr) + simp only [no, ↓reduceIte] + exact ⟨_, emits_pure _, agS clean ag, unS clean ag um, by simp⟩ + · obtain ⟨em, ag', mi⟩ := cl hinv + have yes' : { clean with votesGranted := insert source clean.votesGranted }.role = .candidate + /\ hasQuorum { clean with votesGranted := insert source clean.votesGranted }.activeConfigurations + { clean with votesGranted := insert source clean.votesGranted }.votesGranted + /\ Not ({ clean with votesGranted := insert source clean.votesGranted }.isRetiredCommitted node) := + ⟨by rw [agrees_role ag, hcand]; rfl, (qS clean ag).mpr yes, savedId ▸ hr⟩ + rw [ite_eq_left yes'] + rw [savedId] at em + subst o + exact ⟨_, em, ag', unmatched_primaryState _ _, mi⟩ + · refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ?_⟩ + rw [receive_vote (el clean ag) (counted clean ag)] + unfold electIfQuorum + have no' : Not ({ clean with votesGranted := insert source clean.votesGranted }.role = .candidate + /\ hasQuorum { clean with votesGranted := insert source clean.votesGranted }.activeConfigurations + { clean with votesGranted := insert source clean.votesGranted }.votesGranted + /\ Not ({ clean with votesGranted := insert source clean.votesGranted }.isRetiredCommitted node)) := + fun ⟨_, q, _⟩ => no ((qS clean ag).mp q) + simp only [no', ↓reduceIte] + exact ⟨_, emits_pure _, agS clean ag, unS clean ag um, by simp⟩ + · have hpre : saved.leadership = .preVoteCandidate := role + have ne : saved.configurations ≠ [] := by + obtain ⟨c, mc, -⟩ := member + exact List.ne_nil_of_mem mc + have agS : forall clean, agrees env.names clean saved = true + -> agrees env.names { clean with preVotesGranted := insert source clean.preVotesGranted } + { saved with votesForMe := recorded (env.names.name source) saved } = true := by + intro clean ag + have := agrees_preVotesGranted ag hpre (recorded (env.names.name source) saved) + rwa [votes, ← (agrees_votes ag).2 hpre] at this + have unS : forall clean, agrees env.names clean saved = true -> UnnamedUnmatched node clean + -> UnnamedUnmatched node { clean with preVotesGranted := insert source clean.preVotesGranted } := + fun clean ag um => unmatched_frame um fun hp => absurd hp (notPrimary clean ag) + have qS : forall clean, agrees env.names clean saved = true + -> (hasQuorum + { clean with preVotesGranted := insert source clean.preVotesGranted }.activeConfigurations + { clean with preVotesGranted := insert source clean.preVotesGranted }.preVotesGranted + <-> b = true) := by + intro clean ag + rw [qb, decide_eq_true_iff, (agrees_votes ag).2 hpre] + show hasQuorum clean.activeConfigurations _ <-> _ + rw [active clean ag] + refine Ae.Hoare.ite (fun yes => ?_) fun no => ?_ + · split + rotate_left + · rename_i e + rw [hpre] at e + cases e + · exact failed + refine Ae.Hoare.post (becomeCandidate_all env (o0 := []) h L0 ne) fun _ v o p => ?_ + have nid : v.nodeId = saved.nodeId := by + obtain ⟨_, _, wn, _⟩ := p { abs env.names saved with role := .follower } + ⟨rfl, rfl, rfl, rfl, rfl, fun hp => absurd hp (by simp)⟩ + exact wn + refine ⟨nid, fun clean ag um hinv => ?_⟩ + obtain ⟨ht', hl, hc, hnf, -, hrc⟩ := agrees_frame ag + obtain ⟨sends, ho, -, cl⟩ := p { clean with preVotesGranted := insert source clean.preVotesGranted } + ⟨ht', hl, hc, hnf, hrc, by rw [savedId]; exact unS clean ag um⟩ + obtain ⟨c', em, ag', um', mi⟩ := cl hinv + rw [savedId] at em um' + rw [receive_preVote (el clean ag) (counted clean ag)] + dsimp only + rw [ite_eq_left ((qS clean ag).mpr yes)] + subst o + exact ⟨c', em, ag', um', mi⟩ + · refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ?_ + subst v o + refine ⟨rfl, fun clean ag um _ => ?_⟩ + rw [receive_preVote (el clean ag) (counted clean ag)] + dsimp only + have no' : Not (hasQuorum + { clean with preVotesGranted := insert source clean.preVotesGranted }.activeConfigurations + { clean with preVotesGranted := insert source clean.preVotesGranted }.preVotesGranted) := + fun q => no ((qS clean ag).mp q) + simp only [no', ↓reduceIte] + exact ⟨_, emits_pure _, agS clean ag, unS clean ag um, by simp⟩ + +end Consensus.TraceValidation.Proofs.Vote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteTally.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteTally.lean new file mode 100644 index 000000000000..0ee376fbae39 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/VoteTally.lean @@ -0,0 +1,527 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.VoteBecomeLeader + +@[expose] public section + +/-! +# Vote tallies: `record_vote` against the clean votes granted (not reviewed) +-/ + +namespace Consensus.TraceValidation.Proofs.Vote + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae (Hoare) +open Consensus.TraceValidation (Names) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (Named named_inj absConfig) + +/-- A vote record: configuration index, votes, quorum. -/ +abbrev VoteRec := Nat × List NodeId × Nat + +def addVote (from_ : NodeId) (vs : List NodeId) : List NodeId := + if vs.contains from_ then vs else vs ++ [from_] + +/-- One iteration of `record_vote`'s loop. -/ +def voteStep (from_ : NodeId) (votes : List VoteRec) (c : Config) : List VoteRec := + if c.nodes.any (·.1 == from_) then + match votes.find? (·.1 == c.idx) with + | some _ => + votes.map + fun (i, vs, q) => if i == c.idx then (i, addVote from_ vs, q) else (i, vs, q) + | none => (votes ++ [(c.idx, [from_], 0)]).mergeSort (fun a b => a.1 <= b.1) + else + votes + +/-- The vote records after `record_vote from_`. -/ +def recorded (from_ : NodeId) (v : State) : List VoteRec := + v.configurations.foldl (voteStep from_) v.votesForMe + +theorem recordVote_spec (env : Env) (from_ : NodeId) (v0 : State) (o0 : Outbox) + : Hoare env (fun v o => v = v0 /\ o = o0) (Exec.recordVote from_) + (fun b v o => + b + = (!v0.configurations.isEmpty + && (recorded from_ v0).all fun (_, vs, q) => decide (vs.length >= q)) + /\ v = { v0 with votesForMe := recorded from_ v0 } + /\ o = o0) := by + unfold Exec.recordVote + refine Ae.Hoare.getV_bind fun s => ?_ + refine Ae.Hoare.pin fun v1 o1 ⟨⟨hv, ho⟩, hs⟩ => ?_ + subst s + subst v1 o1 + split + · rename_i he + refine Ae.Hoare.pure _ fun v o ⟨hv, ho⟩ => ⟨by simp [he], ?_, ho⟩ + have : recorded from_ v0 = v0.votesForMe := by + simp only [List.isEmpty_iff] at he + simp [recorded, he] + rw [this, hv] + · refine Ae.Hoare.bind (Ae.Hoare.pre (Ae.Hoare.forIn_list _ _ _ + (fun pre b v o => v = v0 /\ o = o0 /\ b = pre.foldl (voteStep from_) v0.votesForMe) + (fun b v o => v = v0 /\ o = o0 /\ b = recorded from_ v0) ?_ fun _ _ _ p => p) + fun v o ⟨hv, ho⟩ => ⟨hv, ho, rfl⟩) ?_ + · intro pre c rest b hl + dsimp only + split <;> rename_i hc <;> refine Ae.Hoare.pure _ fun v o ⟨hv, ho, hb⟩ => ⟨hv, ho, ?_⟩ <;> + simp only [List.foldl_append, List.foldl_cons, List.foldl_nil, ← hb, voteStep, addVote, + hc] <;> rfl + · rename_i he + intro b + refine Ae.Hoare.bind (R := fun _ v o => + v = { v0 with votesForMe := recorded from_ v0 } /\ o = o0 /\ b = recorded from_ v0) + (Ae.Hoare.setV _ fun v o ⟨hv, ho, hb⟩ => ⟨by rw [hv, hb], ho, hb⟩) fun _ => ?_ + exact Ae.Hoare.pure _ fun v o ⟨hv, ho, hb⟩ => ⟨by simp [he, hb], hv, ho⟩ + +/-- A record after the loop: its votes gain `from_` if a configuration at its index has it. -/ +def addIf (from_ : NodeId) (cs : List Config) (r : VoteRec) : VoteRec := + if cs.any (fun c => c.idx == r.1 && c.nodes.any (·.1 == from_)) then + (r.1, addVote from_ r.2.1, r.2.2) + else + r + +theorem addVote_addVote (from_ : NodeId) (vs : List NodeId) + : addVote from_ (addVote from_ vs) = addVote from_ vs := by + unfold addVote + split + · simp_all + · simp + +theorem mem_addVote {from_ x : NodeId} {vs : List NodeId} + : x ∈ addVote from_ vs <-> x = from_ \/ x ∈ vs := by + unfold addVote + split + · rename_i h + simp only [List.contains_iff_mem] at h + constructor + · exact Or.inr + · rintro (rfl | h') + · exact h + · exact h' + · simp [or_comm] + +theorem nodup_addVote {from_ : NodeId} {vs : List NodeId} (h : vs.Nodup) + : (addVote from_ vs).Nodup := by + unfold addVote + split + · exact h + · rename_i hc + simp only [List.contains_iff_mem] at hc + exact List.nodup_append.mpr ⟨h, List.nodup_cons.mpr ⟨List.not_mem_nil, List.nodup_nil⟩, fun a ha b hb => by + simp only [List.mem_singleton] at hb + subst hb + exact fun e => hc (e ▸ ha)⟩ + +/-- With a record at the index of each configuration, the loop adds to records in place. -/ +theorem foldl_voteStep (from_ : NodeId) + : forall (cs : List Config) (votes : List VoteRec), + (forall c, c ∈ cs -> exists r, r ∈ votes /\ r.1 = c.idx) + -> cs.foldl (voteStep from_) votes = votes.map (addIf from_ cs) + | [], votes, _ => + ((List.map_congr_left (l := votes) (f := addIf from_ []) (g := id) + fun r _ => by simp [addIf]).trans (List.map_id _)).symm + | c :: rest, votes, cover => by + rw [List.foldl_cons] + by_cases hc : c.nodes.any (·.1 == from_) = true + · obtain ⟨r, hr, hi⟩ := cover c List.mem_cons_self + have found : (votes.find? (·.1 == c.idx)).isSome := by + rw [List.find?_isSome] + exact ⟨r, hr, by simp [hi]⟩ + have step : voteStep from_ votes c + = votes.map fun r => if r.1 == c.idx then (r.1, addVote from_ r.2.1, r.2.2) else r := by + simp only [voteStep, hc, ite_true] + obtain ⟨y, hy⟩ := Option.isSome_iff_exists.mp found + rw [hy] + rw [step, foldl_voteStep from_ rest _ fun c' mem => ?_, List.map_map] + · apply List.map_congr_left + intro r _ + show addIf from_ rest (if r.1 == c.idx then (r.1, addVote from_ r.2.1, r.2.2) else r) + = addIf from_ (c :: rest) r + by_cases e : r.1 = c.idx + · have be : (r.1 == c.idx) = true := beq_iff_eq.mpr e + simp only [be, ite_true] + unfold addIf + simp [e, hc, addVote_addVote] + · have be : (r.1 == c.idx) = false := beq_false_of_ne e + have be' : (c.idx == r.1) = false := beq_false_of_ne fun h => e h.symm + simp only [be, Bool.false_eq_true, ite_false] + unfold addIf + simp only [List.any_cons, be', Bool.false_and, Bool.false_or] + · obtain ⟨r', hr', hi'⟩ := cover c' (List.mem_cons_of_mem _ mem) + refine ⟨_, List.mem_map_of_mem hr', ?_⟩ + split <;> exact hi' + · have step : voteStep from_ votes c = votes := by simp [voteStep, hc] + rw [step, foldl_voteStep from_ rest _ fun c' mem => + cover c' (List.mem_cons_of_mem _ mem)] + apply List.map_congr_left + intro r _ + rw [Bool.not_eq_true] at hc + simp only [addIf, List.any_cons, hc, Bool.and_false, Bool.false_or] + +/-- +`votes` tallies the votes of `W` against the configurations `cs`: one record per +configuration, at its index with its quorum, whose duplicate-free votes are the members of the +configuration in `W`. +-/ +def Tally (cs : List Config) (votes : List VoteRec) (W : List NodeId) : Prop := + votes.length = cs.length + /\ forall r c, + (r, c) ∈ votes.zip cs + -> r.1 = c.idx + /\ r.2.2 = State.quorum c.nodes.length + /\ r.2.1.Nodup + /\ forall x, x ∈ r.2.1 <-> x ∈ c.nodes.map Prod.fst /\ x ∈ W + +theorem exists_zip_right {α β : Type} + : forall {as : List α} {bs : List β}, + as.length = bs.length -> forall b, b ∈ bs -> exists a, (a, b) ∈ as.zip bs + | [], [], _, _, h => absurd h List.not_mem_nil + | a :: as, b' :: bs, hl, b, h => by + rcases List.mem_cons.mp h with rfl | h + · exact ⟨a, by simp⟩ + · obtain ⟨x, hx⟩ := exists_zip_right (as := as) (by simpa using hl) b h + exact ⟨x, List.mem_cons_of_mem _ hx⟩ + +theorem idx_inj + : forall {cs : List Config}, + cs.Pairwise (fun a b => a.idx < b.idx) + -> forall {a b : Config}, a ∈ cs -> b ∈ cs -> a.idx = b.idx -> a = b + | [], _, _, _, ha, _, _ => absurd ha List.not_mem_nil + | x :: xs, sorted, a, b, ha, hb, e => by + obtain ⟨lt, sorted⟩ := List.pairwise_cons.mp sorted + rcases List.mem_cons.mp ha with ha' | ha' <;> rcases List.mem_cons.mp hb with hb' | hb' + · rw [ha', hb'] + · have := lt b hb'; rw [ha'] at e; omega + · have := lt a ha'; rw [hb'] at e; omega + · exact idx_inj sorted ha' hb' e + +theorem Tally.cover {cs : List Config} {votes : List VoteRec} {W : List NodeId} + (t : Tally cs votes W) + : forall c, c ∈ cs -> exists r, r ∈ votes /\ r.1 = c.idx := by + intro c mem + obtain ⟨r, hr⟩ := exists_zip_right t.1 c mem + exact ⟨r, (List.of_mem_zip hr).1, (t.2 r c hr).1⟩ + +theorem mem_ids {c : Config} {x : NodeId} + : c.nodes.any (·.1 == x) = true <-> x ∈ c.nodes.map Prod.fst := by + simp + +/-- `record_vote from_` tallies one more voter. -/ +theorem tally_record {cs : List Config} {votes : List VoteRec} {W : List NodeId} + (from_ : NodeId) (t : Tally cs votes W) + (sorted : cs.Pairwise fun a b => a.idx < b.idx) + : Tally cs (cs.foldl (voteStep from_) votes) (from_ :: W) := by + rw [foldl_voteStep from_ cs votes t.cover] + refine ⟨by rw [List.length_map, t.1], fun r' c mem => ?_⟩ + rw [List.zip_map_left, List.mem_map] at mem + obtain ⟨⟨r, c'⟩, mem, e⟩ := mem + simp only [Prod.map, id, Prod.mk.injEq] at e + obtain ⟨rfl, rfl⟩ := e + obtain ⟨hi, hq, nd, hm⟩ := t.2 r c' mem + have hc : c' ∈ cs := (List.of_mem_zip mem).2 + have cond : cs.any (fun c => c.idx == r.1 && c.nodes.any (·.1 == from_)) + = c'.nodes.any (·.1 == from_) := by + apply Bool.eq_iff_iff.mpr + simp only [List.any_eq_true, Bool.and_eq_true, beq_iff_eq] + constructor + · rintro ⟨c, mem, ci, has⟩ + rw [idx_inj sorted mem hc (ci.trans hi)] at has + exact has + · exact fun has => ⟨c', hc, hi.symm, has⟩ + unfold addIf + rw [cond] + split + · rename_i has + rw [mem_ids] at has + refine ⟨hi, hq, nodup_addVote nd, fun x => ?_⟩ + rw [mem_addVote, hm, List.mem_cons] + constructor + · rintro (rfl | ⟨a, b⟩) + · exact ⟨has, Or.inl rfl⟩ + · exact ⟨a, Or.inr b⟩ + · rintro ⟨a, rfl | b⟩ + · exact Or.inl rfl + · exact Or.inr ⟨a, b⟩ + · rename_i has + rw [mem_ids] at has + refine ⟨hi, hq, nd, fun x => ?_⟩ + rw [hm, List.mem_cons] + constructor + · rintro ⟨a, b⟩ + exact ⟨a, Or.inr b⟩ + · rintro ⟨a, rfl | b⟩ + · exact absurd a has + · exact ⟨a, b⟩ + +theorem nodup_map_named {names : Names} {l : List NodeId} + (named : forall a, a ∈ l -> Named names a) (nodup : l.Nodup) + : (l.map names.id).Nodup := by + unfold List.Nodup + rw [List.pairwise_map] + exact List.Pairwise.imp_of_mem (fun ma mb ne same => ne (named_inj (named _ ma) (named _ mb) same)) + nodup + +/-- A record's quorum check is the clean majority of its configuration. -/ +theorem majority_tally {names : Names} {c : Config} {vs W : List NodeId} + (named : forall a, a ∈ c.nodes -> Named names a.1) + (Wnamed : forall w, w ∈ W -> Named names w) (distinct : (c.nodes.map Prod.fst).Nodup) + (nodup : vs.Nodup) (mem : forall x, x ∈ vs <-> x ∈ c.nodes.map Prod.fst /\ x ∈ W) + : decide (vs.length >= State.quorum c.nodes.length) + = decide (hasConfigurationMajority (names.set W) (absConfig names c)) := by + have idsNamed : forall a, a ∈ c.nodes.map Prod.fst -> Named names a := by + intro a ha + obtain ⟨p, hp, rfl⟩ := List.mem_map.mp ha + exact named p hp + have nodes : (absConfig names c).nodes.card = c.nodes.length := by + simp only [absConfig, Names.set] + rw [CCF.Finset.card_ofList_of_nodup (nodup_map_named idsNamed distinct), List.length_map, + List.length_map] + have inter : (names.set W ∩ (absConfig names c).nodes).card = vs.length := by + rw [← List.length_map (f := names.id)] + apply CCF.Finset.length_eq_of_nodup_of_mem_iff + (CCF.Finset.nodup_of_sorted (CCF.Finset.sorted _)) + (nodup_map_named (fun a ha => idsNamed a ((mem a).mp ha).1) nodup) + intro n + rw [← CCF.Finset.mem_def, CCF.Finset.mem_inter] + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, List.mem_map] + constructor + · rintro ⟨⟨w, hw, rfl⟩, ⟨i, hi, e⟩⟩ + have hi' : i ∈ c.nodes.map Prod.fst := List.mem_map.mpr hi + obtain ⟨p, hp, rfl⟩ := hi + have same := named_inj (named p hp) (Wnamed w hw) e + exact ⟨w, (mem w).mpr ⟨same ▸ hi', hw⟩, rfl⟩ + · rintro ⟨v, hv, rfl⟩ + obtain ⟨hi, hw⟩ := (mem v).mp hv + obtain ⟨p, hp, rfl⟩ := List.mem_map.mp hi + exact ⟨⟨p.1, hw, rfl⟩, ⟨p.1, ⟨p, hp, rfl⟩, rfl⟩⟩ + apply Bool.eq_iff_iff.mpr + simp only [decide_eq_true_eq] + unfold hasConfigurationMajority State.quorum + rw [nodes, inter] + omega + +theorem all_zip {α β : Type} {p : α -> Bool} {q : β -> Bool} + : forall {as : List α} {bs : List β}, + as.length = bs.length + -> (forall a b, (a, b) ∈ as.zip bs -> p a = q b) + -> as.all p = bs.all q + | [], [], _, _ => rfl + | a :: as, b :: bs, hl, h => by + simp only [List.all_cons] + rw [h a b (by simp), all_zip (as := as) (by simpa using hl) + fun x y m => h x y (List.mem_cons_of_mem _ m)] + +theorem all_majority_congr {names : Names} (V : CCF.Finset NodeID) + : forall {D E : List Config}, + D.map (·.nodes) = E.map (·.nodes) + -> (D.map (absConfig names)).all (fun c => decide (hasConfigurationMajority V c)) + = (E.map (absConfig names)).all + (fun c => decide (hasConfigurationMajority V c)) + | [], [], _ => rfl + | x :: D, y :: E, h => by + simp only [List.map_cons, List.cons.injEq] at h + simp only [List.map_cons, List.all_cons] + rw [all_majority_congr V h.2] + simp only [absConfig, hasConfigurationMajority, h.1] + rfl + +theorem shifted_nodes {ci : Nat} {D E : List Config} + (sh : ReplUpdateCommit.Shifted ci D E) + : D.map (·.nodes) = E.map (·.nodes) := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, nodes, -⟩ + · rfl + · simp [nodes] + +/-- `record_vote`'s result is the clean quorum of the tallied voters. -/ +theorem quorum_tally {names : Names} {cs D : List Config} {votes : List VoteRec} + {W : List NodeId} (t : Tally cs votes W) + (named : forall x, x ∈ cs -> forall a, a ∈ x.nodes -> Named names a.1) + (Wnamed : forall w, w ∈ W -> Named names w) + (distinct : forall x, x ∈ cs -> (x.nodes.map Prod.fst).Nodup) + (nodesEq : D.map (·.nodes) = cs.map (·.nodes)) + : (!cs.isEmpty && votes.all fun r => decide (r.2.1.length >= r.2.2)) + = decide (hasQuorum (D.map (absConfig names)) (names.set W)) := by + have all : (votes.all fun r => decide (r.2.1.length >= r.2.2)) + = (cs.map (absConfig names)).all + (fun c => decide (hasConfigurationMajority (names.set W) c)) := by + rw [List.all_map] + apply all_zip t.1 + intro r c mem + obtain ⟨-, hq, nd, hm⟩ := t.2 r c mem + have hc := (List.of_mem_zip mem).2 + rw [hq] + exact majority_tally (named c hc) Wnamed (distinct c hc) nd hm + have len : D.length = cs.length := by + rw [← List.length_map (f := (·.nodes)), nodesEq, List.length_map] + apply Bool.eq_iff_iff.mpr + rw [all, ← all_majority_congr _ nodesEq] + simp only [Bool.and_eq_true, Bool.not_eq_true', List.isEmpty_eq_false_iff, decide_eq_true_eq, + ne_eq] + constructor + · rintro ⟨ne, h⟩ + refine ⟨fun e => ne (List.eq_nil_of_length_eq_zero ?_), h⟩ + have := congrArg List.length e + rw [List.length_map, len] at this + exact this + · rintro ⟨ne, h⟩ + exact ⟨fun e => ne (List.eq_nil_of_length_eq_zero (by rw [List.length_map, len, e]; rfl)), h⟩ + +/-- The voters a (pre-)candidate has tallied: itself and every recorded vote. -/ +def voters (d : State) : List NodeId := d.nodeId :: d.votesForMe.flatMap (·.2.1) + +/-- A (pre-)candidate's vote records tally its voters (`inv`'s `votes_for_me`). -/ +theorem tally_of_inv {names : Names} {d : State} (h : inv names d = true) + (cand : d.leadership = .candidate \/ d.leadership = .preVoteCandidate) + : Tally d.configurations d.votesForMe (voters d) := by + have hc : (!(d.leadership == .candidate || d.leadership == .preVoteCandidate) + || (d.votesForMe.length == d.configurations.length + && (d.votesForMe.zip d.configurations).all + fun (r, c) => + let members := (c.nodes.map Prod.fst).filter (voters d).contains + r.1 == c.idx + && r.2.2 == State.quorum c.nodes.length + && r.2.1.eraseDups == r.2.1 + && r.2.1.all members.contains + && members.all r.2.1.contains)) = true := by + inv_conj h "votes_for_me" + have hl : (d.leadership == .candidate || d.leadership == .preVoteCandidate) = true := by + rcases cand with e | e <;> simp [e] + rw [hl] at hc + simp only [Bool.not_true, Bool.false_or, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] + at hc + refine ⟨hc.1, fun r c mem => ?_⟩ + obtain ⟨⟨⟨⟨hi, hq⟩, hd⟩, h1⟩, h2⟩ := hc.2 (r, c) mem + refine ⟨ + hi, + hq, + ReplUpdateCommit.nodup_of_eraseDups_eq hd, + fun x => ⟨fun m => ?_, fun m => ?_⟩ + ⟩ + · have := h1 x m + simp only [List.contains_iff_mem, List.mem_filter] at this + exact this + · have := h2 x (by simp only [List.mem_filter, List.contains_iff_mem]; exact m) + simpa using this + +theorem mem_flat_tally {cs : List Config} {votes : List VoteRec} {W : List NodeId} + (t : Tally cs votes W) {x : NodeId} + : x ∈ votes.flatMap (·.2.1) + <-> x ∈ W /\ exists c, c ∈ cs /\ x ∈ c.nodes.map Prod.fst := by + rw [List.mem_flatMap] + constructor + · rintro ⟨r, mr, mx⟩ + obtain ⟨i, hi, rfl⟩ := List.getElem_of_mem mr + have hc : i < cs.length := t.1 ▸ hi + have mem : (votes[i], cs[i]) ∈ votes.zip cs := by + rw [List.mem_iff_getElem] + exact ⟨i, by simp only [List.length_zip]; omega, by simp⟩ + obtain ⟨-, -, -, hm⟩ := t.2 _ _ mem + exact ⟨((hm x).mp mx).2, cs[i], List.getElem_mem hc, ((hm x).mp mx).1⟩ + · rintro ⟨w, c, mc, mx⟩ + obtain ⟨r, mem⟩ := exists_zip_right t.1 c mc + exact ⟨r, (List.of_mem_zip mem).1, ((t.2 r c mem).2.2.2 x).mpr ⟨mx, w⟩⟩ + +theorem set_congr {names : Names} {l m : List NodeId} (h : forall x, x ∈ l <-> x ∈ m) + : names.set l = names.set m := by + apply CCF.Finset.ext + intro a + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] + exact ⟨fun ⟨x, hx, e⟩ => ⟨x, (h x).mp hx, e⟩, fun ⟨x, hx, e⟩ => ⟨x, (h x).mpr hx, e⟩⟩ + +/-- After `record_vote from_` by a voter in a configuration, the voters gained `from_`. -/ +theorem voters_record {d : State} {from_ : NodeId} + (t : Tally d.configurations d.votesForMe (voters d)) + (sorted : d.configurations.Pairwise fun a b => a.idx < b.idx) + (member : exists c, c ∈ d.configurations /\ from_ ∈ c.nodes.map Prod.fst) + : forall x, + x ∈ voters { d with votesForMe := recorded from_ d } + <-> x ∈ from_ :: voters d := by + have t' := tally_record from_ t sorted + intro x + have old := fun x => (mem_flat_tally (x := x) t).mp + have new := fun x => mem_flat_tally (x := x) t' + simp only [voters, recorded, List.mem_cons] at old new ⊢ + rw [new] + constructor + · rintro (rfl | ⟨w, -⟩) + · exact Or.inr (Or.inl rfl) + · exact w + · rintro (rfl | rfl | w) + · exact Or.inr ⟨Or.inl rfl, member⟩ + · exact Or.inl rfl + · exact Or.inr ⟨Or.inr (Or.inr w), (old x w).2⟩ + +theorem lookup_isSome {β : Type} {l : List (NodeId × β)} {k : NodeId} + : (l.lookup k).isSome = true <-> exists p, p ∈ l /\ p.1 = k := by + induction l with + | nil => simp + | cons p l ih => + obtain ⟨a, b⟩ := p + simp only [List.lookup_cons] + by_cases e : k = a + · subst e + simp + · have : (k == a) = false := beq_false_of_ne e + simp only [this, ih, List.mem_cons] + constructor + · rintro ⟨q, mq, eq⟩ + exact ⟨q, Or.inr mq, eq⟩ + · rintro ⟨q, rfl | mq, eq⟩ + · exact absurd eq.symm e + · exact ⟨q, mq, eq⟩ + +/-- +An initialised node knows a peer exactly when the clean node has it as an eligible peer +(`inv`'s `peers` conjuncts, and `empty_ledger_alone` for an empty ledger). +-/ +theorem peer_iff_eligible {names : Names} {d : State} (h : inv names d = true) + (init : initialised d = true) {source : NodeID} + (hs : names.id (names.name source) = source) + : (d.peer? (names.name source)).isSome = true + <-> source ∈ eligiblePeers (abs names d) (names.id d.nodeId) := by + unfold State.peer? + rw [lookup_isSome] + by_cases L0 : d.lastIdx = 0 + · have alone : (d.currentView == 0 && d.leadership == .none) || d.lastIdx != 0 + || d.allOtherNodes.isEmpty := by + inv_conj h "empty_ledger_alone" + have commit : d.commitIdx = 0 := by have := (inv_parts h).2.1; omega + have empty := eligiblePeers_empty (s := abs names d) (by simp [abs, L0]) commit + (names.id d.nodeId) + unfold initialised at init + simp only [bne_iff_ne, ne_eq, Bool.or_eq_true] at init + simp only [Bool.or_eq_true, Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, L0, + not_true_eq_false, or_false, List.isEmpty_iff] at alone + have none : d.allOtherNodes = [] := by + rcases alone with ⟨a, b⟩ | a + · rcases init with i | i <;> contradiction + · exact a + rw [none, ← CCF.Finset.mem_sort, empty] + simp + · have eq : d.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (abs names d) (names.id d.nodeId)).sort := by + have p1 : (d.lastIdx == 0 || d.leadership == .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names d) (names.id d.nodeId)).sort) = true := by + inv_conj h "peers" + have p2 : (d.lastIdx == 0 || d.leadership != .none + || d.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names d) (names.id d.nodeId)).sort) = true := by + inv_conj h "peers_without_role" + simp only [Bool.or_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, L0, false_or] at p1 p2 + by_cases r : d.leadership = .none + · simpa [r] using p2 + · simpa [r] using p1 + have named := (ReplUpdateCommit.Hyps.ofInv h).peersNamed + rw [← CCF.Finset.mem_sort, ← eq, List.mem_map] + constructor + · rintro ⟨p, mp, e⟩ + exact ⟨p, mp, by rw [e, hs]⟩ + · rintro ⟨p, mp, e⟩ + refine ⟨p, mp, ?_⟩ + rw [← named p mp, e] + +end Consensus.TraceValidation.Proofs.Vote From 98274d6b8b4c27745fd4b13f5393fc335995fac4 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:17 +0000 Subject: [PATCH 12/25] Prove the AppendEntriesResponse and nomination obligations A leader's handling of an AppendEntries response (match and sent index updates, commit, retirement and successor nomination) and the nomination trace point refine the clean steps. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 1 + .../Proofs/Handlers/AeRespClean.lean | 125 +++++ .../Proofs/Handlers/AeRespCommit.lean | 523 ++++++++++++++++++ .../Proofs/Handlers/AeRespMain.lean | 265 +++++++++ .../Proofs/Handlers/AeRespPeers.lean | 211 +++++++ .../Proofs/Handlers/AeRespStep.lean | 364 ++++++++++++ .../Proofs/Handlers/AeRespSuccessor.lean | 489 ++++++++++++++++ .../Handlers/AppendEntriesResponse.lean | 406 ++++++++++++++ .../Proofs/Handlers/Nomination.lean | 159 ++++++ 9 files changed, 2543 insertions(+) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespClean.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespCommit.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespMain.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespPeers.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespStep.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespSuccessor.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntriesResponse.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Nomination.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 2f81d5d3d4e0..a9d6d3ccd7a7 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -6,6 +6,7 @@ public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks import Consensus.TraceValidation.Proofs.Handlers.AppendEntries +import Consensus.TraceValidation.Proofs.Handlers.AppendEntriesResponse import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespClean.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespClean.lean new file mode 100644 index 000000000000..75b87e12f311 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespClean.lean @@ -0,0 +1,125 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespPeers +public import Consensus.TraceValidation.Proofs.Handlers.AeClean + +@[expose] public section + +/-! +# Clean-side facts for the AppendEntries response (not reviewed) + +`highestCommittableIndex` reads the match indexes of the active members other than the node +only (`hc_congr`); every eligible peer is a member of a configuration of the log +(`eligible_mem_history`); and `agrees` unpacked into its fields (`Agrees`). +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open Consensus.Model.Node +open Consensus.TraceValidation (Names abs absRole agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) + +theorem mem_configurationMembers_iff {cs : List Configuration} {n : NodeID} + : n ∈ configurationMembers cs <-> exists x, x ∈ cs /\ n ∈ x.nodes := by + constructor + · unfold configurationMembers + have general : forall (cs : List Configuration) (acc : CCF.Finset NodeID), + n ∈ cs.foldl (fun nodes configuration => nodes ∪ configuration.nodes) acc + -> n ∈ acc \/ exists x, x ∈ cs /\ n ∈ x.nodes := by + intro cs + induction cs with + | nil => intro acc h; exact Or.inl h + | cons y cs ih => + intro acc h + rcases ih _ h with h | ⟨x, mem, member⟩ + · rcases CCF.Finset.mem_union.mp h with h | h + · exact Or.inl h + · exact Or.inr ⟨y, List.mem_cons_self, h⟩ + · exact Or.inr ⟨x, List.mem_cons_of_mem _ mem, member⟩ + intro h + rcases general cs ∅ h with h | h + · exact absurd h (CCF.Finset.notMem_empty _) + · exact h + · rintro ⟨x, mem, member⟩ + exact ReplUpdateCommit.mem_configurationMembers mem member + +/-- Every eligible peer is a member of a configuration of the log. -/ +theorem eligible_mem_history {st : NodeState} {self n : NodeID} + (h : n ∈ eligiblePeers st self) + : n ∈ configurationMembers (configurationHistory st.log) := by + unfold eligiblePeers at h + rcases CCF.Finset.mem_union.mp (CCF.Finset.mem_erase.mp h).2 with h | h + · obtain ⟨x, mem, member⟩ := mem_configurationMembers_iff.mp h + exact mem_configurationMembers_iff.mpr ⟨x, List.mem_of_mem_drop mem, member⟩ + · unfold NodeState.retirementCompletedNodes at h + have h := (CCF.Finset.mem_sdiff.mp (CCF.Finset.mem_sdiff.mp h).1).1 + obtain ⟨x, mem, member⟩ := mem_configurationMembers_iff.mp h + refine mem_configurationMembers_iff.mpr ⟨x, ?_, member⟩ + exact (Ae.configurationHistory_prefix (List.take_prefix _ _)).subset mem + +/-- +`highestCommittableIndex` depends on the match indexes of the active members other than the +node only. +-/ +theorem hc_congr {a b : NodeState} {self : NodeID} (hl : a.log = b.log) + (hc : a.commitIndex = b.commitIndex) (ht : a.currentTerm = b.currentTerm) + (hm : forall n, n ∈ a.activeMembers -> n ≠ self -> a.matchIndex n = b.matchIndex n) + : highestCommittableIndex a self = highestCommittableIndex b self := by + have members : a.activeMembers = b.activeMembers := by + unfold NodeState.activeMembers NodeState.activeConfigurations + rw [hl, hc] + have rep : forall index : Nat, + a.activeMembers.filter (fun node => node = self \/ a.matchIndex node >= index) + = b.activeMembers.filter (fun node => node = self \/ b.matchIndex node >= index) := by + intro index + apply CCF.Finset.ext + intro n + rw [CCF.Finset.mem_filter, CCF.Finset.mem_filter, ← members] + constructor + · rintro ⟨mem, h⟩ + refine ⟨mem, ?_⟩ + by_cases e : n = self + · exact Or.inl e + · rw [← hm n mem e]; exact h + · rintro ⟨mem, h⟩ + refine ⟨mem, ?_⟩ + by_cases e : n = self + · exact Or.inl e + · rw [hm n mem e]; exact h + unfold highestCommittableIndex + simp only [rep, hl, hc, ht] + +/-- `agrees`, field by field. -/ +structure Agrees (names : Names) (c : NodeState) (d : State) : Prop where + role : c.role = absRole d.leadership + term : c.currentTerm = d.currentView + log : c.log = (abs names d).log + commit : c.commitIndex = d.commitIdx + sent : forall n, n ∈ trackedPeers names d -> c.sentIndex n = (abs names d).sentIndex n + match_ + : forall n, n ∈ trackedPeers names d -> c.matchIndex n = (abs names d).matchIndex n + newFollower : c.isNewFollower = d.isNewFollower + voted : c.votedFor = d.votedFor.map names.id + known : c.primaryKnown = d.leaderId.isSome + rci : c.retiredCommittedIndex = d.retiredCommittedIdx + +theorem Agrees.of {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : Agrees names c d := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, h5⟩, h6⟩, h7⟩, h8⟩, -⟩, -⟩, h11⟩ := h + exact ⟨h1, h2, h3, h4, fun n m => (h5 n m).1, fun n m => (h5 n m).2, h6, h7, h8, h11⟩ + +theorem Agrees.to {names : Names} {c : NodeState} {d : State} (h : Agrees names c d) + (nc : d.leadership ≠ .candidate /\ d.leadership ≠ .preVoteCandidate) + : agrees names c d = true := by + obtain ⟨h1, h2, h3, h4, h5, h6, h7, h8, h9, h11⟩ := h + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] + refine ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, fun n m => by simp [h5 n m, h6 n m]⟩, h7⟩, h8⟩, h9⟩, + ?_⟩, ?_⟩, h11⟩ <;> + cases hl : d.leadership <;> simp_all [abs, absRole] + +end Consensus.TraceValidation.Proofs.AeResp diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespCommit.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespCommit.lean new file mode 100644 index 000000000000..b322980814e1 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespCommit.lean @@ -0,0 +1,523 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.Nomination +public import Consensus.TraceValidation.Proofs.Handlers.AeRespClean +public import Consensus.TraceValidation.Proofs.Handlers.AeHoare + +@[expose] public section + +/-! +# A leader's `commit` (not reviewed) + +`commit i` on a leader `v1` above its commit index sets the commit index and keeps the +node's term, ledger and votes (`Kept`). It either stays leader, sends nothing and keeps a +sub-collection of `v1`'s peers, or (when the node's own retirement commits) steps down +retired-committed, having nominated the successor that `find_successor` picks from `v1`'s +peers (`nominationSends`). M_tv checks that the successor cft.h picks after erasing the peers +retired-committed earlier in the same commit is that one. + +A retired-committed peer erased by the commit is not re-created by +`create_and_remove_node_state`: `inv` (`rc_entries_retired`) puts it outside the +configurations the commit keeps. +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open Consensus.Model.Node +open Consensus.TraceValidation (Names Env abs agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open Consensus.TraceValidation.Proofs.Ae (Hoare) + +/-! ## Configurations kept by a commit -/ + +theorem pop_suffix (i : Nat) : forall cs : List Config, Exec.commit.pop i cs <:+ cs + | [] => by rw [Exec.commit.pop.eq_def]; exact List.suffix_refl _ + | [c] => by rw [Exec.commit.pop.eq_def]; exact List.suffix_refl _ + | c :: n :: rest => by + rw [Exec.commit.pop.eq_1] + split + · exact List.suffix_refl _ + · exact (pop_suffix i (n :: rest)).trans (List.suffix_cons _ _) + +theorem pop_pop {ver i : Nat} (le : ver <= i) + : forall cs : List Config, + Exec.commit.pop i (Exec.commit.pop ver cs) = Exec.commit.pop i cs + | [] => by simp only [Exec.commit.pop.eq_def] + | [c] => by simp only [Exec.commit.pop.eq_def] + | c :: n :: rest => by + by_cases h : ver < n.idx + · simp only [Exec.commit.pop.eq_1 ver, h, ↓reduceIte] + · have h' : ¬ i < n.idx := by omega + simp only [Exec.commit.pop.eq_1 ver, h, Exec.commit.pop.eq_1 i, h', ↓reduceIte] + exact pop_pop le (n :: rest) + +/-- `id` is a member of a configuration of `cs`. -/ +def MemIn (cs : List Config) (id : Exec.NodeId) : Prop := + exists c, c ∈ cs /\ exists a, a ∈ c.nodes /\ a.1 = id + +theorem MemIn.suffix {cs ds : List Config} {id : Exec.NodeId} (h : cs <:+ ds) + (m : MemIn cs id) + : MemIn ds id := by + obtain ⟨c, mem, rest⟩ := m + exact ⟨c, h.subset mem, rest⟩ + +theorem MemIn.pop {ver i : Nat} (le : ver <= i) {cs : List Config} {id : Exec.NodeId} + (m : MemIn (Exec.commit.pop i cs) id) + : MemIn (Exec.commit.pop ver cs) id := by + rw [← pop_pop le] at m + exact m.suffix (pop_suffix _ _) + +theorem memIn_of_any {cs : List Config} {id : Exec.NodeId} + (h : (cs.any fun c => c.nodes.any fun a => a.1 == id) = true) + : MemIn cs id := by + simp only [List.any_eq_true, beq_iff_eq] at h + obtain ⟨c, mem, a, ma, e⟩ := h + exact ⟨c, mem, a, ma, e⟩ + +theorem memIn_active {cs : List Config} {id : Exec.NodeId} + (h + : id + ∈ ((cs.flatMap fun x => x.nodes.map Prod.fst).mergeSort + fun x1 x2 => decide (x1 <= x2)).eraseDups) + : MemIn cs id := by + rw [List.mem_eraseDups, List.mem_mergeSort, List.mem_flatMap] at h + obtain ⟨c, mem, h⟩ := h + obtain ⟨a, ma, e⟩ := List.mem_map.mp h + exact ⟨c, mem, a, ma, e⟩ + +theorem lookup_isSome {l : List (Exec.NodeId × Peer)} {p : Exec.NodeId × Peer} + (mem : p ∈ l) + : (l.lookup p.1).isSome = true := by + induction l with + | nil => cases mem + | cons q l ih => + rw [List.lookup_cons] + split + · rfl + · rcases List.mem_cons.mp mem with rfl | mem + · rename_i ne; simp at ne + · exact ih mem + +/-! ## The successor -/ + +theorem tvSuccessor_congr {v w : State} (h1 : v.allOtherNodes = w.allOtherNodes) + (h2 : v.configurations = w.configurations) + : tvSuccessor v = tvSuccessor w := by + have : tvStep v = tvStep w := by + funext acc p + simp only [tvStep, latestOf, h2] + simp only [tvSuccessor, this, h1] + +theorem nominationSends_congr {names : Names} {v w : State} (lv : v.leadership = .leader) + (lw : w.leadership = .leader) (hs : tvSuccessor v = tvSuccessor w) + (hn : v.nodeId = w.nodeId) (ht : v.currentView = w.currentView) + : nominationSends names v = nominationSends names w := by + simp only [nominationSends, lv, lw, hs, hn, ht, ↓reduceIte] + +/-! ## Hoare helpers -/ + +theorem hoare_assume {env : Env} {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} {φ : Prop} (imp : forall v o, P v o -> φ) + (h : φ -> Hoare env P x Q) + : Hoare env P x Q := + fun c a c' e p r => h (imp _ _ p) c a c' e p r + +theorem hoare_fail_bind {env : Env} {α β : Type} (m : String) {f : α -> M β} + {P : State -> Outbox -> Prop} {Q : β -> State -> Outbox -> Prop} + : Hoare env P (Exec.fail m >>= f) Q := + Hoare.bind (R := fun _ _ _ => False) (Hoare.fail m) + fun _ => Hoare.false_pre fun _ _ h => h + +theorem hoare_curLoc_fail {env : Env} {α β : Type} (m : String -> String) {f : α -> M β} + {P : State -> Outbox -> Prop} {Q : β -> State -> Outbox -> Prop} + : Hoare env P (Exec.curLoc >>= fun l => Exec.fail (m l) >>= f) Q := + Hoare.bind (Hoare.keeps Spec.curLoc fun _ _ _ h => h) fun _ => hoare_fail_bind _ + +/-! ## What a commit keeps -/ + +/-- The fields a commit keeps, and the commit index it sets. -/ +def Kept (v1 : State) (i : Nat) (w : State) : Prop := + w.nodeId = v1.nodeId + /\ w.currentView = v1.currentView + /\ w.ledger = v1.ledger + /\ w.lastIdx = v1.lastIdx + /\ w.isNewFollower = v1.isNewFollower + /\ w.votedFor = v1.votedFor + /\ w.commitIdx = i + +/-- +Still leader: nothing sent, the peers among `v1`'s, keeping every peer of `v1` that is a +member of `cs`. +-/ +def StillLeader (v1 : State) (cs : List Config) (o0 : Outbox) (w : State) (o : Outbox) + : Prop := + w.leadership = .leader + /\ w.leaderId = v1.leaderId + /\ o = o0 + /\ (forall p, p ∈ w.allOtherNodes -> p ∈ v1.allOtherNodes) + /\ (forall p, p ∈ v1.allOtherNodes -> MemIn cs p.1 -> p ∈ w.allOtherNodes) + +/-- Stepped down retired-committed, having nominated `v1`'s successor. -/ +def SteppedDown (names : Names) (v1 : State) (o0 : Outbox) (w : State) (o : Outbox) + : Prop := + w.leadership = .none + /\ w.leaderId = none + /\ w.isRetiredCommitted = true + /\ o = o0 ++ nominationSends names v1 + +/-- The invariant of the retired-committed records' processing. -/ +def CInv (env : Env) (v1 : State) (i : Nat) (o0 : Outbox) (w : State) (o : Outbox) + : Prop := + Kept v1 i w + /\ w.configurations = v1.configurations + /\ (StillLeader v1 (Exec.commit.pop i v1.configurations) o0 w o + \/ SteppedDown env.names v1 o0 w o) + +section +variable {env : Env} {v1 : State} {i : Nat} {o0 : Outbox} + +theorem becomeRetiredRC_spec (seqno : Nat) + : Spec env (Exec.becomeRetired seqno .retiredCommitted) + fun v o _ v' o' => + v' + = { + v with + leaderId := none, + leadership := .none, + retired := true, + retirementPhase := some .retiredCommitted + } + /\ o' = o ++ nominationSends env.names v := by + unfold Exec.becomeRetired + exact Spec.weaken + (Spec.bind nominateUnsafe_spec fun _ => Spec.bind (Spec.setV _) fun _ => Spec.setV _) + fun _ _ _ _ _ ⟨_, _, _, ⟨e1, f1⟩, _, _, _, ⟨e2, f2⟩, e3, f3⟩ => by + subst e1 f1 e2 f2 e3 f3 + exact ⟨rfl, rfl⟩ + +/-- The step down when the node's own retirement commits. -/ +def rcTail (seqno : Nat) : M (ForInStep PUnit) := do + Exec.setV fun v => { v with retiredCommittedIdx := some seqno } + Exec.becomeRetired seqno Exec.Phase.retiredCommitted + pure (ForInStep.yield PUnit.unit) + +def rcState (seqno : Nat) (v : State) : State := + { + v with + retiredCommittedIdx := some seqno, + leaderId := none, + leadership := .none, + retired := true, + retirementPhase := some .retiredCommitted + } + +theorem rcTail_spec (seqno : Nat) + : Spec env (rcTail seqno) + fun v o r v' o' => + r = .yield PUnit.unit + /\ v' = rcState seqno v + /\ o' + = o + ++ nominationSends env.names + { v with retiredCommittedIdx := some seqno } := + Spec.weaken + (Spec.bind (Spec.setV _) + fun _ => + Spec.bind (becomeRetiredRC_spec seqno) fun _ => Spec.pure _) + fun _ _ _ _ _ ⟨_, _, _, ⟨e1, f1⟩, _, _, _, ⟨e2, f2⟩, e3, e4, f3⟩ => by + subst e1 f1 e2 f2 e3 e4 f3 + exact ⟨rfl, rfl, rfl⟩ + +/-- One `set_retired_committed` record that the commit covers. -/ +theorem setRetiredCommitted_spec (env : Env) (lead : v1.leadership = .leader) + (seqno : Nat) (ids : List Exec.NodeId) + (hids + : forall id, + id ∈ ids -> id ≠ v1.nodeId -> ¬ MemIn (Exec.commit.pop i v1.configurations) id) + : Hoare env (CInv env v1 i o0) (Exec.setRetiredCommitted seqno ids v1.allOtherNodes) + fun _ => CInv env v1 i o0 := by + unfold Exec.setRetiredCommitted + refine Hoare.bind + (Hoare.forIn_list ids PUnit.unit _ (fun _ _ => CInv env v1 i o0) + (fun _ => CInv env v1 i o0) ?_ fun _ _ _ h => h) + fun _ => Hoare.pure _ fun _ _ h => h + intro pre a rest _ hl + have mem : a ∈ ids := by simp [hl] + refine Hoare.pin fun w o hw => ?_ + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := w = s) (fun _ _ h => h.1.1 ▸ h.2) fun e => ?_ + subst e + obtain ⟨kept, cfg, hw⟩ := hw + by_cases self : a = w.nodeId + · subst self + simp only [beq_self_eq_true, ↓reduceIte] + refine Hoare.ite (fun _ => ?_) (fun _ => hoare_curLoc_fail _) + have done : forall o', o' = o0 ++ nominationSends env.names v1 + -> CInv env v1 i o0 (rcState seqno w) o' := + fun o' e => ⟨kept, cfg, Or.inr ⟨rfl, rfl, rfl, e⟩⟩ + refine Hoare.ite (fun hl => ?_) (fun hnl => ?_) + · have hl : w.leadership = .leader := by simpa using hl + obtain ⟨-, -, ho, -, -⟩ := hw.resolve_right fun d => by rw [d.1] at hl; cases hl + let w' := { w with allOtherNodes := v1.allOtherNodes } + refine Hoare.bind (R := fun a v o' => a = tvSuccessor w /\ v = w /\ o' = o) + (Hoare.of_spec findSuccessor_spec fun _ _ _ _ _ p r => by + obtain ⟨⟨rfl, rfl⟩, -⟩ := p; exact r) fun actual => ?_ + refine hoare_assume (fun _ _ p => p.1) fun ha => ?_ + refine Hoare.bind (R := fun _ v o' => v = w' /\ o' = o) + (Hoare.setV _ fun v o' p => by obtain ⟨_, rfl, rfl⟩ := p; exact ⟨rfl, rfl⟩) + fun _ => ?_ + refine Hoare.bind (R := fun b v o' => b = tvSuccessor w' /\ v = w' /\ o' = o) + (Hoare.of_spec findSuccessor_spec fun _ _ _ _ _ p r => by + obtain ⟨rfl, rfl⟩ := p; exact r) fun specified => ?_ + refine hoare_assume (fun _ _ p => p.1) fun hs => ?_ + refine Hoare.bind (R := fun _ v o' => v = w /\ o' = o) + (Hoare.setV _ fun _ _ p => ⟨rfl, p.2.2⟩) fun _ => ?_ + refine Hoare.ite (fun he => ?_) (fun _ => hoare_curLoc_fail _) + have he : actual = specified := by simpa using he + refine Hoare.of_spec (rcTail_spec seqno) fun _ _ _ _ _ p q => ?_ + obtain ⟨rfl, rfl⟩ := p + obtain ⟨rfl, rfl, rfl⟩ := q + refine done _ ?_ + rw [ho] + congr 1 + refine nominationSends_congr hl lead ?_ kept.1 kept.2.1 + exact (tvSuccessor_congr rfl rfl).trans + (ha.symm.trans (he.trans (hs.trans (tvSuccessor_congr rfl cfg)))) + · have hnl : w.leadership ≠ .leader := by simpa using hnl + obtain ⟨-, -, -, ho⟩ := hw.resolve_left fun st => hnl st.1 + refine Hoare.of_spec (rcTail_spec seqno) fun _ _ _ _ _ p q => ?_ + obtain ⟨⟨rfl, rfl⟩, -⟩ := p + obtain ⟨rfl, rfl, rfl⟩ := q + refine done _ ?_ + simp only [nominationSends, hnl, ↓reduceIte, List.append_nil, ho] + · have ne : (a == w.nodeId) = false := by simpa using self + simp only [ne, Bool.false_eq_true, ↓reduceIte] + refine Hoare.bind (Hoare.setV _ fun v o' p => ?_) fun _ => Hoare.pure _ fun _ _ h => h + obtain ⟨⟨rfl, rfl⟩, -⟩ := p + refine ⟨kept, cfg, ?_⟩ + rcases hw with ⟨l, li, ho, sub, keep⟩ | down + · refine Or.inl ⟨l, li, ho, fun p mp => sub p (List.mem_filter.mp mp).1, fun p mp m => ?_⟩ + refine List.mem_filter.mpr ⟨keep p mp m, ?_⟩ + have : p.1 ≠ a := fun e => hids a mem (kept.1 ▸ self) (e ▸ m) + simpa using this + · exact Or.inr down + +/-- The covered records, in order. -/ +theorem go_spec (env : Env) (lead : v1.leadership = .leader) + : forall l : List (Nat × List Exec.NodeId), + (forall e, + e ∈ l + -> e.1 <= i + -> forall id, + id ∈ e.2 + -> id ≠ v1.nodeId + -> ¬ MemIn (Exec.commit.pop e.1 v1.configurations) id) + -> Hoare env (CInv env v1 i o0) (Exec.storeCompact.go i v1.allOtherNodes l) + fun _ => CInv env v1 i o0 + | [], _ => by + rw [Exec.storeCompact.go.eq_def] + exact Hoare.pure _ fun _ _ h => h + | (ver, ids) :: rest, h => by + rw [Exec.storeCompact.go.eq_def] + dsimp only + refine Hoare.ite (fun le => ?_) (fun _ => Hoare.pure _ fun _ _ h => h) + exact Hoare.bind + (setRetiredCommitted_spec env lead ver ids fun id m ne mi => + h _ List.mem_cons_self le id m ne (MemIn.pop le mi)) + fun _ => go_spec env lead rest fun e m => h e (List.mem_cons_of_mem _ m) + +theorem storeCompact_spec (env : Env) (lead : v1.leadership = .leader) + (hrc + : forall e, + e ∈ v1.rcEntries + -> e.1 <= i + -> forall id, + id ∈ e.2 + -> id ≠ v1.nodeId + -> ¬ MemIn (Exec.commit.pop e.1 v1.configurations) id) + : Hoare env + (fun v o => + CInv env v1 i o0 v o + /\ v.allOtherNodes = v1.allOtherNodes + /\ v.rcEntries = v1.rcEntries) + (Exec.storeCompact i) fun _ => CInv env v1 i o0 := by + unfold Exec.storeCompact + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s.allOtherNodes = v1.allOtherNodes /\ s.rcEntries = v1.rcEntries) + (fun _ _ p => p.2 ▸ p.1.2) fun ⟨hp, hr⟩ => ?_ + refine Hoare.getV_bind fun s' => ?_ + refine hoare_assume (φ := s' = s) (fun _ _ p => p.2.symm.trans p.1.2) fun e => ?_ + subst e + rw [hp, hr] + exact Hoare.bind (Hoare.pre (go_spec env lead _ hrc) fun _ _ p => p.1.1.1) + fun _ => Hoare.setV _ fun _ _ h => h + +/-- After the configurations are popped. -/ +def RInv (env : Env) (v1 : State) (i : Nat) (o0 : Outbox) (w : State) (o : Outbox) + : Prop := + Kept v1 i w + /\ w.configurations = Exec.commit.pop i v1.configurations + /\ (StillLeader v1 (Exec.commit.pop i v1.configurations) o0 w o + \/ SteppedDown env.names v1 o0 w o) + +/-- `id` of a configuration of `v1` other than the node is one of its peers. -/ +def Cover (v1 : State) : Prop := + forall id, + MemIn v1.configurations id + -> id ≠ v1.nodeId + -> exists p, p ∈ v1.allOtherNodes /\ p.1 = id + +theorem createAndRemove_spec (env : Env) (cover : Cover v1) + : Hoare env (RInv env v1 i o0) Exec.createAndRemoveNodeState + fun _ => RInv env v1 i o0 := by + unfold Exec.createAndRemoveNodeState + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume + (φ := s.configurations = Exec.commit.pop i v1.configurations /\ s.nodeId = v1.nodeId) + (fun _ _ p => p.2 ▸ ⟨p.1.2.1, p.1.1.1⟩) fun ⟨hc, hn⟩ => ?_ + refine Hoare.bind + (Hoare.pre + (Hoare.forIn_list _ PUnit.unit _ (fun _ _ => RInv env v1 i o0) + (fun _ => RInv env v1 i o0) ?_ fun _ _ _ h => h) + fun _ _ p => p.1) + fun _ => Hoare.pure _ fun _ _ h => h + intro pre a rest _ hl + have mi : MemIn (Exec.commit.pop i v1.configurations) a := by + rw [← hc] + exact memIn_active (by rw [hl]; simp) + refine Hoare.pin fun w o hw => ?_ + have same : forall v o', (v = w /\ o' = o) -> RInv env v1 i o0 v o' := by + rintro _ _ ⟨rfl, rfl⟩ + exact hw + refine Hoare.ite (fun _ => Hoare.pure _ same) fun ne => ?_ + have ne : a ≠ v1.nodeId := by + rw [← hn] + simpa using ne + refine Hoare.getV_bind fun t => ?_ + refine hoare_assume (φ := t = w) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + refine Hoare.ite (fun hnone => ?_) fun _ => Hoare.pure _ fun _ _ p => same _ _ p.1 + have down : SteppedDown env.names v1 o0 t o := hw.2.2.resolve_left fun st => by + obtain ⟨p, mp, e⟩ := cover a (mi.suffix (pop_suffix _ _)) ne + have := lookup_isSome (st.2.2.2.2 p mp (e ▸ mi)) + rw [e] at this + simp only [State.peer?, Option.isNone_iff_eq_none] at hnone + rw [hnone] at this + cases this + refine Hoare.bind + (R := + fun _ v o' => v = t.setPeer a { sentIdx := t.lastIdx + 1, matchIdx := 0 } /\ o' = o) + (Hoare.setV _ fun _ _ p => by obtain ⟨⟨rfl, rfl⟩, -⟩ := p; exact ⟨rfl, rfl⟩) + fun _ => ?_ + have post : forall v o', (v = t.setPeer a { sentIdx := t.lastIdx + 1, matchIdx := 0 } + /\ o' = o) -> RInv env v1 i o0 v o' := by + rintro _ _ ⟨rfl, rfl⟩ + exact ⟨hw.1, hw.2.1, Or.inr down⟩ + refine Hoare.ite (fun hl => ?_) fun _ => Hoare.pure _ post + rw [down.1] at hl + cases hl + +theorem commitTail_spec (env : Env) (lead : v1.leadership = .leader) (cover : Cover v1) + (hrc + : forall e, + e ∈ v1.rcEntries + -> e.1 <= i + -> forall id, + id ∈ e.2 + -> id ≠ v1.nodeId + -> ¬ MemIn (Exec.commit.pop e.1 v1.configurations) id) + : Hoare env + (fun v o => + CInv env v1 i o0 v o + /\ v.allOtherNodes = v1.allOtherNodes + /\ v.rcEntries = v1.rcEntries) + (do + Exec.storeCompact i + let l ← Exec.getV + if (List.length (Exec.commit.pop i l.configurations) != l.configurations.length) + = true then do + Exec.setV + fun v => { v with configurations := Exec.commit.pop i l.configurations } + Exec.createAndRemoveNodeState + else + pure ()) + fun _ => RInv env v1 i o0 := by + refine Hoare.bind (storeCompact_spec env lead hrc) fun _ => ?_ + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s.configurations = v1.configurations) + (fun _ _ p => p.2 ▸ p.1.2.1) fun hc => ?_ + rw [hc] + refine Hoare.ite (fun _ => ?_) fun hlen => ?_ + · refine Hoare.bind (Hoare.setV _ fun v o p => ?_) fun _ => createAndRemove_spec env cover + obtain ⟨⟨kept, -, h⟩, rfl⟩ := p + exact ⟨kept, rfl, h⟩ + · have e : Exec.commit.pop i v1.configurations = v1.configurations := + (pop_suffix _ _).eq_of_length (by simpa using hlen) + refine Hoare.pure _ fun v o p => ?_ + obtain ⟨⟨kept, cfg, h⟩, rfl⟩ := p + exact ⟨kept, cfg.trans e.symm, h⟩ + +theorem becomeRetiredCompleted_spec (seqno : Nat) + : Spec env (Exec.becomeRetired seqno .completed) + fun v o _ v' o' => + v' = { v with retired := true, retirementPhase := some .completed } + /\ o' = o := by + unfold Exec.becomeRetired + exact Spec.setV _ + +/-- +`commit i` by a leader `v1` between its commit and last indexes: the commit index set and the +configurations popped, either still leader with nothing sent and some of its peers, keeping +every peer the kept configurations name, or stepped down retired-committed having nominated +`v1`'s successor. +-/ +theorem commit_spec (env : Env) (lead : v1.leadership = .leader) (lt : v1.commitIdx < i) + (le : i <= v1.lastIdx) (cover : Cover v1) + (hrc + : forall e, + e ∈ v1.rcEntries + -> e.1 <= i + -> forall id, + id ∈ e.2 + -> id ≠ v1.nodeId + -> ¬ MemIn (Exec.commit.pop e.1 v1.configurations) id) + : Hoare env (fun v o => v = v1 /\ o = o0) (Exec.commit i) + fun _ => RInv env v1 i o0 := by + unfold Exec.commit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = v1) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + simp only [show ¬ i > s.lastIdx by omega, show ¬ i <= s.commitIdx by omega, ↓reduceIte] + refine Hoare.bind (Hoare.keeps (Spec.trace _) fun _ _ _ h => h) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.emitNat _ _) fun _ _ _ h => h) fun _ => ?_ + refine Hoare.bind (Q := fun _ => RInv env s i o0) + (R := fun _ v o => (CInv env s i o0 v o /\ v.allOtherNodes = s.allOtherNodes + /\ v.rcEntries = s.rcEntries) /\ v.leadership = .leader) + (Hoare.setV _ fun v o p => ?_) fun _ => ?_ + · obtain ⟨⟨e, f⟩, -⟩ := p + rw [e, f] + exact ⟨⟨⟨⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩, rfl, + Or.inl ⟨lead, rfl, rfl, fun _ m => m, fun _ m _ => m⟩⟩, rfl, rfl⟩, lead⟩ + refine Hoare.getV_bind fun t => ?_ + have tail := Hoare.pre (commitTail_spec env lead cover hrc (o0 := o0)) + (P := fun v o => ((CInv env s i o0 v o /\ v.allOtherNodes = s.allOtherNodes + /\ v.rcEntries = s.rcEntries) /\ v.leadership = .leader) /\ v = t) fun _ _ p => p.1.1 + refine Hoare.ite (fun _ => ?_) fun _ => tail + split + · refine Hoare.ite (fun _ => ?_) fun _ => tail + refine Hoare.bind (Hoare.of_spec (becomeRetiredCompleted_spec i) fun v o _ v' o' p q => ?_) + fun _ => commitTail_spec env lead cover hrc + obtain ⟨⟨⟨⟨kept', cfg, h⟩, hp, hr⟩, hl⟩, -⟩ := p + obtain ⟨rfl, rfl⟩ := q + refine ⟨⟨kept', cfg, ?_⟩, hp, hr⟩ + rcases h with ⟨h1, h2, h3, h4, h5⟩ | h + · exact Or.inl ⟨h1, h2, h3, h4, h5⟩ + · exact absurd (h.1.symm.trans hl) (by decide) + · exact tail + +end + +end Consensus.TraceValidation.Proofs.AeResp diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespMain.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespMain.lean new file mode 100644 index 000000000000..4bbab474cff9 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespMain.lean @@ -0,0 +1,265 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespStep + +@[expose] public section + +/-! +# The AppendEntries response: facts from `inv` (not reviewed) + +What `inv` gives of a leader's peers (`PeerCtx`), the hypotheses of `handler_spec` +(`cover_of_inv`, `rcRetired_of_inv`), a leader's unlatched retirement confirmation +(`leader_rci_none`), and agreement and `UnnamedUnmatched` after a peer's indexes change. +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp +open Consensus.Model.Node +open Consensus.TraceValidation (Names Env abs absRole agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (absConfig Named named_inj Hyps) + +theorem lookup_mem {l : List (Exec.NodeId × Peer)} {k : Exec.NodeId} {b : Peer} + (h : l.lookup k = some b) + : (k, b) ∈ l := by + obtain ⟨l1, l2, rfl, -⟩ := List.lookup_eq_some_iff.mp h + simp + +theorem abs_sentIndex_of_sorted {names : Names} {v : State} + (sorted : v.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1)) {p} + (mem : p ∈ v.allOtherNodes) + : (abs names v).sentIndex (names.id p.1) = p.2.sentIdx := by + simp only [abs] + rw [find_sorted names _ sorted p mem] + +theorem leader_nonempty {names : Names} {v : State} (h : inv names v = true) + (lead : v.leadership = .leader) {q : Exec.NodeId × Peer} (mem : q ∈ v.allOtherNodes) + : v.lastIdx ≠ 0 := by + intro L0 + have e : (v.lastIdx != 0 || v.leadership != .leader || v.allOtherNodes.isEmpty) = true := by + inv_conj h "empty_leader_alone" + simp [L0, lead] at e + rw [e] at mem + cases mem + +/-- What `inv` says of the peers of a leader with a nonempty ledger. -/ +structure PeerCtx (names : Names) (v : State) : Prop where + peersEq + : v.allOtherNodes.map (fun p => names.id p.1) + = (eligiblePeers (abs names v) (names.id v.nodeId)).sort + sortedId : v.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1) + sortedStr : v.allOtherNodes.Pairwise (fun p q => p.1 < q.1) + +theorem peerCtx {names : Names} {v : State} (h : inv names v = true) + (lead : v.leadership = .leader) (L0 : v.lastIdx ≠ 0) + : PeerCtx names v := by + have peersEq : v.allOtherNodes.map (fun p => names.id p.1) + = (eligiblePeers (abs names v) (names.id v.nodeId)).sort := by + have e := ReplUpdateCommit.inv_conjunct h "peers" + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at e + simpa [L0, lead] using e + have sortedId : v.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1) := by + have := (eligiblePeers (abs names v) (names.id v.nodeId)).sorted + rw [← CCF.Finset.sort, ← peersEq, List.pairwise_map] at this + exact this + have sortedStr : v.allOtherNodes.Pairwise (fun p q => p.1 < q.1) := by + have e : ((v.allOtherNodes.zip v.allOtherNodes.tail).all + fun (x : (Exec.NodeId × Peer) × (Exec.NodeId × Peer)) => decide (x.1.1 < x.2.1)) = true := by + inv_conj h "peers_sorted" + exact pairwise_of_zip_tail (r := fun p q : Exec.NodeId × Peer => p.1 < q.1) + (fun a b => String.lt_trans a b) _ e + exact ⟨peersEq, sortedId, sortedStr⟩ + +/-- A clean id is an eligible peer of a leader iff it is the id of one of its peers. -/ +theorem PeerCtx.eligible_iff {names : Names} {v : State} (pc : PeerCtx names v) + {n : NodeID} + : n ∈ eligiblePeers (abs names v) (names.id v.nodeId) + <-> exists p, p ∈ v.allOtherNodes /\ names.id p.1 = n := by + rw [← CCF.Finset.mem_sort, ← pc.peersEq, List.mem_map] + +theorem PeerCtx.inj {names : Names} {v : State} (pc : PeerCtx names v) + {x y : Exec.NodeId × Peer} (hx : x ∈ v.allOtherNodes) (hy : y ∈ v.allOtherNodes) + (e : names.id x.1 = names.id y.1) + : x = y := + pairwise_inj Nat.lt_irrefl (f := fun p : Exec.NodeId × Peer => names.id p.1) pc.sortedId + hx hy e + +/-- A leader's tracked peers include every eligible peer of an agreeing clean state. -/ +theorem tracked_of_eligible {names : Names} {v : State} {st : NodeState} + (pc : PeerCtx names v) (lead : v.leadership = .leader) (A : Agrees names st v) + {n : NodeID} (e : n ∈ eligiblePeers st (names.id v.nodeId)) + : n ∈ trackedPeers names v := by + rw [Ae.eligiblePeers_congr A.log A.commit, pc.eligible_iff] at e + obtain ⟨p, mem, rfl⟩ := e + simp only [trackedPeers, lead, beq_self_eq_true, ↓reduceIte, List.mem_map] + exact ⟨p, mem, rfl⟩ + +/-- `highestCommittableIndex` of an agreeing clean state, when its eligible peers are tracked. -/ +theorem hc_of_agrees {names : Names} {st : NodeState} {d : State} {self : NodeID} + (A : Agrees names st d) + (tracked : forall n, n ∈ eligiblePeers st self -> n ∈ trackedPeers names d) + : highestCommittableIndex st self = highestCommittableIndex (abs names d) self := + hc_congr A.log A.commit A.term + fun n mem ne => + A.match_ n + (tracked n (CCF.Finset.mem_erase.mpr ⟨ne, CCF.Finset.mem_union.mpr (Or.inl mem)⟩)) + +theorem trackedPeers_putPeer {names : Names} {v w : State} {id : Exec.NodeId} {p : Peer} + (hw : w.allOtherNodes = putPeer v.allOtherNodes id p) + (hl : w.leadership = v.leadership) + : trackedPeers names w = trackedPeers names v := by + have keys := congrArg (List.map names.id) (putPeer_keys v.allOtherNodes id p) + simp only [List.map_map] at keys + simp only [trackedPeers, hw, hl] + split + · exact keys + · rfl + +/-- Changing a leader's peer `id` changes its clean indexes at `names.id id` only. -/ +theorem agrees_setPeer {names : Names} {clean clean1 : NodeState} {saved : State} + {id : Exec.NodeId} {nd p : Peer} (A : Agrees names clean saved) + (pc : PeerCtx names saved) (mem : (id, nd) ∈ saved.allOtherNodes) + (role : clean1.role = clean.role) (term : clean1.currentTerm = clean.currentTerm) + (log : clean1.log = clean.log) (commit : clean1.commitIndex = clean.commitIndex) + (nf : clean1.isNewFollower = clean.isNewFollower) + (voted : clean1.votedFor = clean.votedFor) + (known : clean1.primaryKnown = clean.primaryKnown) + (rci : clean1.retiredCommittedIndex = clean.retiredCommittedIndex) + (mi + : clean1.matchIndex = CCF.Function.update clean.matchIndex (names.id id) p.matchIdx) + (si : clean1.sentIndex = CCF.Function.update clean.sentIndex (names.id id) p.sentIdx) + : Agrees names clean1 (saved.setPeer id p) := by + rw [setPeer_eq saved pc.sortedStr mem] + have inj : forall x, x ∈ saved.allOtherNodes -> names.id x.1 = names.id id -> x.1 = id := + fun x hx e => by rw [pc.inj hx mem e] + have keyMem : id ∈ saved.allOtherNodes.map Prod.fst := List.mem_map.mpr ⟨_, mem, rfl⟩ + obtain ⟨hm, hs⟩ := abs_putPeer (names := names) (v := saved) + (w := { saved with allOtherNodes := putPeer saved.allOtherNodes id p }) rfl inj keyMem + have tr := trackedPeers_putPeer (names := names) (v := saved) + (w := { saved with allOtherNodes := putPeer saved.allOtherNodes id p }) rfl rfl + refine ⟨role.trans A.role, term.trans A.term, log.trans A.log, commit.trans A.commit, + ?_, ?_, nf.trans A.newFollower, voted.trans A.voted, known.trans A.known, rci.trans A.rci⟩ + · intro n mem' + rw [tr] at mem' + rw [hs, si] + by_cases e : n = names.id id + · simp [CCF.Function.update, e] + · simp only [CCF.Function.update, e, ↓reduceIte] + exact A.sent n mem' + · intro n mem' + rw [tr] at mem' + rw [hm, mi] + by_cases e : n = names.id id + · simp [CCF.Function.update, e] + · simp only [CCF.Function.update, e, ↓reduceIte] + exact A.match_ n mem' + +/-- A leader with a peer covers every node of its configurations by a peer. -/ +theorem cover_of_inv {names : Names} {v : State} (h : inv names v = true) + (lead : v.leadership = .leader) (L0 : v.lastIdx ≠ 0) + : Cover v := by + have hy := Hyps.ofInv h + have pc := peerCtx h lead L0 + intro id ⟨c, memC, a, ma, ea⟩ ne + subst ea + obtain ⟨D, hD, sh⟩ := hy.configs (by omega) + obtain ⟨x', memD', nodes⟩ := ReplUpdateCommit.shifted_mem sh memC + have named := hy.membersNamed c memC a ma + have inAbs : names.id a.1 ∈ (absConfig names x').nodes := by + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, List.mem_map, nodes] + exact ⟨a.1, ⟨a, ma, rfl⟩, rfl⟩ + have active : names.id a.1 ∈ (abs names v).activeMembers := by + show names.id a.1 ∈ configurationMembers (activeConfigurations (abs names v).log v.commitIdx) + rw [hD] + exact ReplUpdateCommit.mem_configurationMembers (List.mem_map_of_mem memD') inAbs + have neId : names.id a.1 ≠ names.id v.nodeId := fun e => ne (named_inj named hy.selfNamed e) + have elig : names.id a.1 ∈ eligiblePeers (abs names v) (names.id v.nodeId) := + CCF.Finset.mem_erase.mpr ⟨neId, CCF.Finset.mem_union.mpr (Or.inl active)⟩ + obtain ⟨p, memP, e⟩ := pc.eligible_iff.mp elig + exact ⟨p, memP, named_inj (hy.peersNamed p memP) named e⟩ + +theorem cover_setPeer {v : State} {id : Exec.NodeId} {q p : Peer} + (sorted : v.allOtherNodes.Pairwise fun a b => a.1 < b.1) + (mem : (id, q) ∈ v.allOtherNodes) (cover : Cover v) + : Cover (v.setPeer id p) := by + rw [setPeer_eq v sorted mem] + intro n memN ne + obtain ⟨p', memP, e⟩ := cover n memN ne + have : n ∈ (putPeer v.allOtherNodes id p).map Prod.fst := by + rw [putPeer_keys] + exact List.mem_map.mpr ⟨p', memP, e⟩ + obtain ⟨p'', m, e'⟩ := List.mem_map.mp this + exact ⟨p'', m, e'⟩ + +theorem rcRetired_of_inv {names : Names} {v : State} (h : inv names v = true) + (lead : v.leadership = .leader) (i : Nat) + : RcRetired v i := by + have e : (v.leadership != .leader + || v.rcEntries.all fun (x : Nat × List Exec.NodeId) => + x.2.all fun id => id == v.nodeId + || !(Exec.commit.pop x.1 v.configurations).any (·.nodes.any (·.1 == id))) = true := by + inv_conj h "rc_entries_retired" + simp only [lead, bne_self_eq_false, Bool.false_or, List.all_eq_true, Bool.or_eq_true, + beq_iff_eq, Bool.not_eq_true'] at e + intro x memX _ id memId ne m + rcases e x memX id memId with e | e + · exact ne e + · obtain ⟨c, memC, a, ma, ea⟩ := m + have : ((Exec.commit.pop x.1 v.configurations).any fun c => c.nodes.any (·.1 == id)) = true := by + simp only [List.any_eq_true, beq_iff_eq] + exact ⟨c, memC, a, ma, ea⟩ + rw [e] at this + cases this + +/-- A leader has not latched its retirement confirmation. -/ +theorem leader_rci_none {names : Names} {v : State} (h : inv names v = true) + (lead : v.leadership = .leader) + : v.retiredCommittedIdx = none := by + have notRC : (v.leadership != .leader || !v.isRetiredCommitted) = true := by + inv_conj h "leader_not_retired_committed" + have rc : (v.isRetiredCommitted == decide ((abs names v).isRetiredCommitted (names.id v.nodeId))) + = true := by + inv_conj h "retired_committed" + have ret : (v.retiredCommittedIdx.all + fun j => (retirementIndexInLog (names.id v.nodeId) ((abs names v).log.take j)).isSome) = true := by + inv_conj h "rci_retired" + cases e : v.retiredCommittedIdx with + | none => rfl + | some j => + exfalso + rw [e] at ret + simp only [Option.all_some] at ret + have full := Ae.rii_prefix (List.take_prefix _ _) ret + have : (abs names v).isRetiredCommitted (names.id v.nodeId) := + (Ae.isRetiredCommitted_iff _ _).mpr ⟨full, by simp [abs, e]⟩ + simp only [lead, bne_self_eq_false, Bool.false_or, Bool.not_eq_true'] at notRC + simp [notRC, this] at rc + +/-- Raising the match index of a node of the log's configurations keeps `UnnamedUnmatched`. -/ +theorem unmatched_update {node : NodeID} {clean st : NodeState} + (u : UnnamedUnmatched node clean) (role : st.role = clean.role) + (log : st.log = clean.log) {src : NodeID} + (named : src ∈ configurationMembers (configurationHistory clean.log)) {x : Nat} + (mi : st.matchIndex = CCF.Function.update clean.matchIndex src x) + : UnnamedUnmatched node st := by + intro primary n ne notMem + rw [log] at notMem + have : n ≠ src := fun e => notMem (e ▸ named) + rw [mi] + simp only [CCF.Function.update, this, ↓reduceIte] + exact u (role ▸ primary) n ne notMem + +theorem localRun_of {env : Env} {node source : NodeID} {clean clean' : NodeState} + {r : AppendEntriesResponse} {out : CCF.Outputs NodeID Message Notification} + (h : cleanRun node source clean r = some (clean', out)) + : CCF.Sections.LocalRun (protocol env) node clean + (cleanActions env (some (source, .appendEntriesResponse r)) []) clean' + out.outgoing := by + have := CCF.Sections.LocalRun.cons (protocol := protocol env) (node := node) (state := clean) + (middle := clean') (action := (protocol env).receive source (.appendEntriesResponse r)) + (effects := out) h (CCF.Sections.LocalRun.nil _) + simpa [cleanActions] using this + +end Consensus.TraceValidation.Proofs.AeResp diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespPeers.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespPeers.lean new file mode 100644 index 000000000000..6052b401c7a2 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespPeers.lean @@ -0,0 +1,211 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespSuccessor + +@[expose] public section + +/-! +# Updating one peer (not reviewed) + +`State.setPeer` erases a peer, appends its new record and sorts by node id. On peers +strictly sorted by id (`inv` conjunct `peers_sorted`) that contain the peer, this replaces +the record in place (`setPeer_eq`), so the clean send and match indexes change at the peer +only (`abs_putPeer_matchIndex`, `abs_putPeer_sentIndex`). +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open Consensus.Model.Node +open Consensus.TraceValidation (Names abs agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (absConfig Named named_inj Hyps) + +/-- Replace the record of peer `id`. -/ +def putPeer (l : List (Exec.NodeId × Peer)) (id : Exec.NodeId) (p : Peer) + : List (Exec.NodeId × Peer) := + l.map fun q => if q.1 = id then (id, p) else q + +theorem putPeer_keys (l : List (Exec.NodeId × Peer)) (id : Exec.NodeId) (p : Peer) + : (putPeer l id p).map Prod.fst = l.map Prod.fst := by + unfold putPeer + rw [List.map_map] + apply List.map_congr_left + intro q _ + by_cases h : q.1 = id <;> simp [h] + +theorem pairwise_inj {β γ : Type} {r : γ -> γ -> Prop} (irrefl : forall x, ¬ r x x) + {f : β -> γ} {l : List β} + (sorted : l.Pairwise fun a b => r (f a) (f b)) {a b : β} (ha : a ∈ l) (hb : b ∈ l) + (e : f a = f b) + : a = b := by + induction l with + | nil => cases ha + | cons x l ih => + cases List.mem_cons.mp ha with + | inl ha => + cases List.mem_cons.mp hb with + | inl hb => rw [ha, hb] + | inr hb => + have := List.rel_of_pairwise_cons sorted hb + rw [← ha, e] at this + exact absurd this (irrefl _) + | inr ha => + cases List.mem_cons.mp hb with + | inl hb => + have := List.rel_of_pairwise_cons sorted ha + rw [← hb, e] at this + exact absurd this (irrefl _) + | inr hb => exact ih (List.Pairwise.of_cons sorted) ha hb + +theorem setPeer_perm {l : List (Exec.NodeId × Peer)} {id : Exec.NodeId} {q p : Peer} + (sorted : l.Pairwise fun a b => a.1 < b.1) (mem : (id, q) ∈ l) + : List.Perm (l.filter (·.1 != id) ++ [(id, p)]) (putPeer l id p) := by + obtain ⟨s, t, rfl⟩ := List.append_of_mem mem + have sorted' := List.pairwise_append.mp sorted + have notS : forall x, x ∈ s -> x.1 ≠ id := fun x hx e => by + have := sorted'.2.2 x hx (id, q) List.mem_cons_self + rw [e] at this + exact String.lt_irrefl _ this + have notT : forall x, x ∈ t -> x.1 ≠ id := fun x hx e => by + have := List.rel_of_pairwise_cons sorted'.2.1 hx + rw [e] at this + exact String.lt_irrefl _ this + have fs : s.filter (·.1 != id) = s := List.filter_eq_self.mpr fun x hx => by + simpa using notS x hx + have ft : t.filter (·.1 != id) = t := List.filter_eq_self.mpr fun x hx => by + simpa using notT x hx + have ps : putPeer s id p = s := by + unfold putPeer + conv => rhs; rw [← List.map_id s] + apply List.map_congr_left + intro x hx + simp [notS x hx] + have pt : putPeer t id p = t := by + unfold putPeer + conv => rhs; rw [← List.map_id t] + apply List.map_congr_left + intro x hx + simp [notT x hx] + have split : putPeer (s ++ (id, q) :: t) id p = s ++ (id, p) :: t := by + have : putPeer (s ++ (id, q) :: t) id p + = putPeer s id p ++ (id, p) :: putPeer t id p := by + simp [putPeer] + rw [this, ps, pt] + rw [split, List.filter_append, List.filter_cons, fs, ft] + simp only [bne_self_eq_false, Bool.false_eq_true, ↓reduceIte, List.append_assoc] + exact List.Perm.append_left s (by simp) + +theorem putPeer_sorted {l : List (Exec.NodeId × Peer)} {id : Exec.NodeId} {p : Peer} + {r : Exec.NodeId -> Exec.NodeId -> Prop} (sorted : l.Pairwise fun a b => r a.1 b.1) + : (putPeer l id p).Pairwise fun a b => r a.1 b.1 := by + have := putPeer_keys l id p + have h : (l.map Prod.fst).Pairwise r := List.pairwise_map.mpr sorted + rw [← this] at h + exact List.pairwise_map.mp h + +theorem setPeer_eq (v : State) {id : Exec.NodeId} {q p : Peer} + (sorted : v.allOtherNodes.Pairwise fun a b => a.1 < b.1) + (mem : (id, q) ∈ v.allOtherNodes) + : v.setPeer id p = { v with allOtherNodes := putPeer v.allOtherNodes id p } := by + suffices key : (v.allOtherNodes.filter (·.1 != id) ++ [(id, p)]).mergeSort + (fun a b => decide (a.1 <= b.1)) = putPeer v.allOtherNodes id p by + simp only [State.setPeer, key] + apply List.Perm.eq_of_pairwise (le := fun a b => (decide (a.1 <= b.1)) = true) + · intro a b ha hb ab ba + have ha' := (List.mergeSort_perm _ _).trans (setPeer_perm (p := p) sorted mem) |>.mem_iff.mp ha + have e : a.1 = b.1 := String.le_antisymm (by simpa using ab) (by simpa using ba) + exact pairwise_inj String.lt_irrefl (f := Prod.fst) (putPeer_sorted sorted) ha' hb e + · exact List.pairwise_mergeSort + (fun a b c hab hbc => by simp only [decide_eq_true_eq] at *; exact String.le_trans hab hbc) + (fun a b => by + rcases String.le_total a.1 b.1 with h | h <;> simp [h]) + _ + · exact (putPeer_sorted sorted).imp fun lt => by + simp only [decide_eq_true_eq] + exact String.not_lt.mp (String.lt_asymm lt) + · exact (List.mergeSort_perm _ _).trans (setPeer_perm sorted mem) + +/-- The `peers_sorted` conjunct as a pairwise relation. -/ +theorem pairwise_of_zip_tail {α : Type} {r : α -> α -> Prop} [DecidableRel r] + (trans : forall {a b c}, r a b -> r b c -> r a c) + : forall (l : List α), + ((l.zip l.tail).all fun (x : α × α) => decide (r x.1 x.2)) = true -> l.Pairwise r + | [], _ => List.Pairwise.nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: t, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true] at h + have ih := pairwise_of_zip_tail (r := r) trans (b :: t) h.2 + have hab := of_decide_eq_true h.1 + refine List.Pairwise.cons ?_ ih + intro x hx + rcases List.mem_cons.mp hx with rfl | hx + · exact hab + · exact trans hab (List.rel_of_pairwise_cons ih hx) + +theorem find_putPeer_ne (names : Names) {n : NodeID} {id : Exec.NodeId} (p : Peer) + (ne : n ≠ names.id id) + : forall (l : List (Exec.NodeId × Peer)), + (putPeer l id p).find? (fun (i, _) => names.id i == n) + = l.find? (fun (i, _) => names.id i == n) + | [] => rfl + | x :: l => by + have ih := find_putPeer_ne names p ne l + unfold putPeer at ih ⊢ + rw [List.map_cons, List.find?_cons, List.find?_cons, ih] + by_cases hx : x.1 = id + · have hne : (names.id id == n) = false := by + simp only [beq_eq_false_iff_ne]; exact fun e => ne e.symm + have hne' : (names.id x.1 == n) = false := by rw [hx]; exact hne + obtain ⟨a, b⟩ := x + simp only at hx hne' + simp only [hx, ↓reduceIte, hne] + · simp only [hx, ↓reduceIte] + +theorem find_putPeer_eq (names : Names) {id : Exec.NodeId} (p : Peer) + : forall (l : List (Exec.NodeId × Peer)), + (forall x, x ∈ l -> names.id x.1 = names.id id -> x.1 = id) + -> id ∈ l.map Prod.fst + -> (putPeer l id p).find? (fun (i, _) => names.id i == names.id id) = some (id, p) + | [], _, mem => by cases mem + | x :: l, inj, mem => by + unfold putPeer + rw [List.map_cons, List.find?_cons] + by_cases hx : x.1 = id + · simp [hx] + · have hne : (names.id x.1 == names.id id) = false := by + simp only [beq_eq_false_iff_ne] + exact fun e => hx (inj x List.mem_cons_self e) + have mem' : id ∈ l.map Prod.fst := by + rcases List.mem_cons.mp mem with e | m + · exact absurd e.symm hx + · exact m + have := find_putPeer_eq names p l (fun y hy => inj y (List.mem_cons_of_mem _ hy)) mem' + unfold putPeer at this + obtain ⟨a, b⟩ := x + simp only at hx hne + simp only [hx, ↓reduceIte, hne, this] + +/-- After `putPeer`, the clean send and match indexes change at the peer only. -/ +theorem abs_putPeer {names : Names} {v w : State} {id : Exec.NodeId} {p : Peer} + (hw : w.allOtherNodes = putPeer v.allOtherNodes id p) + (inj : forall x, x ∈ v.allOtherNodes -> names.id x.1 = names.id id -> x.1 = id) + (mem : id ∈ v.allOtherNodes.map Prod.fst) + : (abs names w).matchIndex + = CCF.Function.update (abs names v).matchIndex (names.id id) p.matchIdx + /\ (abs names w).sentIndex + = CCF.Function.update (abs names v).sentIndex (names.id id) p.sentIdx := by + constructor <;> funext n <;> simp only [abs, CCF.Function.update, hw] <;> + by_cases e : n = names.id id + all_goals first + | (subst e; rw [find_putPeer_eq names p _ inj mem]; simp) + | (rw [find_putPeer_ne names p e]; simp [e]) + +theorem update_self {α β : Type} [DecidableEq α] (f : α -> β) (a : α) + : CCF.Function.update f a (f a) = f := by + funext x + by_cases e : x = a <;> simp [CCF.Function.update, e] + +end Consensus.TraceValidation.Proofs.AeResp diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespStep.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespStep.lean new file mode 100644 index 000000000000..2092e9ff9fc6 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespStep.lean @@ -0,0 +1,364 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespCommit + +@[expose] public section + +/-! +# The AppendEntries response, step by step (not reviewed) + +`recv_append_entries_response` from a declared state in closed form (`handler_spec`, one +disjunct of `Outcome` per path), and the clean receive of the response +(`receive_ineligible`, `receive_notPrimary`, `receive_primary`, `handle_*`, `advance_run`). +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open Consensus.Model.Node +open Consensus.TraceValidation (Names Env abs agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open Consensus.TraceValidation.Proofs.Ae (Hoare) + +/-- The peer record after a success response. -/ +def ackPeer (node : Peer) (r : AppendEntriesResponse) : Peer := + { sentIdx := node.sentIdx, matchIdx := max node.matchIdx r.lastLogIndex } + +/-- The peer record after a NACK. -/ +def nackPeer (v : State) (node : Peer) (r : AppendEntriesResponse) : Peer := + { + sentIdx := + max (min (v.highestMatch r.term r.lastLogIndex) node.sentIdx) node.matchIdx, + matchIdx := node.matchIdx + } + +/-- What `recv_append_entries_response` does from `saved`. -/ +def Outcome (env : Env) (saved : State) (from_ : Exec.NodeId) (r : AppendEntriesResponse) + (v : State) (o : Outbox) + : Prop := + exists node, + saved.peer? from_ = some node + /\ ((saved.leadership ≠ .leader /\ v = saved /\ o = []) + \/ (saved.leadership = .leader + /\ saved.currentView < r.term + /\ v = Ae.bant r.term saved + /\ o = []) + \/ (saved.leadership = .leader + /\ r.term < saved.currentView + /\ r.success = true + /\ v = saved + /\ o = []) + \/ (saved.leadership = .leader + /\ r.term = saved.currentView + /\ r.success = true + /\ r.lastLogIndex < node.matchIdx + /\ v = saved + /\ o = []) + \/ (saved.leadership = .leader + /\ r.term <= saved.currentView + /\ r.success = false + /\ v = saved.setPeer from_ (nackPeer saved node r) + /\ o = []) + \/ (saved.leadership = .leader + /\ r.term = saved.currentView + /\ r.success = true + /\ node.matchIdx <= r.lastLogIndex + /\ exists res, + ReplUpdateCommit.updateCommitOf (saved.setPeer from_ (ackPeer node r)) 0 + none ((saved.setPeer from_ (ackPeer node r)).lastIdx + 2) + = .ok res + /\ ((res.getD saved.commitIdx <= saved.commitIdx + /\ v = saved.setPeer from_ (ackPeer node r) + /\ o = []) + \/ exists i, + res = some i + /\ saved.commitIdx < i + /\ i <= saved.lastIdx + /\ RInv env (saved.setPeer from_ (ackPeer node r)) i [] v o))) + +/-- The pending retired-committed records up to `i` name no other node `v` keeps. -/ +def RcRetired (v : State) (i : Nat) : Prop := + forall e, + e ∈ v.rcEntries + -> e.1 <= i + -> forall id, + id ∈ e.2 -> id ≠ v.nodeId -> ¬ MemIn (Exec.commit.pop e.1 v.configurations) id + +theorem handler_spec (env : Env) (saved : State) (from_ : Exec.NodeId) + (r : AppendEntriesResponse) + (cover + : forall node, + saved.peer? from_ = some node + -> saved.leadership = .leader + -> Cover (saved.setPeer from_ (ackPeer node r))) + (hrc : saved.leadership = .leader -> forall i, RcRetired saved i) + : Hoare env (fun v o => v = saved /\ o = []) (Exec.recvAppendEntriesResponse from_ r) + fun _ => Outcome env saved from_ r := by + unfold Exec.recvAppendEntriesResponse + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = saved) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + cases hp : s.peer? from_ with + | none => exact Hoare.fail _ + | some node => + simp only + refine Hoare.bind (Hoare.of_spec (Ae.det_traceRecv env _ _ _) + (Q := fun _ v o => v = s /\ o = []) fun v o _ v' o' p q => ?_) fun _ => ?_ + · obtain ⟨⟨e, f⟩, -⟩ := p + rw [q.1, q.2, e, f]; exact ⟨rfl, rfl⟩ + refine Hoare.getV_bind fun t => ?_ + refine hoare_assume (φ := t = s) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + have pre + : forall (v : State) (o : Outbox), + ((v = t /\ o = []) /\ v = t) -> v = t /\ o = [] := + fun _ _ p => p.1 + refine Hoare.ite (fun nl => Hoare.pure _ fun v o p => ?_) fun lead => ?_ + · obtain ⟨e, f⟩ := pre v o p + refine ⟨node, hp, Or.inl ⟨by simpa using nl, e, f⟩⟩ + have lead : t.leadership = .leader := by simpa using lead + refine Hoare.ite (fun gt => ?_) fun ngt => ?_ + · refine Hoare.bind (Hoare.of_spec (Ae.det_becomeAware env r.term) + (Q := fun _ v o => v = Ae.bant r.term t /\ o = []) fun v o _ v' o' p q => ?_) + fun _ => Hoare.pure _ fun v o p => ⟨node, hp, Or.inr (Or.inl ⟨lead, gt, p⟩)⟩ + obtain ⟨e, f⟩ := pre v o p + rw [q.1, q.2, e, f]; exact ⟨rfl, rfl⟩ + cases hs : r.success + · simp only [Bool.not_false, ↓reduceIte, Bool.false_eq_true, ite_self] + refine Hoare.bind (Hoare.setV _ + (Q := fun _ v o => v = t.setPeer from_ (nackPeer t node r) /\ o = []) fun v o p => ?_) + fun _ => Hoare.pure _ fun v o p => + ⟨node, hp, Or.inr (Or.inr (Or.inr (Or.inr (Or.inl ⟨lead, by omega, hs, p⟩))))⟩ + obtain ⟨e, f⟩ := pre v o p + rw [e, f] + exact ⟨rfl, rfl⟩ + simp only [Bool.not_true, ↓reduceIte, Bool.false_eq_true] + by_cases same : t.currentView ≠ r.term + · simp only [bne_iff_ne, ne_eq, same, not_false_eq_true, ↓reduceIte] + exact Hoare.pure _ fun v o p => ⟨node, hp, Or.inr (Or.inr (Or.inl + ⟨lead, by omega, hs, pre v o p⟩))⟩ + replace same : t.currentView = r.term := Decidable.of_not_not same + simp only [same, bne_self_eq_false, Bool.false_eq_true, ↓reduceIte] + refine Hoare.ite + (fun lt => + Hoare.pure _ + fun v o p => + ⟨ + node, + hp, + Or.inr (Or.inr (Or.inr (Or.inl ⟨lead, same.symm, hs, lt, pre v o p⟩))) + ⟩) + fun nlt => ?_ + refine Hoare.bind + (Hoare.setV _ (Q := fun _ v o => v = t.setPeer from_ (ackPeer node r) /\ o = []) + fun v o p => ?_) + fun _ => ?_ + · obtain ⟨e, f⟩ := pre v o p + rw [e, f] + exact ⟨rfl, rfl⟩ + unfold Exec.updateCommit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = t.setPeer from_ (ackPeer node r)) + (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + have l1 : ((t.setPeer from_ (ackPeer node r)).leadership == .leader) = true := by + simp [Exec.State.setPeer, lead] + simp only [l1, ↓reduceIte] + refine Hoare.bind (Hoare.of_spec (ReplUpdateCommit.updateCommitGo_spec _ _ _) + (Q := fun res v o => v = t.setPeer from_ (ackPeer node r) /\ o = [] + /\ ReplUpdateCommit.updateCommitOf (t.setPeer from_ (ackPeer node r)) 0 none + ((t.setPeer from_ (ackPeer node r)).lastIdx + 2) = .ok res) + fun v o a v' o' p q => ?_) fun res => ?_ + · obtain ⟨⟨e, f⟩, -⟩ := p + obtain ⟨q1, q2, q3⟩ := q + rw [q1, q2, e, f] + exact ⟨rfl, rfl, e ▸ q3⟩ + have out + : forall (v : State) (o : Outbox), + (v = t.setPeer from_ (ackPeer node r) + /\ o = [] + /\ ReplUpdateCommit.updateCommitOf (t.setPeer from_ (ackPeer node r)) 0 + none ((t.setPeer from_ (ackPeer node r)).lastIdx + 2) + = .ok res) + -> res.getD t.commitIdx <= t.commitIdx + -> Outcome env t from_ r v o := + fun v o p le => + ⟨ + node, + hp, + Or.inr + (Or.inr + (Or.inr + (Or.inr + (Or.inr + ⟨ + lead, + same.symm, + hs, + by omega, + res, + p.2.2, + Or.inl ⟨le, p.1, p.2.1⟩ + ⟩)))) + ⟩ + cases res with + | none => exact Hoare.pure _ fun v o p => out v o p (Nat.le_refl _) + | some i => + simp only + have v1Last : (t.setPeer from_ (ackPeer node r)).lastIdx = t.lastIdx := rfl + have v1Commit : (t.setPeer from_ (ackPeer node r)).commitIdx = t.commitIdx := + rfl + by_cases gt : i > t.lastIdx + · unfold Exec.commit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = t.setPeer from_ (ackPeer node r)) + (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + simp only [v1Last, gt, ↓reduceIte] + exact hoare_curLoc_fail _ + by_cases le : i <= t.commitIdx + · unfold Exec.commit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = t.setPeer from_ (ackPeer node r)) + (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + simp only [v1Last, v1Commit, gt, le, ↓reduceIte] + exact Hoare.pure _ fun v o p => out v o p.1 le + refine hoare_assume + (φ := + ReplUpdateCommit.updateCommitOf (t.setPeer from_ (ackPeer node r)) + 0 none ((t.setPeer from_ (ackPeer node r)).lastIdx + 2) + = .ok (some i)) + (fun _ _ p => p.2.2) fun ran => ?_ + refine Hoare.post + (Hoare.pre + (commit_spec env (v1 := t.setPeer from_ (ackPeer node r)) + (o0 := []) lead (by omega) (by omega) (cover node hp lead) (hrc lead i)) + fun v o p => ⟨p.1, p.2.1⟩) + fun _ v o q => + ⟨ + node, + hp, + Or.inr + (Or.inr + (Or.inr + (Or.inr + (Or.inr + ⟨ + lead, + same.symm, + hs, + by omega, + some i, + ran, + Or.inr ⟨i, rfl, by omega, by omega, q⟩ + ⟩)))) + ⟩ + +/-- What a primary's clean `nominateSuccessor` sends. -/ +def nomSends (node : NodeID) (st : NodeState) : List (CCF.Envelope NodeID Message) := + ((findSuccessor st node).map + fun t => + CCF.Envelope.mk node t (Message.proposeRequestVoteRequest st.currentTerm)).toList + +theorem advance_run (node : NodeID) (st : NodeState) (primary : st.role = .primary) + : (advanceCommit (CCF.Capabilities.record node) st node).run {} + = some + ( + if highestCommittableIndex st node <= st.commitIndex then + st + else + st.recordCommit node (highestCommittableIndex st node), + { + outgoing := + if ¬ highestCommittableIndex st node <= st.commitIndex + /\ (st.recordCommit node + (highestCommittableIndex st node)).isRetiredCommitted + node then + nomSends node st + else + [] + } + ) := by + unfold advanceCommit + by_cases h : highestCommittableIndex st node <= st.commitIndex + · simp [h] + · by_cases r : (st.recordCommit node (highestCommittableIndex st node)).isRetiredCommitted node + · cases hs : findSuccessor st node <;> + simp [h, primary, nominateSuccessor, guard, nomSends, hs, CCF.Capabilities.record, + modify, modifyGet, MonadStateOf.modifyGet, StateT.run] <;> (try split) <;> simp_all <;> rfl + · simp [h]; split <;> simp_all <;> rfl + +abbrev cleanRun (node source : NodeID) (clean : NodeState) (r : AppendEntriesResponse) := + (Consensus.Model.Node.step (CCF.Capabilities.record node) node clean + (.receive source (.appendEntriesResponse r))).run + {} + +theorem receive_ineligible {node source : NodeID} {clean : NodeState} + (r : AppendEntriesResponse) (h : source ∉ eligiblePeers clean node) + : cleanRun node source clean r = some (clean, {}) := by + simp [cleanRun, Consensus.Model.Node.step, Model.Node.receive, h] + +theorem receive_notPrimary {node source : NodeID} {clean : NodeState} + (r : AppendEntriesResponse) (h : clean.role ≠ .primary) + : cleanRun node source clean r = some (clean, {}) := by + by_cases e : source ∈ eligiblePeers clean node + · simp [cleanRun, Consensus.Model.Node.step, Model.Node.receive, e, observeTerm, h, + handleAppendEntriesResponse] + · exact receive_ineligible r e + +theorem receive_primary {node source : NodeID} {clean : NodeState} + (r : AppendEntriesResponse) (e : source ∈ eligiblePeers clean node) + (h : clean.role = .primary) + : cleanRun node source clean r + = (handleAppendEntriesResponse (CCF.Capabilities.record node) node + (updateTerm clean r.term) source r).run + {} := by + simp [cleanRun, Consensus.Model.Node.step, Model.Node.receive, e, observeTerm, h] + +theorem handle_notPrimary {node source : NodeID} {st : NodeState} + (r : AppendEntriesResponse) (h : st.role ≠ .primary) + : (handleAppendEntriesResponse (CCF.Capabilities.record node) node st source r).run {} + = some (st, {}) := by + simp [handleAppendEntriesResponse, h] + +theorem handle_stale {node source : NodeID} {st : NodeState} (r : AppendEntriesResponse) + (h : st.role = .primary) (ok : r.success = true) (ne : r.term ≠ st.currentTerm) + : (handleAppendEntriesResponse (CCF.Capabilities.record node) node st source r).run {} + = some (st, {}) := by + simp [handleAppendEntriesResponse, h, ok, ne] + +theorem handle_nack {node source : NodeID} {st : NodeState} (r : AppendEntriesResponse) + (h : st.role = .primary) (nok : r.success = false) + : (handleAppendEntriesResponse (CCF.Capabilities.record node) node st source r).run {} + = some + ( + { + st with + sentIndex := + CCF.Function.update st.sentIndex source + (max + (min (findHighestPossibleMatch st.log r.lastLogIndex r.term) + (st.sentIndex source)) + (st.matchIndex source)) + }, + {} + ) := by + simp [handleAppendEntriesResponse, h, nok] + +theorem handle_ack {node source : NodeID} {st : NodeState} (r : AppendEntriesResponse) + (h : st.role = .primary) (ok : r.success = true) (same : r.term = st.currentTerm) + : (handleAppendEntriesResponse (CCF.Capabilities.record node) node st source r).run {} + = (advanceCommit (CCF.Capabilities.record node) + { + st with + matchIndex := + CCF.Function.update st.matchIndex source + (max (st.matchIndex source) r.lastLogIndex) + } node).run + {} := by + simp [handleAppendEntriesResponse, h, ok, same] + +end Consensus.TraceValidation.Proofs.AeResp diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespSuccessor.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespSuccessor.lean new file mode 100644 index 000000000000..a4979b85af10 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeRespSuccessor.lean @@ -0,0 +1,489 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit +public import Consensus.TraceValidation.Proofs.Handlers.AeLemmas + +@[expose] public section + +/-! +# cft.h's successor is the clean `findSuccessor` (not reviewed) + +M_tv's `find_successor` loop (`Exec.becomeRetired.findSuccessor`) walks the peers in order +and keeps the peer with the highest match index, breaking ties by the latest configuration +naming it and then by the later peer. The peers are the clean eligible peers in increasing +id order (`inv` conjunct `peers`), so "the later peer" is the clean tie-break by node id: + +* `findSuccessor_spec`: the loop reads the state, changes nothing and returns `tvSuccessor`; +* `tvSuccessor_eq`: for a leader satisfying `inv` and a clean state that agrees with it, + `tvSuccessor` mapped to clean ids is the clean `findSuccessor`. +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open Consensus.Model.Node +open Consensus.TraceValidation (Names abs agrees trackedPeers inv invChecks) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open Consensus.TraceValidation.Proofs.ReplUpdateCommit (absConfig Named named_inj) + +/-- The index of the last configuration of `cs` naming `node`, or 0. -/ +def latestIn (cs : List Config) (node : Exec.NodeId) : Nat := + ((cs.reverse.find? (·.nodes.any (·.1 == node))).map (·.idx)).getD 0 + +/-- The index of the last declared configuration naming `node`, or 0. -/ +abbrev latestOf (v : State) (node : Exec.NodeId) : Nat := latestIn v.configurations node + +/-- One iteration of `find_successor`: the successor, its match index and its `latest`. -/ +def tvStep (v : State) (acc : Option Exec.NodeId × Nat × Nat) (p : Exec.NodeId × Peer) + : Option Exec.NodeId × Nat × Nat := + if p.2.matchIdx >= acc.2.1 then + if (!(p.2.matchIdx == acc.2.1 && decide (latestOf v p.1 < acc.2.2))) = true then + (some p.1, p.2.matchIdx, latestOf v p.1) + else + acc + else + acc + +/-- What `find_successor` returns on `v`. -/ +def tvSuccessor (v : State) : Option Exec.NodeId := + (v.allOtherNodes.foldl (tvStep v) (none, 0, 0)).1 + +/-! ## The monadic loop -/ + +theorem forIn_yield {α β : Type} (f : β -> α -> β) (body : α -> β -> M (ForInStep β)) + (hb : forall a b, body a b = pure (.yield (f b a))) + : forall (l : List α) (init : β), forIn l init body = pure (l.foldl f init) + | [], _ => rfl + | a :: l, init => by + rw [List.forIn_cons, hb, pure_bind, List.foldl_cons] + exact forIn_yield f body hb l (f init a) + +theorem getV_bind_run {α : Type} (f : State -> M α) (c : Ctx) + : (Exec.getV >>= f).run c = (f c.vars).run c := + rfl + +theorem findSuccessor_run (c : Ctx) + : Exec.becomeRetired.findSuccessor.run c = .ok (tvSuccessor c.vars, c) := by + unfold Exec.becomeRetired.findSuccessor + rw [getV_bind_run] + dsimp only + rw [forIn_yield (tvStep c.vars)] + · rfl + · intro p acc + obtain ⟨k, st⟩ := p + obtain ⟨s, mm, rc⟩ := acc + simp only [tvStep, latestOf, latestIn] + split + · split + · rename_i h + exact congrArg (fun z => pure (ForInStep.yield z)) + (ite_eq_left_of_eq_true _ _ (eq_true h)).symm + · rename_i h + exact congrArg (fun z => pure (ForInStep.yield z)) + (ite_eq_right_of_eq_false _ _ (eq_false h)).symm + · rfl + +theorem findSuccessor_spec {env : Consensus.TraceValidation.Env} + : Spec env Exec.becomeRetired.findSuccessor + fun v o a v' o' => a = tvSuccessor v /\ v' = v /\ o' = o := by + intro c a c' envOk h + rw [findSuccessor_run] at h + cases h + exact ⟨envOk, rfl, rfl, rfl⟩ + +/-- `find_successor` returns a peer. -/ +theorem tvSuccessor_mem {v : State} {s : Exec.NodeId} (h : tvSuccessor v = some s) + : exists p, p ∈ v.allOtherNodes /\ p.1 = s := by + unfold tvSuccessor at h + have general : forall (l : List (Exec.NodeId × Peer)) (acc : Option Exec.NodeId × Nat × Nat), + (l.foldl (tvStep v) acc).1 = some s + -> acc.1 = some s \/ exists p, p ∈ l /\ p.1 = s := by + intro l + induction l with + | nil => intro acc h; exact Or.inl h + | cons q l ih => + intro acc h + rcases ih _ h with h | ⟨p, mem, ps⟩ + · simp only [tvStep] at h + split at h + · split at h + · simp only [Option.some.injEq] at h + exact Or.inr ⟨q, List.mem_cons_self, h⟩ + · exact Or.inl h + · exact Or.inl h + · exact Or.inr ⟨p, List.mem_cons_of_mem _ mem, ps⟩ + rcases general _ _ h with h | found + · cases h + · exact found + +/-! ## Against the clean fold -/ + +/-- The clean step of `findSuccessor`'s fold, with rank `(m n, lat n, n)`. -/ +abbrev cleanStep (m lat : NodeID -> Nat) (best : Option NodeID) (candidate : NodeID) + : Option NodeID := + match best with + | none => some candidate + | some selected => + if rankBelow (m selected, lat selected, selected) + (m candidate, lat candidate, candidate) + = true then + some candidate + else + best + +theorem tvStep_some (v : State) (s : Exec.NodeId) (mm rc : Nat) (p : Exec.NodeId × Peer) + : tvStep v (some s, mm, rc) p + = if mm < p.2.matchIdx \/ (p.2.matchIdx = mm /\ Not (latestOf v p.1 < rc)) then + (some p.1, p.2.matchIdx, latestOf v p.1) + else + (some s, mm, rc) := by + unfold tvStep + by_cases a : mm <= p.2.matchIdx <;> by_cases b : p.2.matchIdx = mm <;> + by_cases c : latestOf v p.1 < rc <;> simp [a, b, c] <;> omega + +theorem cleanStep_some (m lat : NodeID -> Nat) {s c : NodeID} (lt : s < c) + : cleanStep m lat (some s) c + = if m s < m c \/ (m c = m s /\ Not (lat c < lat s)) then some c else some s := by + simp only [cleanStep, rankBelow, Prod.lexLt] + by_cases a : m s < m c <;> by_cases b : m c = m s <;> by_cases d : lat c < lat s <;> + by_cases e : lat s = lat c <;> simp [a, b, d, e, lt] <;> omega + +theorem fold_sim (v : State) (id : Exec.NodeId -> NodeID) (m lat : NodeID -> Nat) + (P : Exec.NodeId -> Prop) + (cmp + : forall a b, + P a -> P b -> (latestOf v a < latestOf v b <-> lat (id a) < lat (id b))) + : forall (l : List (Exec.NodeId × Peer)) (acc : Option Exec.NodeId × Nat × Nat) + (best : Option NodeID), + l.Pairwise (fun p q => id p.1 < id q.1) + -> (forall p, p ∈ l -> P p.1 /\ m (id p.1) = p.2.matchIdx) + -> acc.1.map id = best + -> (acc.1 = none -> acc.2 = (0, 0)) + -> (forall s, + acc.1 = some s + -> P s + /\ acc.2.1 = m (id s) + /\ acc.2.2 = latestOf v s + /\ forall p, p ∈ l -> id s < id p.1) + -> (l.foldl (tvStep v) acc).1.map id + = (l.map fun p => id p.1).foldl (cleanStep m lat) best + | [], _, _, _, _, same, _, _ => same + | p :: l, acc, best, sorted, values, same, zero, cur => by + rw [List.foldl_cons, List.map_cons, List.foldl_cons] + obtain ⟨hp, hm⟩ := values p List.mem_cons_self + have later : forall q, q ∈ l -> id p.1 < id q.1 := + fun _ mem => List.rel_of_pairwise_cons sorted mem + have rest := fun acc best => + fold_sim v id m lat P cmp l acc best (List.Pairwise.of_cons sorted) + (fun q mem => values q (List.mem_cons_of_mem _ mem)) + have chosen : forall acc', acc' = (some p.1, p.2.matchIdx, latestOf v p.1) + -> (l.foldl (tvStep v) acc').1.map id + = (l.map fun p => id p.1).foldl (cleanStep m lat) (some (id p.1)) := by + intro acc' h + subst h + exact rest _ _ rfl (by simp) fun s hs => by + cases hs + exact ⟨hp, hm.symm, rfl, later⟩ + obtain ⟨o, mm, rc⟩ := acc + cases o with + | none => + obtain ⟨rfl, rfl⟩ := Prod.mk.inj (zero rfl) + simp only [Option.map_none] at same + subst same + exact chosen _ (by simp [tvStep]) + | some s => + obtain ⟨hs, hmm, hrc, lt⟩ := cur s rfl + simp only [Option.map_some] at same + subst same + simp only at hmm hrc + subst hmm hrc + have sp := lt p List.mem_cons_self + rw [tvStep_some, cleanStep_some m lat sp, hm] + simp only [cmp p.1 s hp hs] + by_cases rep : m (id s) < p.2.matchIdx + \/ (p.2.matchIdx = m (id s) /\ Not (lat (id p.1) < lat (id s))) + · simp only [rep, ↓reduceIte] + exact chosen _ rfl + · simp only [rep, ↓reduceIte] + exact rest _ _ rfl (by simp) fun s' hs' => by + cases hs' + exact ⟨hs, rfl, rfl, fun q mem => lt q (List.mem_cons_of_mem _ mem)⟩ + +/-! ## The ranks agree -/ + +theorem foldl_latest {Q : Config -> Bool} {P : Config -> Prop} [DecidablePred P] + : forall (D : List Config) (acc : Nat), + (forall x, x ∈ D -> (P x <-> Q x = true)) + -> D.Pairwise (fun a b => a.idx < b.idx) + -> (forall x, x ∈ D -> acc <= x.idx) + -> D.foldl (fun highest x => if P x then max highest x.idx else highest) acc + = ((D.reverse.find? Q).map (·.idx)).getD acc + | [], _, _, _, _ => rfl + | x :: D, acc, same, sorted, low => by + rw [List.foldl_cons, List.reverse_cons, List.find?_append] + have later : forall y, y ∈ D -> x.idx <= y.idx := + fun _ mem => Nat.le_of_lt (List.rel_of_pairwise_cons sorted mem) + have rest := fun acc low' => + foldl_latest D acc (fun y mem => same y (List.mem_cons_of_mem _ mem)) + (List.Pairwise.of_cons sorted) low' + by_cases px : P x + · have qx : Q x = true := (same x List.mem_cons_self).mp px + simp only [px, ↓reduceIte, List.find?_cons, qx] + rw [Nat.max_eq_right (low x List.mem_cons_self), rest x.idx later] + cases D.reverse.find? Q <;> rfl + · have qx : Q x = false := by + cases hq : Q x + · rfl + · exact absurd ((same x List.mem_cons_self).mpr hq) px + simp only [px, ↓reduceIte, List.find?_cons, qx] + refine (rest acc fun y mem => low y (List.mem_cons_of_mem _ mem)).trans ?_ + cases D.reverse.find? Q <;> rfl + +theorem mem_absConfig_iff {names : Names} {x : Config} {node : Exec.NodeId} + (named : Named names node) (membersNamed : forall a, a ∈ x.nodes -> Named names a.1) + : names.id node ∈ (absConfig names x).nodes + <-> (x.nodes.any (·.1 == node)) = true := by + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, List.map_map, List.mem_map, + List.any_eq_true, beq_iff_eq, Function.comp_apply] + constructor + · rintro ⟨a, mem, same⟩ + exact ⟨a, mem, named_inj (membersNamed a mem) named same⟩ + · rintro ⟨a, mem, rfl⟩ + exact ⟨a, mem, rfl⟩ + +theorem latest_eq {names : Names} {D : List Config} {node : Exec.NodeId} + (named : Named names node) + (membersNamed : forall x, x ∈ D -> forall a, a ∈ x.nodes -> Named names a.1) + (sorted : D.Pairwise fun a b => a.idx < b.idx) + : latestMembershipIndex (D.map (absConfig names)) (names.id node) + = latestIn D node := by + unfold latestMembershipIndex latestIn + rw [List.foldl_map] + exact foldl_latest (Q := fun x => x.nodes.any (·.1 == node)) _ 0 + (fun x mem => mem_absConfig_iff named (membersNamed x mem)) sorted + (fun _ _ => Nat.zero_le _) + +theorem latestIn_cons (x : Config) (rest : List Config) (node : Exec.NodeId) + : latestIn (x :: rest) node + = match rest.reverse.find? (·.nodes.any (·.1 == node)) with + | some z => z.idx + | none => if x.nodes.any (·.1 == node) then x.idx else 0 := by + unfold latestIn + rw [List.reverse_cons, List.find?_append] + cases rest.reverse.find? (·.nodes.any (·.1 == node)) with + | some z => rfl + | none => + simp only [Option.none_or, List.find?_cons, List.find?_nil] + split <;> simp [*] + +/-- +Shifting the first configuration to a later index at or below `ci`, the others being above +`ci`, keeps the order of the latest configurations naming two nodes. +-/ +theorem latestIn_shifted {ci : Nat} {D E : List Config} + (sh : ReplUpdateCommit.Shifted ci D E) (pos : forall x, x ∈ D -> 0 < x.idx) + (above : forall x, x ∈ D.drop 1 -> ci < x.idx) (a b : Exec.NodeId) + : latestIn E a < latestIn E b <-> latestIn D a < latestIn D b := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, nodes, xy, yc⟩ + · exact Iff.rfl + · simp only [List.drop_succ_cons, List.drop_zero] at above + have x0 := pos x List.mem_cons_self + have found : forall n z, rest.reverse.find? (·.nodes.any (·.1 == n)) = some z -> ci < z.idx := + fun _ z h => above z (List.mem_reverse.mp (List.mem_of_find?_eq_some h)) + rw [latestIn_cons, latestIn_cons, latestIn_cons, latestIn_cons, nodes] + cases ha : rest.reverse.find? (·.nodes.any (·.1 == a)) <;> + cases hb : rest.reverse.find? (·.nodes.any (·.1 == b)) <;> + simp only + · split <;> split <;> omega + · have := found b _ hb + split <;> omega + · have := found a _ ha + split <;> omega + +theorem find_sorted (names : Names) + : forall (l : List (Exec.NodeId × Peer)), + l.Pairwise (fun p q => names.id p.1 < names.id q.1) + -> forall p, + p ∈ l -> l.find? (fun (id, _) => names.id id == names.id p.1) = some p + | [], _, _, mem => by cases mem + | q :: l, sorted, p, mem => by + rcases List.mem_cons.mp mem with rfl | mem + · simp + · have lt := List.rel_of_pairwise_cons sorted mem + have ne : (names.id q.1 == names.id p.1) = false := by + simp only [beq_eq_false_iff_ne] + exact Nat.ne_of_lt lt + rw [List.find?_cons] + simp only [ne] + exact find_sorted names l (List.Pairwise.of_cons sorted) p mem + +theorem abs_matchIndex_of_sorted {names : Names} {v : State} + (sorted : v.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1)) {p} + (mem : p ∈ v.allOtherNodes) + : (abs names v).matchIndex (names.id p.1) = p.2.matchIdx := by + simp only [abs] + rw [find_sorted names _ sorted p mem] + +theorem eligiblePeers_of_log_nil {st : NodeState} (empty : st.log = []) (self : NodeID) + : (eligiblePeers st self).sort = [] := by + unfold eligiblePeers NodeState.activeMembers NodeState.retirementCompletedNodes + NodeState.activeConfigurations NodeState.committedLog + rw [empty] + simp only [List.take_nil, activeConfigurations, configurationHistory, List.zipIdx_nil, + List.filterMap_nil, List.filter_nil, List.drop_nil] + rfl + +/-! ## The successor -/ + +/-- +The successor on `w`, which has the peers of a leader `v` satisfying `inv` (with any match +indexes) and its configurations, is the clean successor of a state with `v`'s log and commit +index and `w`'s match indexes. +-/ +theorem tvSuccessor_core {names : Names} {v w : State} {c : NodeState} + (h : inv names v = true) (leader : v.leadership = .leader) + (hlog : c.log = (abs names v).log) + (hcommit : c.commitIndex = (abs names v).commitIndex) + (keys : w.allOtherNodes.map Prod.fst = v.allOtherNodes.map Prod.fst) + (configs : w.configurations = v.configurations) + (matched + : forall p, p ∈ w.allOtherNodes -> c.matchIndex (names.id p.1) = p.2.matchIdx) + : (tvSuccessor w).map names.id = findSuccessor c (names.id v.nodeId) := by + have hyps := ReplUpdateCommit.Hyps.ofInv h + have step : tvStep w = tvStep v := by + funext acc p + simp only [tvStep, latestOf, configs] + have keysId : w.allOtherNodes.map (fun p => names.id p.1) + = v.allOtherNodes.map (fun p => names.id p.1) := by + have := congrArg (List.map names.id) keys + simp only [List.map_map] at this + exact this + by_cases L0 : v.lastIdx = 0 + · have alone : v.allOtherNodes = [] := by + have e := ReplUpdateCommit.inv_conjunct h "empty_leader_alone" + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at e + simpa [L0, leader] using e + have aloneW : w.allOtherNodes = [] := by + rw [alone] at keys + exact List.map_eq_nil_iff.mp keys + have nil : (eligiblePeers c (names.id v.nodeId)).sort = [] := by + apply eligiblePeers_of_log_nil + rw [hlog] + simp [abs, L0] + unfold tvSuccessor findSuccessor + rw [aloneW, nil] + rfl + · have peersEq : v.allOtherNodes.map (fun p => names.id p.1) + = (eligiblePeers (abs names v) (names.id v.nodeId)).sort := by + have e := ReplUpdateCommit.inv_conjunct h "peers" + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at e + simpa [L0, leader] using e + have sorted : w.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1) := by + have := (eligiblePeers (abs names v) (names.id v.nodeId)).sorted + rw [← CCF.Finset.sort, ← peersEq, ← keysId, List.pairwise_map] at this + exact this + have namedW : forall p, p ∈ w.allOtherNodes -> Named names p.1 := by + intro p mem + have : p.1 ∈ v.allOtherNodes.map Prod.fst := by + rw [← keys] + exact List.mem_map_of_mem mem + obtain ⟨q, qm, e⟩ := List.mem_map.mp this + exact e ▸ hyps.peersNamed q qm + obtain ⟨D, hD, sh⟩ := hyps.configs (Nat.pos_of_ne_zero L0) + have active : c.activeConfigurations = D.map (absConfig names) := by + unfold NodeState.activeConfigurations + rw [hlog, hcommit] + exact hD + have membersD : forall x, x ∈ D -> forall a, a ∈ x.nodes -> Named names a.1 := by + intro x mem a am + rcases sh with rfl | ⟨x', y, rest, rfl, hE, nodes, _⟩ + · exact hyps.membersNamed x mem a am + · rcases List.mem_cons.mp mem with rfl | mem + · exact hyps.membersNamed y (by rw [hE]; exact List.mem_cons_self) a (nodes ▸ am) + · exact hyps.membersNamed x (by rw [hE]; exact List.mem_cons_of_mem _ mem) a am + let P : Exec.NodeId -> Prop := fun a => exists p, p ∈ w.allOtherNodes /\ p.1 = a + have cmp : forall a b, P a -> P b + -> (latestOf v a < latestOf v b + <-> latestMembershipIndex c.activeConfigurations (names.id a) + < latestMembershipIndex c.activeConfigurations (names.id b)) := by + rintro a b ⟨p, pm, rfl⟩ ⟨q, qm, rfl⟩ + rw [active, latest_eq (namedW p pm) membersD (ReplUpdateCommit.declared_sorted hD), + latest_eq (namedW q qm) membersD (ReplUpdateCommit.declared_sorted hD)] + exact latestIn_shifted sh (fun _ mem => ReplUpdateCommit.declared_pos hD mem) + (ReplUpdateCommit.active_tail_above names _ hD) _ _ + have values : forall p, p ∈ w.allOtherNodes + -> P p.1 /\ c.matchIndex (names.id p.1) = p.2.matchIdx := + fun p mem => ⟨⟨p, mem, rfl⟩, matched p mem⟩ + have key := fold_sim v names.id c.matchIndex (latestMembershipIndex c.activeConfigurations) + P cmp w.allOtherNodes (none, 0, 0) none sorted values rfl (fun _ => rfl) + (fun _ hs => by cases hs) + unfold tvSuccessor + rw [step, key] + unfold findSuccessor + rw [Ae.eligiblePeers_congr hlog hcommit, ← peersEq, keysId] + rfl + +theorem tvSuccessor_eq {names : Names} {v : State} {c : NodeState} + (h : inv names v = true) (leader : v.leadership = .leader) + (agreed : agrees names c v = true) + : (tvSuccessor v).map names.id = findSuccessor c (names.id v.nodeId) := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq, and_assoc, List.all_eq_true] at agreed + obtain ⟨_, _, hlog, hcommit, tracked, _⟩ := agreed + simp only [trackedPeers, leader, beq_self_eq_true, ↓reduceIte, List.mem_map] at tracked + refine tvSuccessor_core h leader hlog hcommit rfl rfl fun p mem => ?_ + have sorted : v.allOtherNodes.Pairwise (fun p q => names.id p.1 < names.id q.1) := by + by_cases L0 : v.lastIdx = 0 + · have e := ReplUpdateCommit.inv_conjunct h "empty_leader_alone" + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at e + have alone : v.allOtherNodes = [] := by simpa [L0, leader] using e + rw [alone] + exact List.Pairwise.nil + · have e := ReplUpdateCommit.inv_conjunct h "peers" + simp only [invChecks, List.lookup, String.reduceBEq, Option.getD_some] at e + have peersEq : v.allOtherNodes.map (fun p => names.id p.1) + = (eligiblePeers (abs names v) (names.id v.nodeId)).sort := by + simpa [L0, leader] using e + have := (eligiblePeers (abs names v) (names.id v.nodeId)).sorted + rw [← CCF.Finset.sort, ← peersEq, List.pairwise_map] at this + exact this + rw [(tracked _ ⟨p, mem, rfl⟩).2] + exact abs_matchIndex_of_sorted sorted mem + +/-- The clean successor is an eligible peer, so it is not the node itself. -/ +theorem findSuccessor_mem {st : NodeState} {self t : NodeID} + (h : findSuccessor st self = some t) + : t ∈ eligiblePeers st self := by + unfold findSuccessor at h + have general : forall (l : List NodeID) (best : Option NodeID), + (l.foldl (cleanStep st.matchIndex (latestMembershipIndex st.activeConfigurations)) best) + = some t + -> best = some t \/ t ∈ l := by + intro l + induction l with + | nil => intro best h; exact Or.inl h + | cons x l ih => + intro best h + rcases ih _ h with h | mem + · cases best with + | none => + simp only [cleanStep, Option.some.injEq] at h + exact Or.inr (h ▸ List.mem_cons_self) + | some s => + simp only [cleanStep] at h + split at h + · simp only [Option.some.injEq] at h + exact Or.inr (h ▸ List.mem_cons_self) + · exact Or.inl h + · exact Or.inr (List.mem_cons_of_mem _ mem) + rcases general _ none h with h | mem + · cases h + · exact CCF.Finset.mem_sort.mp mem + +theorem findSuccessor_ne {st : NodeState} {self t : NodeID} + (h : findSuccessor st self = some t) + : t ≠ self := by + have := findSuccessor_mem h + unfold eligiblePeers at this + exact (CCF.Finset.mem_erase.mp this).1 diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntriesResponse.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntriesResponse.lean new file mode 100644 index 000000000000..d37d0a0c7501 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AppendEntriesResponse.lean @@ -0,0 +1,406 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespMain +public import Consensus.TraceValidation.Proofs.Handlers.Nomination +public import Consensus.TraceValidation.Proofs.Handlers.AeMatch + +@[expose] public section + +/-! +# Obligation: `append_entries_response` (not reviewed) + +The driver's `recv_append_entries_response`. Responses from unknown senders, to non-leaders, +or of a stale term change nothing; a newer term makes the node a follower. A NACK lowers the +sent index to the retry point. An ACK raises the sender's match and sent indices and then runs +`update_commit`: no commit changes nothing more; a commit either keeps the node leader, or +(when the node's own retirement is now committed) steps down after nominating a successor. +Each case is matched by the clean `appendEntriesResponse` run (`AeResp.handler_spec`, +`AeResp.commit_spec`, `AeResp.tvSuccessor_core`). +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation ( + Names Env abs absRole agrees trackedPeers inv invChecks msgInv) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) + +/-- The state `recordCommit` builds before it may clear the role. -/ +abbrev latch (node : NodeID) (st : NodeState) (i : Nat) : NodeState := + { st with commitIndex := i, retiredCommittedIndex := Ae.firstConf node st.log i } + +theorem recordCommit_clear {node : NodeID} {st : NodeState} {i : Nat} + (h : st.retiredCommittedIndex = none) (c : (latch node st i).isRetiredCommitted node) + : st.recordCommit node i + = { latch node st i with role := .none, primaryKnown := false } := by + unfold NodeState.recordCommit + simp only [latch, Ae.firstConf] at c + simp [h, Ae.firstConf, c] + +theorem recordCommit_keep {node : NodeID} {st : NodeState} {i : Nat} + (h : st.retiredCommittedIndex = none) + (c : ¬ (latch node st i).isRetiredCommitted node) + : st.recordCommit node i = latch node st i := by + unfold NodeState.recordCommit + simp only [latch, Ae.firstConf] at c + simp [h, Ae.firstConf, c] + +/-- The clean state after a success response, before the commit. -/ +abbrev ackState (st : NodeState) (source : NodeID) (idx : Nat) : NodeState := + { + st with + matchIndex := + CCF.Function.update st.matchIndex source (max (st.matchIndex source) idx) + } + +/-- The clean side of a hold, from one clean receive. -/ +theorem concl_of {env : Env} {node source : NodeID} {r : AppendEntriesResponse} + {cleanOthers : List (NodeID × NodeState)} {clean clean' : NodeState} {vars : State} + {outbox : Outbox} {out : CCF.Outputs NodeID Message Notification} + (step : cleanRun node source clean r = some (clean', out)) + (sends : out.outgoing = outbox) (agreed : agrees env.names clean' vars = true) + (unmatched : UnnamedUnmatched node clean') + (msgs : forall e, e ∈ outbox -> msgInv env.names e = true) + : exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node clean + (cleanActions env (some (source, .appendEntriesResponse r)) inputs) clean' + outbox + /\ agrees env.names clean' vars = true + /\ UnnamedUnmatched node clean' + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall envelope, envelope ∈ outbox -> msgInv env.names envelope = true := + ⟨[], clean', sends ▸ localRun_of step, agreed, unmatched, by simp, msgs⟩ + +end Consensus.TraceValidation.Proofs.AeResp + +namespace Consensus.TraceValidation.Proofs +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation ( + Names Env abs absRole agrees trackedPeers inv invChecks msgInv) +open Consensus.TraceValidation.Exec (State Ctx Peer Config M) +open AeResp + +theorem appendEntriesResponseSound (env : Env) : AppendEntriesResponseSound env := by + intro node source r saved actions c vars others cleanOthers savedName savedId invSaved msgOk _ ran _ + finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have hsrc : env.names.id (env.names.name source) = source := + Ae.msgInv_source (msgOk source _ rfl) + have cover : forall nd, saved.peer? (env.names.name source) = some nd + -> saved.leadership = .leader + -> Cover (saved.setPeer (env.names.name source) (ackPeer nd r)) := by + intro nd hp lead + have mem := lookup_mem hp + have L0 := leader_nonempty invSaved lead mem + exact cover_setPeer (peerCtx invSaved lead L0).sortedStr mem (cover_of_inv invSaved lead L0) + obtain ⟨nd, hp, outcome⟩ := Ae.Hoare.run + (handler_spec env saved (env.names.name source) r cover + fun lead => rcRetired_of_inv invSaved lead) ⟨rfl, rfl⟩ ran + have mem := lookup_mem hp + -- Not a leader: nothing changes. + rcases outcome with ⟨nl, hv, ho⟩ | outcome + · rw [hv, ho] + refine ⟨rfl, fun clean _ agreed unmatched => ?_⟩ + have np : clean.role ≠ .primary := by + rw [(Agrees.of agreed).role] + cases h : saved.leadership <;> simp_all [absRole] + exact concl_of (receive_notPrimary r np) rfl agreed unmatched (by simp) + have lead : saved.leadership = .leader := by + rcases outcome with ⟨l, _⟩ | ⟨l, _⟩ | ⟨l, _⟩ | ⟨l, _⟩ | ⟨l, _⟩ <;> exact l + have L0 := leader_nonempty invSaved lead mem + have pc := peerCtx invSaved lead L0 + have facts : forall clean, agrees env.names clean saved = true + -> Agrees env.names clean saved /\ clean.role = .primary + /\ source ∈ eligiblePeers clean node + /\ clean.matchIndex source = nd.matchIdx /\ clean.sentIndex source = nd.sentIdx := by + intro clean agreed + have A := Agrees.of agreed + have tracked : source ∈ trackedPeers env.names saved := by + simp only [trackedPeers, lead, beq_self_eq_true, ↓reduceIte, List.mem_map] + exact ⟨_, mem, hsrc⟩ + refine ⟨A, by rw [A.role, lead]; rfl, ?_, ?_, ?_⟩ + · rw [Ae.eligiblePeers_congr A.log A.commit, ← savedId, pc.eligible_iff] + exact ⟨_, mem, hsrc⟩ + · rw [A.match_ _ tracked, ← hsrc] + exact abs_matchIndex_of_sorted pc.sortedId mem + · rw [A.sent _ tracked, ← hsrc] + exact abs_sentIndex_of_sorted pc.sortedId mem + rcases outcome with ⟨_, lt, hv, ho⟩ | ⟨_, lt, ok, hv, ho⟩ | ⟨_, eq, ok, lt, hv, ho⟩ + | ⟨_, le, nok, hv, ho⟩ | ⟨_, eq, ok, le, res, run, branch⟩ + -- A newer term: become a follower. + · rw [hv, ho] + refine ⟨rfl, fun clean _ agreed _ => ?_⟩ + obtain ⟨A, primary, elig, -, -⟩ := facts clean agreed + have step := receive_primary r elig primary + rw [Ae.updateTerm_of_lt (by rw [A.term]; exact lt), + handle_notPrimary r (by simp [Model.Node.becomeAwareOfNewTerm])] at step + exact concl_of step rfl (Ae.agrees_bant r.term agreed) + (fun h => by simp [Model.Node.becomeAwareOfNewTerm] at h) (by simp) + -- A stale success: ignored. + · rw [hv, ho] + refine ⟨rfl, fun clean _ agreed unmatched => ?_⟩ + obtain ⟨A, primary, elig, -, -⟩ := facts clean agreed + have step := receive_primary r elig primary + rw [Ae.updateTerm_of_ge (by rw [A.term]; omega), + handle_stale r primary ok (by rw [A.term]; omega)] at step + exact concl_of step rfl agreed unmatched (by simp) + -- A success below the match index: no change, and the clean commit does not advance. + · rw [hv, ho] + refine ⟨rfl, fun clean _ agreed unmatched => ?_⟩ + obtain ⟨A, primary, elig, matched, -⟩ := facts clean agreed + have step := receive_primary r elig primary + rw [Ae.updateTerm_of_ge (by rw [A.term]; omega), + handle_ack r primary ok (by rw [A.term]; exact eq), + Nat.max_eq_left (by omega : r.lastLogIndex <= clean.matchIndex source), update_self, + show ({ clean with matchIndex := clean.matchIndex } : NodeState) = clean from rfl, + advance_run node clean primary] at step + have maximal : (saved.leadership != .leader + || decide (highestCommittableIndex (abs env.names saved) (env.names.id saved.nodeId) + <= saved.commitIdx)) = true := by + inv_conj invSaved "commit_maximal" + simp only [lead, bne_self_eq_false, Bool.false_or, decide_eq_true_eq] at maximal + have hle : highestCommittableIndex clean node <= clean.commitIndex := by + rw [hc_of_agrees A (fun n e => tracked_of_eligible pc lead A (by rw [savedId]; exact e)), + A.commit, ← savedId] + exact maximal + simp only [hle, ↓reduceIte, not_true_eq_false, false_and] at step + exact concl_of step rfl agreed unmatched (by simp) + -- A NACK: the send index moves back. + · rw [hv, ho] + refine ⟨rfl, fun clean _ agreed unmatched => ?_⟩ + obtain ⟨A, primary, elig, matched, sent⟩ := facts clean agreed + have step := receive_primary r elig primary + rw [Ae.updateTerm_of_ge (by rw [A.term]; omega), handle_nack r primary nok] at step + refine concl_of step rfl + (Agrees.to (agrees_setPeer A pc mem rfl rfl rfl rfl rfl rfl rfl rfl ?_ ?_) + ⟨by simp [State.setPeer, lead], by simp [State.setPeer, lead]⟩) unmatched (by simp) + · show clean.matchIndex = CCF.Function.update clean.matchIndex (env.names.id (env.names.name source)) nd.matchIdx + rw [hsrc, ← matched, update_self] + · show _ = CCF.Function.update clean.sentIndex (env.names.id (env.names.name source)) + (max (min (saved.highestMatch r.term r.lastLogIndex) nd.sentIdx) nd.matchIdx) + rw [hsrc, matched, sent, Ae.highestMatch_eq invSaved, ← A.log] + -- A success at or above the match index: the match index moves up and the commit may advance. + · have hv1 := setPeer_eq saved pc.sortedStr mem (p := ackPeer nd r) + rw [hv1] at run branch + generalize hW : ({ saved with + allOtherNodes := putPeer saved.allOtherNodes (env.names.name source) (ackPeer nd r) } + : State) = W at run branch + have wLead : W.leadership = .leader := by rw [← hW]; exact lead + have wKeys : W.allOtherNodes.map Prod.fst = saved.allOtherNodes.map Prod.fst := by + rw [← hW]; exact putPeer_keys _ _ _ + have wSorted : W.allOtherNodes.Pairwise fun p q => env.names.id p.1 < env.names.id q.1 := by + rw [← hW] + exact putPeer_sorted (r := fun a b => env.names.id a < env.names.id b) pc.sortedId + have hy0 := ReplUpdateCommit.Hyps.ofInv invSaved + have hy : ReplUpdateCommit.Hyps env.names W := by + rw [← hW] + refine { hy0 with peersNamed := fun p m => ?_ } + have : p.1 ∈ (putPeer saved.allOtherNodes (env.names.name source) (ackPeer nd r)).map + Prod.fst := List.mem_map_of_mem m + rw [putPeer_keys] at this + obtain ⟨q, mq, e⟩ := List.mem_map.mp this + rw [← e] + exact hy0.peersNamed q mq + have hcW : highestCommittableIndex (abs env.names W) node = res.getD saved.commitIdx := by + have := ReplUpdateCommit.updateCommit_eq hy run + rw [← hW] at this ⊢ + rw [← savedId] + exact this + have cleanSide : forall clean, agrees env.names clean saved = true + -> Agrees env.names (ackState clean source r.lastLogIndex) W + /\ clean.role = .primary /\ source ∈ eligiblePeers clean node + /\ highestCommittableIndex (ackState clean source r.lastLogIndex) node + = res.getD saved.commitIdx + /\ cleanRun node source clean r + = (advanceCommit (CCF.Capabilities.record node) (ackState clean source r.lastLogIndex) + node).run {} := by + intro clean agreed + obtain ⟨A, primary, elig, matched, sent⟩ := facts clean agreed + have A1 := agrees_setPeer (clean1 := ackState clean source r.lastLogIndex) (p := ackPeer nd r) + A pc mem rfl rfl rfl rfl rfl rfl rfl rfl + (by show CCF.Function.update clean.matchIndex source + (max (clean.matchIndex source) r.lastLogIndex) + = CCF.Function.update clean.matchIndex (env.names.id (env.names.name source)) + (max nd.matchIdx r.lastLogIndex) + rw [hsrc, matched]) + (by show clean.sentIndex = CCF.Function.update clean.sentIndex + (env.names.id (env.names.name source)) nd.sentIdx + rw [hsrc, ← sent, update_self]) + rw [hv1, hW] at A1 + have tracked : forall n, n ∈ eligiblePeers (ackState clean source r.lastLogIndex) node + -> n ∈ trackedPeers env.names W := by + intro n e + rw [← hW, trackedPeers_putPeer (names := env.names) (v := saved) + (w := { saved with + allOtherNodes := putPeer saved.allOtherNodes (env.names.name source) (ackPeer nd r) }) + rfl rfl] + rw [Ae.eligiblePeers_congr (a := ackState clean source r.lastLogIndex) (b := clean) + rfl rfl] at e + exact tracked_of_eligible pc lead A (by rw [savedId]; exact e) + refine ⟨A1, primary, elig, (hc_of_agrees A1 tracked).trans hcW, ?_⟩ + rw [receive_primary r elig primary, Ae.updateTerm_of_ge (by rw [A.term]; omega), + handle_ack r primary ok (by rw [A.term]; exact eq)] + rcases branch with ⟨hle, hv, ho⟩ | ⟨i, hi, lt, -, R⟩ + -- No commit. + · refine ⟨by rw [hv, ← hW], fun clean _ agreed unmatched => ?_⟩ + obtain ⟨A1, primary, elig, hc1, step⟩ := cleanSide clean agreed + rw [advance_run node (ackState clean source r.lastLogIndex) primary] at step + have h' : highestCommittableIndex (ackState clean source r.lastLogIndex) node + <= (ackState clean source r.lastLogIndex).commitIndex := by + rw [hc1] + show _ <= clean.commitIndex + rw [(Agrees.of agreed).commit] + exact hle + simp only [h', ↓reduceIte, not_true_eq_false, false_and] at step + rw [hv, ho] + exact concl_of step rfl (Agrees.to A1 ⟨by rw [wLead]; simp, by rw [wLead]; simp⟩) + (unmatched_update unmatched rfl rfl (eligible_mem_history elig) rfl) (by simp) + -- A commit. + · subst hi + obtain ⟨⟨kId, kView, kLedger, kLast, kNF, kVoted, kCommit⟩, -, R⟩ := R + refine ⟨by rw [kId, ← hW], fun clean _ agreed unmatched => ?_⟩ + obtain ⟨A1, primary, elig, hc1, step⟩ := cleanSide clean agreed + have A := Agrees.of agreed + simp only [Option.getD_some] at hc1 + have nle : ¬ i <= clean.commitIndex := by + rw [A.commit] + omega + rw [advance_run node (ackState clean source r.lastLogIndex) primary] at step + simp only [hc1] at step + simp only [nle, ↓reduceIte, not_false_eq_true, true_and] at step + have rciNone : (ackState clean source r.lastLogIndex).retiredCommittedIndex = none := + A.rci.trans (leader_rci_none invSaved lead) + have absLog : (abs env.names c.vars).log = clean.log := by + show (c.vars.ledger.toList.take c.vars.lastIdx).map _ = _ + rw [kLedger, kLast, ← hW] + exact A.log.symm + have hIdV : env.names.id c.vars.nodeId = node := by rw [kId, ← hW]; exact savedId + have rciEq : c.vars.retiredCommittedIdx = Ae.firstConf node clean.log i := by + have e : (c.vars.retiredCommittedIdx + == firstLogIndexAfter ((abs env.names c.vars).log.take c.vars.commitIdx) 0 + fun x => decide (env.names.id c.vars.nodeId ∈ x.metadata.retirementConfirmations)) + = true := by + inv_conj invVars "rci_first" + rw [absLog, kCommit, hIdV, beq_iff_eq] at e + exact e + have rcIff : (latch node (ackState clean source r.lastLogIndex) i).isRetiredCommitted node + <-> c.vars.isRetiredCommitted = true := by + have e : (c.vars.isRetiredCommitted + == decide ((abs env.names c.vars).isRetiredCommitted (env.names.id c.vars.nodeId))) + = true := by + inv_conj invVars "retired_committed" + rw [hIdV, beq_iff_eq] at e + rw [e, decide_eq_true_iff, Ae.isRetiredCommitted_iff, Ae.isRetiredCommitted_iff, absLog] + show _ <-> _ /\ c.vars.retiredCommittedIdx.isSome = true + rw [rciEq] + have trackedW : forall p, p ∈ W.allOtherNodes -> env.names.id p.1 ∈ trackedPeers env.names W := by + intro p m + simp only [trackedPeers, wLead, beq_self_eq_true, ↓reduceIte, List.mem_map] + exact ⟨p, m, rfl⟩ + rcases R with ⟨vl, vlid, ho, sub, -⟩ | ⟨vl, vlid, vrc, ho⟩ + -- Still leader. + · have notRC : (c.vars.leadership != .leader || !c.vars.isRetiredCommitted) = true := by + inv_conj invVars "leader_not_retired_committed" + simp only [vl, bne_self_eq_false, Bool.false_or, Bool.not_eq_true'] at notRC + have nrc : ¬ (latch node (ackState clean source r.lastLogIndex) i).isRetiredCommitted node := + fun h => by rw [rcIff.mp h] at notRC; cases notRC + rw [recordCommit_keep rciNone nrc] at step + simp only [nrc, ↓reduceIte] at step + have sortedV := (peerCtx invVars vl (by rw [kLast, ← hW]; exact L0)).sortedId + have trackedV : forall n, n ∈ trackedPeers env.names c.vars + -> exists p, p ∈ c.vars.allOtherNodes /\ env.names.id p.1 = n := by + intro n m + simp only [trackedPeers, vl, beq_self_eq_true, ↓reduceIte, List.mem_map] at m + exact m + have agreedV : Agrees env.names (latch node (ackState clean source r.lastLogIndex) i) + c.vars := by + refine ⟨?_, ?_, absLog.symm, kCommit.symm, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · show clean.role = _ + rw [primary, vl] + rfl + · show clean.currentTerm = c.vars.currentView + rw [A.term, kView, ← hW] + · intro n m + obtain ⟨p, mp, rfl⟩ := trackedV n m + have mW := sub p mp + exact ((A1.sent _ (trackedW p mW)).trans (abs_sentIndex_of_sorted wSorted mW)).trans + (abs_sentIndex_of_sorted sortedV mp).symm + · intro n m + obtain ⟨p, mp, rfl⟩ := trackedV n m + have mW := sub p mp + exact ((A1.match_ _ (trackedW p mW)).trans (abs_matchIndex_of_sorted wSorted mW)).trans + (abs_matchIndex_of_sorted sortedV mp).symm + · show clean.isNewFollower = c.vars.isNewFollower + rw [A.newFollower, kNF, ← hW] + · show clean.votedFor = _ + rw [A.voted, kVoted, ← hW] + · show clean.primaryKnown = c.vars.leaderId.isSome + rw [A.known, vlid, ← hW] + · show Ae.firstConf node clean.log i = _ + rw [rciEq] + rw [ho] + exact concl_of step rfl (Agrees.to agreedV ⟨by rw [vl]; simp, by rw [vl]; simp⟩) + (unmatched_update unmatched rfl rfl (eligible_mem_history elig) rfl) (by simp) + -- Stepped down, having nominated a successor. + · have yrc := rcIff.mpr vrc + rw [recordCommit_clear rciNone yrc] at step + have yrc' : ({ latch node (ackState clean source r.lastLogIndex) i with + role := .none, primaryKnown := false } : NodeState).isRetiredCommitted node := + (Ae.isRetiredCommitted_iff _ _).mpr ((Ae.isRetiredCommitted_iff _ _).mp yrc) + split at step + rotate_left + · exact absurd yrc' ‹_› + have matchedW : forall p, p ∈ W.allOtherNodes + -> (ackState clean source r.lastLogIndex).matchIndex (env.names.id p.1) = p.2.matchIdx := + fun p m => (A1.match_ _ (trackedW p m)).trans (abs_matchIndex_of_sorted wSorted m) + have succ := tvSuccessor_core invSaved lead (w := W) (c := ackState clean source r.lastLogIndex) + A.log A.commit wKeys (by rw [← hW]) matchedW + rw [savedId] at succ + have wId : W.nodeId = saved.nodeId := by rw [← hW] + have wView : W.currentView = saved.currentView := by rw [← hW] + have sends : nomSends node (ackState clean source r.lastLogIndex) + = nominationSends env.names W := by + unfold nomSends nominationSends + rw [← succ] + cases tvSuccessor W <;> simp [wLead, wId, savedId, wView, A.term] + have agreedV : Agrees env.names { latch node (ackState clean source r.lastLogIndex) i with + role := .none, primaryKnown := false } c.vars := by + refine ⟨by rw [vl]; rfl, ?_, absLog.symm, kCommit.symm, ?_, ?_, ?_, ?_, + by rw [vlid]; rfl, ?_⟩ + · show clean.currentTerm = c.vars.currentView + rw [A.term, kView, ← hW] + · intro n m + simp [trackedPeers, vl] at m + · intro n m + simp [trackedPeers, vl] at m + · show clean.isNewFollower = c.vars.isNewFollower + rw [A.newFollower, kNF, ← hW] + · show clean.votedFor = _ + rw [A.voted, kVoted, ← hW] + · show Ae.firstConf node clean.log i = _ + rw [rciEq] + rw [List.nil_append] at ho + rw [ho] + refine concl_of step sends + (Agrees.to agreedV ⟨by rw [vl]; simp, by rw [vl]; simp⟩) + (fun h => by simp at h) + ?_ + have hnode : env.names.id (env.names.name node) = node := by rw [← savedName]; exact savedId + intro envelope memE + rw [← sends] at memE + unfold nomSends at memE + cases hs : findSuccessor (ackState clean source r.lastLogIndex) node with + | none => simp [hs] at memE + | some t => + simp only [hs, Option.map_some, Option.toList_some, List.mem_singleton] at memE + subst memE + have ne := findSuccessor_ne hs + simp only [msgInv, hnode, beq_self_eq_true, Bool.true_and, bne_iff_ne, ne_eq, + Bool.and_true] + exact fun e => ne e.symm +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Nomination.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Nomination.lean new file mode 100644 index 000000000000..7df3d79310ab --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Nomination.lean @@ -0,0 +1,159 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeRespSuccessor + +@[expose] public section + +/-! +# Obligation: `nomination` (not reviewed) + +The driver's `nominate_successor`: a leader proposes a vote to the successor that +`find_successor` picks and changes nothing. The clean counterpart is the internal +`nominateSuccessor` input, whose successor is the same (`AeResp.tvSuccessor_eq`). A node +that is not a leader does nothing, matched by the empty clean run (the clean input would be +disabled by its primary guard). +-/ + +namespace Consensus.TraceValidation.Proofs.AeResp + +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation (Names Env abs agrees inv msgInv) +open Consensus.TraceValidation.Exec (State Ctx Action M) + +/-- What `nominate_successor` sends from `v`. -/ +def nominationSends (names : Names) (v : State) : Outbox := + if v.leadership = .leader then + ((tvSuccessor v).map + fun s => + CCF.Envelope.mk (names.id v.nodeId) (names.id s) + (Message.proposeRequestVoteRequest v.currentView)).toList + else + [] + +theorem findSuccessor_bind_run {α : Type} (f : Option Exec.NodeId -> M α) (c : Ctx) + : (Exec.becomeRetired.findSuccessor >>= f).run c + = (f (tvSuccessor c.vars)).run c := by + rw [StateT.run_bind, findSuccessor_run] + rfl + +theorem nominateUnsafe_spec {env : Env} + : Spec env Exec.nominateSuccessorUnsafe + fun v o _ v' o' => v' = v /\ o' = o ++ nominationSends env.names v := by + intro c a c' envOk h + unfold Exec.nominateSuccessorUnsafe Exec.becomeRetired.nominateSuccessorUnsafe at h + rw [getV_bind_run] at h + by_cases leader : c.vars.leadership = .leader + · simp only [leader, beq_self_eq_true, ↓reduceIte] at h + rw [findSuccessor_bind_run] at h + cases hs : tvSuccessor c.vars with + | none => + rw [hs] at h + simp only [StateT.run, Pure.pure, StateT.pure, Except.pure, Except.ok.injEq, + Prod.mk.injEq] at h + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, by simp [nominationSends, leader, hs]⟩ + | some s => + rw [hs] at h + dsimp only at h + have sp : Spec env + (do + Exec.trace "step_down_and_nominate_successor" + Exec.emitStr "to_node_id" s + Exec.send s (Message.proposeRequestVoteRequest c.vars.currentView)) + fun v o _ v' o' => + v' = v + /\ o' = o ++ [CCF.Envelope.mk (env.names.id v.nodeId) (env.names.id s) + (Message.proposeRequestVoteRequest c.vars.currentView)] := + Spec.weaken + (Spec.bind (Spec.trace _) fun _ => Spec.bind (Spec.emitStr _ _) fun _ => Spec.send _ _) + fun v o _ v' o' ⟨_, v1, o1, ⟨e1, f1⟩, _, v2, o2, ⟨e2, f2⟩, e3, f3⟩ => by + subst e1 f1 e2 f2 e3 f3 + exact ⟨rfl, rfl⟩ + obtain ⟨envEnd, hv, ho⟩ := sp c a c' envOk h + exact ⟨envEnd, hv, by simp [ho, nominationSends, leader, hs]⟩ + · have nl : (c.vars.leadership == .leader) = false := by simpa using leader + simp only [nl, Bool.false_eq_true, ↓reduceIte] at h + simp only [StateT.run, Pure.pure, StateT.pure, Except.pure, Except.ok.injEq, + Prod.mk.injEq] at h + obtain ⟨_, rfl⟩ := h + exact ⟨envOk, rfl, by simp [nominationSends, leader]⟩ + +theorem nominate_spec {env : Env} + : Spec env Exec.nominateSuccessor + fun v o _ v' o' => v' = v /\ o' = o ++ nominationSends env.names v := + Spec.weaken (Spec.bind (Spec.trace _) fun _ => nominateUnsafe_spec) + fun _ _ _ _ _ ⟨_, _, _, ⟨e1, f1⟩, e2, f2⟩ => by + subst e1 f1 e2 f2 + exact ⟨rfl, rfl⟩ + +end Consensus.TraceValidation.Proofs.AeResp + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation.Proofs.AeResp + +theorem nominationSound (env : Env) : NominationSound env := by + intro node saved actions c vars others cleanOthers _ hId invSaved _ _ ran _ finished _ + obtain ⟨hv, ho⟩ := Spec.run nominate_spec ran + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + rw [hv] + rw [List.nil_append] at ho + rw [ho] + refine ⟨rfl, fun clean _ agreed unmatched => ?_⟩ + by_cases leader : saved.leadership = .leader + · have parts := agreed + simp only [agrees, Bool.and_eq_true, beq_iff_eq, and_assoc] at parts + obtain ⟨cRole, cTerm, _⟩ := parts + have primary : clean.role = .primary := by + rw [cRole] + simp [abs, absRole, leader] + have succ := tvSuccessor_eq invSaved leader agreed + rw [hId] at succ + have selfNamed : env.names.name (env.names.id saved.nodeId) = saved.nodeId := + (ReplUpdateCommit.Hyps.ofInv invSaved).selfNamed + refine ⟨[.nominateSuccessor], clean, ?_, agreed, unmatched, by simp [admit], ?_⟩ + · have step := LocalRun.cons (protocol := protocol env) (node := node) (state := clean) + (middle := clean) (action := (protocol env).internal .nominateSuccessor) + (effects := { + outgoing := ((findSuccessor clean node).map fun t => + CCF.Envelope.mk node t + (Message.proposeRequestVoteRequest clean.currentTerm)).toList }) ?_ + (LocalRun.nil _) + · have sends : nominationSends env.names saved + = ((findSuccessor clean node).map fun t => + CCF.Envelope.mk node t + (Message.proposeRequestVoteRequest clean.currentTerm)).toList := by + rw [← succ, cTerm] + cases hs : tvSuccessor saved <;> simp [nominationSends, leader, hId, abs, hs] + rw [sends] + simpa [cleanActions] using step + · cases hs : findSuccessor clean node <;> + simp [Consensus.Model.protocol, Consensus.Model.Node.step, act, + Consensus.Model.Node.nominateSuccessor, guard, primary, hs, + CCF.Capabilities.record, modify, modifyGet, MonadStateOf.modifyGet, + StateT.run] <;> rfl + · intro envelope mem + simp only [nominationSends, leader, ↓reduceIte] at mem + cases hs : tvSuccessor saved with + | none => simp [hs] at mem + | some s => + simp only [hs, Option.map_some, Option.toList_some, List.mem_singleton] at mem + subst mem + have ne := findSuccessor_ne (succ ▸ (by simp [hs] : (tvSuccessor saved).map + env.names.id = some (env.names.id s))) + simp only [msgInv, selfNamed, beq_self_eq_true, Bool.true_and, bne_iff_ne, ne_eq, + Bool.and_true] + exact fun e => ne (by rw [← e, hId]) + · refine ⟨[], clean, ?_, agreed, unmatched, by simp, ?_⟩ + · simpa [cleanActions, nominationSends, leader] using LocalRun.nil (protocol := protocol env) + (node := node) clean + · simp [nominationSends, leader] + +end Consensus.TraceValidation.Proofs From d6ee2981cc3dd0e85c5373c5ff2b20906d4b02f7 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:24 +0000 Subject: [PATCH 13/25] Prove the tick obligation `periodic` refines the clean timeout steps: heartbeats, CheckQuorum step-down, and election and pre-vote timeouts, with the timers that no trace point records read from the node's next event. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 1 + .../TraceValidation/Proofs/Handlers/Tick.lean | 47 ++ .../Proofs/Handlers/TickElect.lean | 663 ++++++++++++++++++ .../Proofs/Handlers/TickLeader.lean | 217 ++++++ .../Proofs/Handlers/TickOrder.lean | 299 ++++++++ .../Proofs/Handlers/TickPeers.lean | 565 +++++++++++++++ .../Proofs/Handlers/TickRun.lean | 190 +++++ .../Proofs/Handlers/TickSend.lean | 254 +++++++ .../Proofs/Handlers/TickViews.lean | 189 +++++ .../Proofs/Handlers/TickVotes.lean | 225 ++++++ 10 files changed, 2650 insertions(+) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Tick.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickElect.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickLeader.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickOrder.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickPeers.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickRun.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickSend.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickViews.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickVotes.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index a9d6d3ccd7a7..38ba99223683 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -16,5 +16,6 @@ import Consensus.TraceValidation.Proofs.Handlers.RequestPreVote import Consensus.TraceValidation.Proofs.Handlers.RequestPreVoteResponse import Consensus.TraceValidation.Proofs.Handlers.RequestVote import Consensus.TraceValidation.Proofs.Handlers.RequestVoteResponse +import Consensus.TraceValidation.Proofs.Handlers.Tick import Consensus.TraceValidation.Proofs.Section import Consensus.TraceValidation.Proofs.Validator diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Tick.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Tick.lean new file mode 100644 index 000000000000..19b04ed86ef0 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Tick.lean @@ -0,0 +1,47 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickElect + +@[expose] public section + +/-! +# The `Tick` obligation (not reviewed) + +`Exec.periodic` is sound: its hold is matched by zero clean inputs, by heartbeats +(`sendEntries`), by a CheckQuorum step-down (`timeout .checkQuorum`) or by an election +timeout (`timeout .election`), as `tick_tri` and `el_tri` show over the ghost clean run. +-/ + +namespace Consensus.TraceValidation.Proofs + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv) + +theorem Tick.agrees_abs (names : Names) (d : State) + : agrees names (abs names d) d = true := by + simp [agrees] + +theorem tickSound (env : Env) : TickSound env := by + intro node saved actions c vars others cleanOthers _ self invS _ _ ran _ finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + have post := fun (clean0 : NodeState) (ag : agrees env.names clean0 saved = true) => + Life.Tri.run (Tick.tick_tri invS self ag fun _ _ _ => Tick.el_tri invS self ag) + ⟨rfl, rfl⟩ ran + refine ⟨(post _ (Tick.agrees_abs env.names saved)).1, fun clean _ ag unmatched => ?_⟩ + obtain ⟨inputs, clean', run, ad, sendsInv, ag', un⟩ := (post clean ag).2 invVars + exact ⟨ + inputs, + clean', + by simpa [cleanActions] using run, + ag', + un unmatched, + fun input mem => ad input mem cleanOthers, + sendsInv + ⟩ + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickElect.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickElect.lean new file mode 100644 index 000000000000..8d7d041c975d --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickElect.lean @@ -0,0 +1,663 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickOrder +public import Consensus.TraceValidation.Proofs.Handlers.TickLeader +public import Consensus.TraceValidation.Proofs.Handlers.VoteBecomeLeader + +@[expose] public section + +/-! +# A non-leader's election timeout (not reviewed; `Tick` obligation) + +The election timeout is one clean `timeout .election`: a pre-vote candidate that asks every +other active member, or, if every configuration is the node alone, a candidate, and then a +primary that sends its heartbeats. +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) +open Life (Tri Pres) + +variable {env : Env} + +/-! ## Vote requests -/ + +/-- The vote request `sendRequestVote pre` sends from `v`. -/ +def rvMsg (pre : Bool) (v : State) : Message := + let r : RequestVoteRequest := + { + term := v.currentView, + lastCommittableTerm := v.getTerm v.lastCommittable, + lastCommittableIndex := v.lastCommittable + } + if pre then .requestPreVoteRequest r else .requestVoteRequest r + +theorem tri_sendRequestVote (pre : Bool) (to : NodeId) (v : State) (O : Outbox) + (h : v.commitIdx <= v.lastCommittable) + : Tri env (fun w o => w = v /\ o = O) (sendRequestVote pre to) + (fun _ w o => + w = v /\ o = O ++ [⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩]) := by + unfold sendRequestVote + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + dsimp only + refine Tri.ite (fun lt => absurd h (Nat.not_le.mpr lt)) fun _ => ?_ + refine tri_keeps_bind (Spec.trace _) fun _ => tri_keeps_bind (Spec.emit _ _) fun _ => + tri_keeps_bind (Spec.emitStr _ _) fun _ => Tri.send fun w o ⟨hw, ho⟩ => ?_ + subst w o + exact ⟨rfl, rfl⟩ + +theorem tri_rvLoop (pre : Bool) (v : State) (h : v.commitIdx <= v.lastCommittable) + : forall (l : List NodeId) (O : Outbox), + Tri env (fun w o => w = v /\ o = O) + (forIn l PUnit.unit + fun id _ => do + sendRequestVote pre id + pure (ForInStep.yield PUnit.unit)) + (fun _ w o => + w = v + /\ o + = O + ++ l.map + fun to => ⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩) + | [], O => by + rw [List.forIn_nil] + exact Tri.conseq (Tri.pure' _) (fun w o ⟨hw, ho⟩ => ⟨hw, by simp [ho]⟩) (fun _ _ _ h => h) + | to :: rest, O => by + rw [List.forIn_cons] + refine Tri.bind (Tri.bind (tri_sendRequestVote pre to v O h) fun _ => + Tri.conseq (Tri.pure' (Q := fun r w o => r = ForInStep.yield PUnit.unit /\ w = v + /\ o = O ++ [⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩]) _) + (fun _ _ h => ⟨rfl, h⟩) (Q := fun r w o => (w = v + /\ o = O ++ [⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩]) + /\ r = ForInStep.yield PUnit.unit) (fun _ _ _ h => by + obtain ⟨a, b, c⟩ := h + exact ⟨⟨b, c⟩, a⟩)) fun r => ?_ + refine tri_pre_prop fun hr => ?_ + subst hr + exact Tri.conseq (tri_rvLoop pre v h rest _) (fun _ _ h => h) + (fun _ _ _ ⟨hw, ho⟩ => ⟨hw, by simp [ho]⟩) + +/-! ## The election guard -/ + +/-- A node that can start an election has a ledger entry. -/ +theorem guard_pos {names : Names} {d : State} {n : NodeID} + (g : canStartElection (abs names d) n) + : 0 < d.lastIdx := by + refine Nat.pos_of_ne_zero fun h => ?_ + have hl : (abs names d).log = [] := by simp [abs, h] + obtain ⟨-, mem, -⟩ := g + unfold NodeState.signedActiveConfigurations NodeState.activeConfigurations + NodeState.retirementCompletedNodes NodeState.committedLog at mem + rw [hl] at mem + simp [activeConfigurations, configurationHistory, configurationMembers, + latestConfigurationMembers, retiredCommittedNodes, CCF.Finset.mem_sdiff] at mem + +/-! ## The states of the election -/ + +/-- The vote records once the node voted for itself. -/ +def marked (v : State) : List (Nat × List NodeId × Nat) := + v.configurations.map + fun c => + (c.idx, if Lists v.nodeId c then [v.nodeId] else [], State.quorum c.nodes.length) + +/-- The declared pre-vote candidate once it voted for itself. -/ +def pvState (v : State) : State := + { v with leadership := .preVoteCandidate, leaderId := none, votesForMe := marked v } + +/-- The declared candidate once it voted for itself. -/ +def candState (v : State) : State := + { + v with + leadership := .candidate, + leaderId := none, + votedFor := some v.nodeId, + votesForMe := marked v, + currentView := v.currentView + 1 + } + +/-- The clean pre-vote candidate. -/ +def cleanPv (c : NodeState) (node : NodeID) : NodeState := + { c with role := .preVoteCandidate, primaryKnown := false, preVotesGranted := {node} } + +/-- The clean candidate. -/ +def cleanCand (c : NodeState) (node : NodeID) : NodeState := + { + cleanPv c node with + role := .candidate, + currentTerm := c.currentTerm + 1, + votedFor := some node, + primaryKnown := false, + votesGranted := {node}, + preVotesGranted := ∅ + } + +theorem agrees_pv {names : Names} {c : NodeState} {d : State} + (ag : agrees names c d = true) + : agrees names (cleanPv c (names.id d.nodeId)) (pvState d) = true := by + obtain ⟨h1, h2, h3, h4, h5, h6⟩ := Vote.agrees_frame ag + have votes := selfVotes_set (names := names) d.configurations d.nodeId + simp only [agrees, Bool.and_eq_true, beq_iff_eq] + simp [cleanPv, pvState, abs, trackedPeers, absRole, h1, h2, h3, h4, h5, h6, marked, votes] + +theorem agrees_cand {names : Names} {c : NodeState} {d : State} + (ag : agrees names c d = true) + : agrees names (cleanCand c (names.id d.nodeId)) (candState d) = true := by + obtain ⟨h1, h2, h3, h4, h5, h6⟩ := Vote.agrees_frame ag + have votes := selfVotes_set (names := names) d.configurations d.nodeId + simp only [agrees, Bool.and_eq_true, beq_iff_eq] + simp [cleanCand, cleanPv, candState, abs, trackedPeers, absRole, h1, h2, h3, h4, h5, h6, marked, + votes] + +/-! ## The guard on both sides -/ + +theorem tri_guard (saved : State) + : Tri env (fun w o => w = saved /\ o = []) electionGuard + (fun _ w o => + (w = saved /\ o = []) + /\ canStartElection (abs env.names saved) (env.names.id saved.nodeId)) := by + unfold electionGuard + refine tri_names (tri_getV fun w o ⟨hw, ho⟩ => ?_) + subst w o + refine Tri.ite (fun g => ?_) (fun _ => ?_) + · exact Tri.conseq (Tri.pure' (Q := fun _ w o => (w = saved /\ o = []) + /\ canStartElection (abs env.names saved) (env.names.id saved.nodeId)) _) + (fun _ _ h => ⟨h, of_decide_eq_true g⟩) (fun _ _ _ h => h) + · exact tri_keeps_bind Spec.curLoc fun _ => Tri.fail _ + +theorem canStartElection_congr {a b : NodeState} (hr : a.role = b.role) + (hl : a.log = b.log) (hc : a.commitIndex = b.commitIndex) + (hrc : a.retiredCommittedIndex = b.retiredCommittedIndex) (n : NodeID) + (g : canStartElection b n) + : canStartElection a n := by + have ret := Vote.retirement_congr hl hc hrc n + unfold canStartElection NodeState.signedActiveConfigurations NodeState.activeConfigurations + NodeState.retirementCompletedNodes NodeState.committedLog NodeState.isRetiredCommitted at * + rw [hr, hl, hc, ret] + exact g + +theorem guard_clean {names : Names} {c : NodeState} {d : State} + (ag : agrees names c d = true) + (g : canStartElection (abs names d) (names.id d.nodeId)) + : canStartElection c (names.id d.nodeId) := by + obtain ⟨-, hl, hc, -, -, hrc⟩ := Vote.agrees_frame ag + have hr : c.role = (abs names d).role := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at ag + exact ag.1.1.1.1.1.1.1.1.1.1 + exact canStartElection_congr hr hl hc hrc _ g + +/-! ## Facts from the invariant -/ + +theorem names_sorted_of {names : Names} {d : State} (h : inv names d = true) + (ne : d.configurations ≠ []) + : names.known.toList.Pairwise (· < ·) := by + have hs : (d.configurations.isEmpty && d.allOtherNodes.isEmpty + || (names.known.toList.zip names.known.toList.tail).all fun (x, y) => decide (x < y)) + = true := by + inv_conj h "names_sorted" + have e : d.configurations.isEmpty = false := by simpa using ne + simp only [e, Bool.false_and, Bool.false_or] at hs + exact pairwise_of_adjacent' (R := fun x y : NodeId => x < y) String.lt_trans hs + +theorem members_known_of {names : Names} {d : State} (h : inv names d = true) + : forall x, x ∈ d.configurations -> forall a, a ∈ x.nodes -> a.1 ∈ names.known := by + have hk : ((d.configurations.flatMap (·.nodes.map Prod.fst)).all names.known.contains) + = true := by + inv_conj h "members_known" + intro x xm a am + simp only [List.all_eq_true, List.mem_flatMap, List.mem_map] at hk + have := hk a.1 ⟨x, xm, a, am, rfl⟩ + simpa using this + +/-! ## The vote requests on both sides -/ + +open ReplUpdateCommit (absConfig Shifted Named named_inj) in +/-- The clean pre-vote broadcast goes to the nodes M_tv asks, in its order. -/ +theorem others_eq {names : Names} {v : State} {active : List Configuration} + {D : List Config} {ci : Nat} (hD : active = D.map (absConfig names)) + (sh : Shifted ci D v.configurations) (sorted : names.known.toList.Pairwise (· < ·)) + (known : forall x, x ∈ v.configurations -> forall a, a ∈ x.nodes -> a.1 ∈ names.known) + (selfNamed : Named names v.nodeId) + (named : forall x, x ∈ v.configurations -> forall a, a ∈ x.nodes -> Named names a.1) + : ((configurationMembers active).erase (names.id v.nodeId)).sort + = v.otherNodesInActiveConfigs.map names.id := by + refine CCF.Finset.eq_of_sorted_of_mem_iff (CCF.Finset.sorted _) + (others_ids_sorted sorted known) fun n => ?_ + rw [CCF.Finset.mem_sort, CCF.Finset.mem_erase, active_members_iff hD sh, List.mem_map] + constructor + · rintro ⟨ne, y, ym, a, am, rfl⟩ + refine ⟨a.1, mem_others.mpr ⟨⟨y, ym, a, am, rfl⟩, fun e => ne (by rw [e])⟩, rfl⟩ + · rintro ⟨s, sm, rfl⟩ + obtain ⟨⟨y, ym, a, am, rfl⟩, ne⟩ := mem_others.mp sm + exact ⟨fun e => ne (named_inj (named y ym a am) selfNamed e), y, ym, a, am, rfl⟩ + +theorem msgInv_rv {names : Names} {src tgt : NodeID} (r : RequestVoteRequest) (pre : Bool) + (hn : names.id (names.name src) = src) (ne : src ≠ tgt) + : msgInv names + ⟨src, tgt, if pre then .requestPreVoteRequest r else .requestVoteRequest r⟩ + = true := by + cases pre <;> simp [msgInv, hn, ne] + +/-- M_tv's vote request is the clean one. -/ +theorem rvMsg_clean {names : Names} {c : NodeState} {d : State} (h : inv names d = true) + (ag : agrees names c d = true) (pre : Bool) + : rvMsg pre d + = if pre then + .requestPreVoteRequest (makeRequestVoteRequest c) + else + .requestVoteRequest (makeRequestVoteRequest c) := by + obtain ⟨ht, hl, hc, -⟩ := Vote.agrees_frame ag + obtain ⟨-, h2, h3, -⟩ := Vote.inv_parts h + have bounds := Vote.lastCommittable_bounds h2 h3 + have lci : lastCommittableIndex c = d.lastCommittable := by + unfold lastCommittableIndex + rw [hl, hc, ← Vote.lastCommittable_eq h] + exact Nat.max_eq_right bounds.1 + have r : makeRequestVoteRequest c + = { term := d.currentView, lastCommittableTerm := d.getTerm d.lastCommittable, + lastCommittableIndex := d.lastCommittable } := by + simp only [makeRequestVoteRequest, lastCommittableTerm, lci, ht, hl, Vote.getTerm_eq h] + rw [r] + rfl + +/-! ## The clean election -/ + +/-- The clean pre-vote broadcast of `node` from `c`. -/ +def pvSends (c : NodeState) (node : NodeID) : List (CCF.Envelope NodeID Message) := + ((cleanPv c node).activeMembers.erase node).sort.map + fun p => + ⟨node, p, .requestPreVoteRequest (makeRequestVoteRequest (cleanPv c node))⟩ + +theorem emits_broadcast (node : NodeID) (st : NodeState) (m : Message) + : Emits (broadcastToOthers (CCF.Capabilities.record node) node st m) () + ((st.activeMembers.erase node).sort.map fun p => ⟨node, p, m⟩) := by + unfold broadcastToOthers + exact emits_congr (emits_bind (emits_forIn _ fun _ => m) (emits_pure ())) rfl (List.append_nil _) + +theorem clean_pv {c : NodeState} {node : NodeID} (g : canStartElection c node) + (nq : Not (hasQuorum c.activeConfigurations {node})) + : Emits (act (CCF.Capabilities.record node) node c (.timeout .election)) + (cleanPv c node) (pvSends c node) := by + show Emits (startElection _ c node) _ _ + unfold startElection + refine emits_congr (emits_bind (emits_guard g) ?_) rfl (List.nil_append _) + unfold Model.Node.becomePreVoteCandidate + have nq' : Not (hasQuorum (cleanPv c node).activeConfigurations (cleanPv c node).preVotesGranted) := + nq + show Emits (if hasQuorum (cleanPv c node).activeConfigurations (cleanPv c node).preVotesGranted + then _ else _) _ _ + rw [ite_eq_right nq'] + exact emits_congr (emits_bind (emits_broadcast _ _ _) (emits_pure _)) rfl (List.append_nil _) + +theorem clean_cand {c : NodeState} {node : NodeID} (g : canStartElection c node) + (q : hasQuorum c.activeConfigurations {node}) + (alone : ((cleanCand c node).activeMembers.erase node).sort = []) + {sends : List (CCF.Envelope NodeID Message)} + (hp + : Emits (becomePrimary (CCF.Capabilities.record node) node (cleanCand c node)) + (primaryState (cleanCand c node)) sends) + : Emits (act (CCF.Capabilities.record node) node c (.timeout .election)) + (primaryState (cleanCand c node)) sends := by + show Emits (startElection _ c node) _ _ + unfold startElection + refine emits_congr (emits_bind (emits_guard g) ?_) rfl (List.nil_append _) + unfold Model.Node.becomePreVoteCandidate + have q' : hasQuorum (cleanPv c node).activeConfigurations (cleanPv c node).preVotesGranted := q + show Emits + (if hasQuorum (cleanPv c node).activeConfigurations + (cleanPv c node).preVotesGranted then + _ + else + _) + _ _ + rw [ite_eq_left q'] + unfold Model.Node.becomeCandidate + have nr : Not ((cleanCand c node).isRetiredCommitted node) := by + have := Vote.retirement_congr (a := cleanCand c node) (b := c) rfl rfl rfl node + simp only [NodeState.isRetiredCommitted, this] + exact g.2.2 + have e : Emits (electIfQuorum (CCF.Capabilities.record node) node (cleanCand c node)) + (primaryState (cleanCand c node)) sends := by + unfold electIfQuorum + rw [ite_eq_left ⟨rfl, q, nr⟩] + exact hp + refine emits_congr (emits_bind e (emits_bind (emits_broadcast node (cleanCand c node) _) + (emits_pure _))) rfl ?_ + rw [alone] + simp + +theorem pvSends_eq {saved : State} {clean0 : NodeState} + (invS : inv env.names saved = true) (ag : agrees env.names clean0 saved = true) + (L0 : 0 < saved.lastIdx) (ne : saved.configurations ≠ []) + : pvSends clean0 (env.names.id saved.nodeId) + = saved.otherNodesInActiveConfigs.map + fun to => + ⟨env.names.id saved.nodeId, env.names.id to, rvMsg true saved⟩ := by + have H := ReplUpdateCommit.Hyps.ofInv invS + obtain ⟨D, hD, sh⟩ := H.configs L0 + obtain ⟨-, hl, hc, -⟩ := Vote.agrees_frame ag + have act : (cleanPv clean0 (env.names.id saved.nodeId)).activeMembers + = configurationMembers (activeConfigurations (abs env.names saved).log saved.commitIdx) := by + show configurationMembers (activeConfigurations clean0.log clean0.commitIndex) = _ + rw [hl, hc] + unfold pvSends + rw [act, others_eq hD sh (names_sorted_of invS ne) (members_known_of invS) H.selfNamed + H.membersNamed, List.map_map, rvMsg_clean invS ag true] + rfl + +theorem pvSends_inv {names : Names} {c : NodeState} {self : Exec.NodeId} + (selfNamed : ReplUpdateCommit.Named names self) + : forall e, e ∈ pvSends c (names.id self) -> msgInv names e = true := by + intro e mem + simp only [pvSends, List.mem_map, CCF.Finset.mem_sort, CCF.Finset.mem_erase] at mem + obtain ⟨p, ⟨ne, -⟩, rfl⟩ := mem + have hn : names.id (names.name (names.id self)) = names.id self := congrArg names.id selfNamed + simp [msgInv, hn, Ne.symm ne] + +/-! ## M_tv's election -/ + +/-- The vote-request loop that ends `becomePreVoteCandidate` and `becomeCandidate`. -/ +abbrev rvLoop (pre : Bool) : M Unit := do + let v ← getV + forIn v.otherNodesInActiveConfigs PUnit.unit + fun id _ => do + sendRequestVote pre id + pure (ForInStep.yield PUnit.unit) + pure () + +theorem tri_loopNone (pre : Bool) {P : State -> Outbox -> Prop} + (h : forall w o, P w o -> w.otherNodesInActiveConfigs = []) + : Tri env P (rvLoop pre) (fun _ => P) := by + refine Tri.getV_bind fun v => ?_ + intro c a c' e ⟨p, hv⟩ run + subst hv + rw [h _ _ p, List.forIn_nil] at run + exact Tri.bind (Tri.pure' (Q := fun _ => P) PUnit.unit) (fun _ => Tri.pure' (Q := fun _ => P) ()) + c a c' e p run + +theorem tri_loopAll (pre : Bool) (v : State) (O : Outbox) + (h : v.commitIdx <= v.lastCommittable) + : Tri env (fun w o => w = v /\ o = O) (rvLoop pre) + (fun _ w o => + w = v + /\ o + = O + ++ v.otherNodesInActiveConfigs.map + fun to => + ⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩) := + tri_getV + fun w o ⟨hw, ho⟩ => by + subst w o + exact Tri.bind (tri_rvLoop pre v h _ O) fun _ => Tri.pure' (Q := fun _ w o => w = v + /\ o = O ++ v.otherNodesInActiveConfigs.map fun to => + ⟨env.names.id v.nodeId, env.names.id to, rvMsg pre v⟩) () + +theorem tri_selfVote (v : State) (O : Outbox) (ne : v.configurations ≠ []) + (sorted : v.configurations.Pairwise fun a b => a.idx < b.idx) + (reset + : v.votesForMe + = v.configurations.map fun c => (c.idx, [], State.quorum c.nodes.length)) + : Tri env (fun w o => w = v /\ o = O) (recordVote v.nodeId) + (fun b w o => + (w = { v with votesForMe := marked v } /\ o = O) + /\ b + = decide + (forall c, + c ∈ v.configurations + -> Lists v.nodeId c /\ c.nodes.length <= 1)) := by + refine Tri.conseq (tri_recordVote v.nodeId v O ne) (fun _ _ h => h) fun b w o h => ?_ + obtain ⟨hw, ho, hb⟩ := h + rw [reset, selfVote_eq _ _ sorted] at hw hb + rw [selfVote_all] at hb + exact ⟨⟨hw, ho⟩, hb⟩ + +/-! ## The candidate that elects itself -/ + +theorem leaderPre_cand {names : Names} {saved : State} (invS : inv names saved = true) + : Vote.LeaderPre names (candState saved) := by + have H := ReplUpdateCommit.Hyps.ofInv invS + obtain ⟨-, -, -, h4, -⟩ := Vote.inv_parts invS + have vl : saved.views.all (· <= saved.lastIdx + 1) = true := by + inv_conj invS "views_le_last" + have rc : saved.isRetiredCommitted + = decide ((abs names saved).isRetiredCommitted (names.id saved.nodeId)) := by + inv_conj invS "retired_committed" + have hp : (saved.lastIdx == 0 || saved.leadership == .none + || saved.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names saved) (names.id saved.nodeId)).sort) = true := by + inv_conj invS "peers" + have hp' : (saved.lastIdx == 0 || saved.leadership != .none + || saved.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names saved) (names.id saved.nodeId)).sort) = true := by + inv_conj invS "peers_without_role" + refine ⟨ + by simp [candState], + Nat.lt_succ_of_le H.viewsBounded, + ?_, + H.size, + H.commitLe, + H.committable, + h4, + H.terms, + ?_, + ?_ + ⟩ + · intro x mem + exact of_decide_eq_true (Array.all_eq_true_iff_forall_mem.mp vl x (Array.mem_toList_iff.mp mem)) + · show saved.isRetiredCommitted = _ + rw [rc] + simp only [NodeState.isRetiredCommitted] + rfl + · have e := Vote.eligiblePeers_congr (a := abs names (candState saved)) (b := abs names saved) + rfl rfl (names.id saved.nodeId) + show saved.lastIdx = 0 \/ saved.allOtherNodes.map (fun x => names.id x.1) + = (eligiblePeers (abs names (candState saved)) (names.id saved.nodeId)).sort + rw [e] + by_cases z : saved.lastIdx = 0 + · exact Or.inl z + · refine Or.inr ?_ + by_cases n : saved.leadership = .none + · simpa [z, n] using hp' + · simpa [z, n] using hp + +theorem others_nil {w : State} + (alone : forall c, c ∈ w.configurations -> Lists w.nodeId c /\ c.nodes.length <= 1) + : w.otherNodesInActiveConfigs = [] := by + refine List.eq_nil_iff_forall_not_mem.mpr fun s mem => ?_ + obtain ⟨⟨x, xm, a, am, rfl⟩, ne⟩ := mem_others.mp mem + obtain ⟨l, len⟩ := alone x xm + simp only [Lists, List.any_eq_true, beq_iff_eq] at l + obtain ⟨b, bm, hb⟩ := l + match h : x.nodes, am, bm, len with + | [y], am, bm, _ => + simp only [List.mem_singleton] at am bm + exact ne (by rw [am, ← bm, hb]) + | [], am, _, _ => simp at am + | _ :: _ :: _, _, _, len => simp at len + +open ReplUpdateCommit (absConfig Shifted Named) in +theorem cand_alone {names : Names} {saved : State} {c : NodeState} {D : List Config} + (hD : activeConfigurations c.log c.commitIndex = D.map (absConfig names)) + (sh : Shifted saved.commitIdx D saved.configurations) + (alone + : forall x, x ∈ saved.configurations -> Lists saved.nodeId x /\ x.nodes.length <= 1) + : ((cleanCand c (names.id saved.nodeId)).activeMembers.erase + (names.id saved.nodeId)).sort + = [] := by + refine List.eq_nil_iff_forall_not_mem.mpr fun n mem => ?_ + rw [CCF.Finset.mem_sort, CCF.Finset.mem_erase] at mem + obtain ⟨ne, mem⟩ := mem + have := (active_members_iff (names := names) hD sh).mp mem + obtain ⟨y, ym, a, am, rfl⟩ := this + have one : saved.otherNodesInActiveConfigs = [] := others_nil alone + by_cases e : a.1 = saved.nodeId + · exact ne (by rw [e]) + · have := mem_others.mpr ⟨⟨y, ym, a, am, rfl⟩, e⟩ + rw [one] at this + simp at this + +/-! ## The election in M_tv -/ + +theorem tri_setV_bind {β : Type} {f : State -> State} {k : PUnit -> M β} {v : State} + {O : Outbox} {R : β -> State -> Outbox -> Prop} + (h : Tri env (fun w o => w = f v /\ o = O) (k ()) R) + : Tri env (fun w o => w = v /\ o = O) (Exec.setV f >>= k) R := + Tri.bind + (Tri.setV (Q := fun _ w o => w = f v /\ o = O) fun _ _ ⟨hw, ho⟩ => ⟨by rw [hw], ho⟩) + fun _ => h + +theorem tri_ofHoare {α : Type} {P : State -> Outbox -> Prop} {x : M α} + {Q : α -> State -> Outbox -> Prop} (h : Ae.Hoare env P x Q) + : Tri env P x Q := + h + +/-- Where a self-elected candidate ends. -/ +def ElPost (env : Env) (saved : State) (clean0 : NodeState) (v : State) (o : Outbox) + : Prop := + v.nodeId = saved.nodeId + /\ v.otherNodesInActiveConfigs = [] + /\ (inv env.names v = true + -> Acc env (env.names.id saved.nodeId) clean0 + (Final env.names (env.names.id saved.nodeId) clean0) v o) + +open ReplUpdateCommit (absConfig Shifted) in +theorem tri_cand {saved : State} {clean0 : NodeState} {D : List Config} + (invS : inv env.names saved = true) (ag : agrees env.names clean0 saved = true) + (g : canStartElection clean0 (env.names.id saved.nodeId)) + (ne : saved.configurations ≠ []) + (sorted : saved.configurations.Pairwise fun a b => a.idx < b.idx) + (hD + : activeConfigurations clean0.log clean0.commitIndex = D.map (absConfig env.names)) + (sh : Shifted saved.commitIdx D saved.configurations) + (alone + : forall x, x ∈ saved.configurations -> Lists saved.nodeId x /\ x.nodes.length <= 1) + (q : hasQuorum clean0.activeConfigurations {env.names.id saved.nodeId}) + : Tri env (fun w o => w = pvState saved /\ o = []) Exec.becomeCandidate + (fun _ => ElPost env saved clean0) := by + unfold Exec.becomeCandidate Exec.resetVotesForMe + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + refine Tri.ite (fun e => Tri.preFalse fun _ _ _ => ne (by simpa [pvState] using e)) + fun _ => ?_ + refine tri_setV_bind + (tri_setV_bind (tri_setV_bind (tri_keeps_bind (Spec.trace _) fun _ => ?_))) + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + refine Tri.bind (tri_selfVote _ [] ne sorted rfl) fun b => tri_pre_prop fun hb => ?_ + have hb' : b = true := hb.trans (decide_eq_true alone) + subst hb' + dsimp only + refine Tri.ite (fun _ => ?_) (fun nb => absurd rfl nb) + refine Tri.bind (Q := fun _ => ElPost env saved clean0) (Tri.discard ?_) + fun _ => tri_loopNone false fun _ _ h => h.2.1 + have hl := Vote.becomeLeader_spec env (c := cleanCand clean0 (env.names.id saved.nodeId)) + (d := candState saved) (o0 := []) (leaderPre_cand invS) (agrees_cand ag) + refine Tri.conseq (P' := fun v o => v = candState saved /\ o = []) + (tri_ofHoare hl) + (fun w o h => ⟨by rw [h.1]; rfl, h.2⟩) fun _ v o h => ?_ + rcases h with ⟨ret, -, -, -⟩ | ⟨-, -, sends, ho, hn, -, -, sub, fin⟩ + · exfalso + exact g.2.2 ret + · refine ⟨hn, others_nil fun x xm => ?_, fun hinv => ?_⟩ + · rw [hn] + exact alone x (sub x xm) + · obtain ⟨em, agv, sinv⟩ := fin hinv + subst ho + exact Acc.extend (Acc.start (R := fun c v => c = clean0 /\ v = saved) ⟨rfl, rfl⟩) + (fun clean ⟨hc, _⟩ => by subst hc; exact ⟨.timeout .election, _, + clean_cand g q (cand_alone hD sh alone) em, admitted_timeout _, + agv, fun _ => Vote.unmatched_primaryState _ _⟩) sinv + +open ReplUpdateCommit (absConfig) in +/-- A non-leader's election timeout: a pre-vote broadcast, or, alone in every configuration, +a self-election. -/ +theorem el_tri {saved : State} {clean0 : NodeState} {node : NodeID} + (invS : inv env.names saved = true) (self : env.names.id saved.nodeId = node) + (ag : agrees env.names clean0 saved = true) + : Tri env (fun w o => w = saved /\ o = []) + (do + electionGuard; note Note.electionTimeout; Exec.becomePreVoteCandidate) + (fun _ v o => + v.nodeId = saved.nodeId + /\ (inv env.names v = true + -> Acc env node clean0 (Final env.names node clean0) v o)) := by + subst self + refine Tri.bind (tri_guard saved) fun _ => tri_pre_prop fun g => ?_ + refine tri_keeps_bind (Spec.note _) fun _ => ?_ + have g' := guard_clean ag g + have L0 := guard_pos g + have H := ReplUpdateCommit.Hyps.ofInv invS + obtain ⟨D, hD, sh⟩ := H.configs L0 + obtain ⟨-, hl, hc, -⟩ := Vote.agrees_frame ag + have hD' : activeConfigurations clean0.log clean0.commitIndex = D.map (absConfig env.names) := by + rw [hl, hc] + exact hD + have sorted := H.sorted L0 + have qiff := hasQuorum_self hD' sh H.selfNamed H.membersNamed H.distinct + unfold Exec.becomePreVoteCandidate Exec.resetVotesForMe Exec.addVoteForMe + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + refine Tri.ite + (fun _ => + Tri.conseq + (Tri.pure' + (Q := + fun _ v o => + v.nodeId = saved.nodeId + /\ (inv env.names v = true + -> Acc env (env.names.id saved.nodeId) clean0 + (Final env.names (env.names.id saved.nodeId) clean0) v o)) + _) + (fun w o ⟨hw, ho⟩ => by subst hw ho; exact ⟨rfl, fun _ => Acc.start ⟨ag, id⟩⟩) + (fun _ _ _ h => h)) + fun hne => ?_ + have ne : saved.configurations ≠ [] := by simpa using hne + refine tri_setV_bind (tri_setV_bind (tri_keeps_bind (Spec.trace _) fun _ => ?_)) + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + by_cases al : + forall x, x ∈ saved.configurations -> Lists saved.nodeId x /\ x.nodes.length <= 1 + · refine Tri.bind (Q := fun _ => ElPost env saved clean0) ?_ fun _ => + Tri.conseq (tri_loopNone true fun _ _ h => h.2.1) (fun _ _ h => h) + fun _ _ _ h => ⟨h.1, h.2.2⟩ + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + refine Tri.bind (tri_selfVote _ [] ne sorted rfl) fun b => tri_pre_prop fun hb => ?_ + have hb' : b = true := hb.trans (decide_eq_true al) + subst hb' + dsimp only + refine Tri.ite (fun _ => ?_) (fun nb => absurd rfl nb) + exact Tri.conseq (tri_cand invS ag g' ne sorted hD' sh al (qiff.mpr ⟨ne, al⟩)) + (fun w o h => ⟨by rw [h.1]; rfl, h.2⟩) (fun _ _ _ h => h) + · refine Tri.bind (Q := fun _ w o => w = pvState saved /\ o = []) ?_ fun _ => ?_ + · refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + refine Tri.bind (tri_selfVote _ [] ne sorted rfl) fun b => tri_pre_prop fun hb => ?_ + have hb' : b = false := hb.trans (decide_eq_false al) + subst hb' + dsimp only + refine Tri.ite (fun nb => absurd nb Bool.false_ne_true) fun _ => ?_ + exact Tri.conseq (Tri.pure' (Q := fun _ w o => w = pvState saved /\ o = []) _) + (fun w o h => ⟨by rw [h.1]; rfl, h.2⟩) (fun _ _ _ h => h) + · have cl := (Vote.lastCommittable_bounds H.commitLe H.committable).1 + refine Tri.conseq (tri_loopAll true (pvState saved) [] cl) (fun _ _ h => h) + fun _ v o ⟨hv, ho⟩ => ⟨by rw [hv]; rfl, fun _ => ?_⟩ + subst hv + have e : o = [] ++ pvSends clean0 (env.names.id saved.nodeId) := by + rw [ho, pvSends_eq invS ag L0 ne] + rfl + subst e + exact Acc.extend (Acc.start (R := fun c v => c = clean0 /\ v = saved) ⟨rfl, rfl⟩) + (fun clean ⟨hc, _⟩ => by + subst hc + exact ⟨.timeout .election, _, clean_pv g' fun q => al (qiff.mp q).2, + admitted_timeout _, agrees_pv ag, fun _ h => by simp [cleanPv] at h⟩) + (pvSends_inv H.selfNamed) + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickLeader.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickLeader.lean new file mode 100644 index 000000000000..e560cdfd5d5c --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickLeader.lean @@ -0,0 +1,217 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickSend + +@[expose] public section + +/-! +# The `Tick` obligation (not reviewed) + +A tick hold (`Exec.periodic`) is, depending on the role and on the untraced timers that the +next trace point resolves: nothing; a leader's heartbeat (one clean `sendEntries` per +`send_append_entries_range`); a leader's CheckQuorum step-down (`timeout .checkQuorum`), +possibly after a heartbeat; or a non-leader's election timeout (`timeout .election`). +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) +open Life (Tri Pres) + +/-- What a tick ends in: the clean state agrees, and has no stale match index if the start +had none. -/ +def Final (names : Names) (node : NodeID) (clean0 : NodeState) (clean : NodeState) + (v : State) + : Prop := + agrees names clean v = true + /\ (UnnamedUnmatched node clean0 -> UnnamedUnmatched node clean) + +variable {env : Env} {node : NodeID} + +/-- A heartbeat's end: the clean state agrees and the node is the same. -/ +theorem HbAcc.final {s0 : State} {clean0 : NodeState} + (H : HbHyps env.names node s0 clean0) {v : State} {o : Outbox} + (acc : HbAcc env node s0 clean0 v o) + : v.nodeId = s0.nodeId /\ Acc env node clean0 (Final env.names node clean0) v o := by + obtain ⟨L, hv, _⟩ := acc.shape + exact ⟨by subst hv; rfl, acc.mono fun _ r => HbRel.finish H r⟩ + +/-- A leader whose configurations can lose a quorum has an active member other than itself. -/ +theorem cq_member {s0 : State} {clean0 : NodeState} (H : HbHyps env.names node s0 clean0) + {L : List (NodeId × Peer)} + (perm : (L.map Prod.fst).Perm (s0.allOtherNodes.map Prod.fst)) + (lose : ({ s0 with allOtherNodes := L } : State).canLoseQuorum = true) + : (clean0.activeMembers.erase node).Nonempty := by + have nonempty : (s0.configurations.all fun c => !c.nodes.isEmpty) = true := by + inv_conj H.inv "configurations_nonempty" + simp only [State.canLoseQuorum, List.any_eq_true, decide_eq_true_eq] at lose + obtain ⟨c, cmem, lt⟩ := lose + have cne : c.nodes ≠ [] := by + simp only [List.all_eq_true, Bool.not_eq_true', List.isEmpty_eq_false_iff] at nonempty + exact nonempty c cmem + have found : exists m, m ∈ c.nodes + /\ (({ s0 with allOtherNodes := L } : State).peer? m.1).isSome = true := by + false_or_by_contra + rename_i none + simp only [not_exists, not_and, Bool.not_eq_true, Option.isSome_eq_false_iff] at none + rw [List.filter_eq_self.mpr (fun m mem => by simp [none m mem])] at lt + have pos := List.length_pos_iff.mpr cne + simp only [State.quorum] at lt + omega + obtain ⟨⟨m, mp⟩, mmem, some⟩ := found + obtain ⟨p, hp⟩ := Option.isSome_iff_exists.mp some + have keyL : m ∈ L.map Prod.fst := by + simp only [State.peer?] at hp + exact List.mem_map.mpr + ⟨(m, p), (lookup_iff_mem (perm.nodup_iff.mpr H.nodup)).mp hp, rfl⟩ + have key := perm.mem_iff.mp keyL + have elig := H.eligible m key + simp only [eligiblePeers, CCF.Finset.mem_erase] at elig + have pos : 0 < s0.lastIdx := by + false_or_by_contra + rename_i z + have alone : (s0.lastIdx != 0 || s0.leadership != .leader || s0.allOtherNodes.isEmpty) + = true := by + inv_conj H.inv "empty_leader_alone" + simp only [show s0.lastIdx = 0 by omega, H.leader, bne_self_eq_false, Bool.false_or, + List.isEmpty_iff] at alone + simp [alone] at key + have hy := ReplUpdateCommit.Hyps.ofInv H.inv + obtain ⟨D, hD, sh⟩ := hy.configs pos + obtain ⟨x, xmem, xnodes⟩ := ReplUpdateCommit.shifted_mem sh cmem + refine ⟨env.names.id m, CCF.Finset.mem_erase.mpr ⟨elig.1, ?_⟩⟩ + have ceq := agrees_eq H.agrees + rw [ceq] + simp only [NodeState.activeMembers, NodeState.activeConfigurations] + rw [show (abs env.names s0).commitIndex = s0.commitIdx from rfl, hD] + refine ReplUpdateCommit.mem_configurationMembers (List.mem_map_of_mem xmem) ?_ + simp only [ReplUpdateCommit.absConfig, Names.set, CCF.Finset.mem_ofList, List.map_map, + List.mem_map, xnodes] + exact ⟨(m, mp), mmem, rfl⟩ + +/-- CheckQuorum's step-down after a heartbeat is the clean `timeout .checkQuorum`. -/ +theorem tri_cq {s0 : State} {clean0 : NodeState} (H : HbHyps env.names node s0 clean0) + (v : State) (o : Outbox) (acc : HbAcc env node s0 clean0 v o) + (lose : v.canLoseQuorum = true) + : Tri env (fun w o' => w = v /\ o' = o) + (do + note Note.checkQuorum; becomeFollower) + (fun _ v o => + v.nodeId = s0.nodeId + /\ Acc env node clean0 (Final env.names node clean0) v o) := by + obtain ⟨L, hv, perm⟩ := acc.shape + subst hv + have others := cq_member H perm lose + refine tri_keeps_bind (Spec.note _) fun _ => ?_ + unfold becomeFollower + refine Tri.bind + (Tri.setV + (Q := + fun _ w o' => + w + = { + { s0 with allOtherNodes := L } with + leaderId := none, leadership := .follower + } + /\ o' = o) + fun _ _ ⟨hw, ho⟩ => ⟨by rw [hw], ho⟩) + fun _ => ?_ + refine Tri.conseq (Tri.keeps (Spec.trace _)) (fun _ _ h => h) fun _ w o' ⟨hw, ho⟩ => ?_ + subst hw ho + refine ⟨rfl, ?_⟩ + rw [← List.append_nil o'] + refine acc.extend (fun clean R => ?_) (by simp) + have ag := (HbRel.finish H R).1 + obtain ⟨_, f, _, rfl, _⟩ := R + have role : clean0.role = .primary := by + rw [agrees_eq H.agrees] + simp [abs, absRole, H.leader] + let clean' : NodeState := + { clean0 with sentIndex := f, role := Role.follower, primaryKnown := false } + refine ⟨.timeout .checkQuorum, clean', ?_, admitted_timeout _, ?_, + fun _ h => by simp [clean'] at h⟩ + · show Emits (checkQuorum { clean0 with sentIndex := f } node) _ _ + exact emits_congr (emits_bind (emits_guard ⟨role, others⟩) (emits_pure _)) rfl rfl + · simp only [clean', agrees, abs, trackedPeers, absRole, Bool.and_eq_true, beq_iff_eq] at ag ⊢ + simp_all + +/-- After any heartbeat, a leader may step down on CheckQuorum. -/ +theorem tri_jp {s0 : State} {clean0 : NodeState} (H : HbHyps env.names node s0 clean0) + : Tri env (HbAcc env node s0 clean0) + (do + let v ← getV + let next ← lookFn + if (v.canLoseQuorum && next == some "become_follower") = true then do + note Note.checkQuorum + becomeFollower + else + pure ()) + (fun _ v o => + v.nodeId = s0.nodeId + /\ Acc env node clean0 (Final env.names node clean0) v o) := by + refine tri_getV fun v o acc => tri_keeps_bind Spec.lookFn fun _ => ?_ + refine Tri.ite (fun h => tri_cq H v o acc (by simp_all)) (fun _ => ?_) + · exact Tri.conseq (Tri.pure' (Q := fun _ v o => v.nodeId = s0.nodeId + /\ Acc env node clean0 (Final env.names node clean0) v o) _) + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact acc.final H) (fun _ _ _ h => h) + +theorem tick_tri {saved : State} {clean0 : NodeState} (invS : inv env.names saved = true) + (self : env.names.id saved.nodeId = node) (ag : agrees env.names clean0 saved = true) + (el + : saved.leadership ≠ .leader + -> saved.isRetiredCommitted = false + -> saved.ticking = true + -> Tri env (fun w o => w = saved /\ o = []) + (do + electionGuard; note Note.electionTimeout; becomePreVoteCandidate) + (fun _ v o => + v.nodeId = saved.nodeId + /\ (inv env.names v = true + -> Acc env node clean0 (Final env.names node clean0) v o))) + : Tri env (fun v o => v = saved /\ o = []) periodic + (fun _ v o => + v.nodeId = saved.nodeId + /\ (inv env.names v = true + -> Acc env node clean0 (Final env.names node clean0) v o)) := by + unfold periodic + refine tri_keeps_bind (Spec.trace _) fun _ => ?_ + refine tri_getV fun v o ⟨hv, ho⟩ => ?_ + subst v ho + refine Tri.ite (fun leader => ?_) (fun notLeader => ?_) + · have H := HbHyps.ofInv invS ag self (by simpa using leader) + refine Tri.conseq (P' := fun v o => v = saved /\ o = []) + (Q' := fun _ v o => v.nodeId = saved.nodeId + /\ Acc env node clean0 (Final env.names node clean0) v o) ?_ (fun _ _ h => h) + (fun _ _ _ h => ⟨h.1, fun _ => h.2⟩) + refine tri_keeps_bind Spec.lookFn fun _ => ?_ + dsimp only + refine Tri.ite (fun _ => ?_) (fun _ => Tri.conseq (P' := HbAcc env node saved clean0) ?_ + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact Acc.start (HbRel.start H)) (fun _ _ _ h => h)) + · refine Tri.conseq (P' := HbAcc env node saved clean0) ?_ + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact Acc.start (HbRel.start H)) (fun _ _ _ h => h) + refine Tri.bind (Tri.keeps (Spec.note _)) fun _ => ?_ + refine Tri.bind Life.pres_otherNodesSorted fun ids => ?_ + refine Tri.bind (Tri.forIn_list fun id _ _ => ?_) fun _ => ?_ + · refine tri_getV fun v o acc => ?_ + split + · rename_i p found + exact Tri.bind (Tri.conseq (tri_sendAE H _ _ _) + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact ⟨acc, p, found, rfl, acc.bound found⟩) + (fun _ _ _ h => h)) fun _ => Pres.pure _ + · exact Tri.conseq (Tri.pure' (Q := fun _ => HbAcc env node saved clean0) _) + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact acc) (fun _ _ _ h => h) + · exact tri_jp H + · exact tri_jp H + · refine tri_keeps_bind Spec.lookFn fun _ => Tri.ite (fun _ => ?_) (fun _ => ?_) + · exact el (by simpa using notLeader) (by simp_all) (by simp_all) + · exact Tri.conseq (Tri.pure' (Q := fun _ v o => v.nodeId = saved.nodeId + /\ (inv env.names v = true -> Acc env node clean0 (Final env.names node clean0) v o)) _) + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact ⟨rfl, fun _ => Acc.start ⟨ag, id⟩⟩) + (fun _ _ _ h => h) + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickOrder.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickOrder.lean new file mode 100644 index 000000000000..80398ed63c0d --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickOrder.lean @@ -0,0 +1,299 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickVotes + +@[expose] public section + +/-! +# Vote-request order (not reviewed; `Tick` obligation) + +M_tv asks `otherNodesInActiveConfigs` in string order; the clean model asks the sorted clean +ids. They coincide because the name table is sorted and holds every member. +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) + +/-- A list whose adjacent elements are related by a transitive relation is sorted by it. -/ +theorem pairwise_of_adjacent' {α : Type} {R : α -> α -> Prop} [DecidableRel R] + (trans : forall {a b c : α}, R a b -> R b c -> R a c) + : forall {l : List α}, + (l.zip l.tail).all (fun (x, y) => decide (R x y)) = true -> l.Pairwise R + | [], _ => .nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: t, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true] at h + have rest : (b :: t).Pairwise R := pairwise_of_adjacent' (R := R) trans h.2 + have hab : R a b := of_decide_eq_true h.1 + refine List.Pairwise.cons ?_ rest + intro x mem + rcases List.mem_cons.mp mem with rfl | mem + · exact hab + · exact trans hab (List.rel_of_pairwise_cons rest mem) + +theorem pairwise_eraseDups {α : Type} [BEq α] [LawfulBEq α] {R : α -> α -> Prop} + : forall (n : Nat) (l : List α), + l.length <= n -> l.Pairwise R -> l.eraseDups.Pairwise R + | _, [], _, _ => by simp + | 0, _ :: _, h, _ => by simp at h + | n + 1, a :: as, h, p => by + rw [List.eraseDups_cons] + rw [List.pairwise_cons] at p + refine List.Pairwise.cons (fun x mem => ?_) ?_ + · rw [List.mem_eraseDups, List.mem_filter] at mem + exact p.1 x mem.1 + · apply pairwise_eraseDups n + · have := List.length_filter_le (fun b => !b == a) as + simp only [List.length_cons] at h + omega + · exact p.2.filter _ + +/-- Known ids keep their string order as clean ids. -/ +theorem id_lt {names : Names} (sorted : names.known.toList.Pairwise (· < ·)) + {a b : NodeId} (ha : a ∈ names.known) (hb : b ∈ names.known) (lt : a < b) + : names.id a < names.id b := by + have find : forall x, x ∈ names.known + -> exists i, exists h : i < names.known.toList.length, + names.id x = i /\ names.known.toList[i] = x := by + intro x mem + have mem' : x ∈ names.known.toList := Array.mem_toList_iff.mpr mem + have isSome : (names.known.toList.findIdx? (· == x)).isSome = true := by + rw [List.findIdx?_isSome, List.any_eq_true] + exact ⟨x, mem', by simp⟩ + obtain ⟨i, hi⟩ := Option.isSome_iff_exists.mp isSome + obtain ⟨h, eq, -⟩ := List.findIdx?_eq_some_iff_getElem.mp hi + refine ⟨i, h, ?_, by simpa using eq⟩ + unfold Names.id + rw [← Array.toArray_toList (xs := names.known), List.findIdx?_toArray, hi] + rfl + obtain ⟨i, hi, ia, eqa⟩ := find a ha + obtain ⟨j, hj, jb, eqb⟩ := find b hb + rw [ia, jb] + rcases Nat.lt_trichotomy i j with ij | ij | ij + · exact ij + · subst ij + rw [eqa] at eqb + subst eqb + exact absurd lt (String.lt_irrefl _) + · have := List.pairwise_iff_getElem.mp sorted j i hj hi ij + rw [eqa, eqb] at this + exact absurd (String.lt_trans lt this) (String.lt_irrefl _) + +theorem mem_others {v : State} {s : NodeId} + : s ∈ v.otherNodesInActiveConfigs + <-> (exists x, x ∈ v.configurations /\ exists a, a ∈ x.nodes /\ a.1 = s) + /\ s ≠ v.nodeId := by + simp only [State.otherNodesInActiveConfigs, List.mem_eraseDups, List.mem_mergeSort, + List.mem_filter, List.mem_flatMap, List.mem_map, bne_iff_ne, ne_eq] + +theorem others_sorted {v : State} : v.otherNodesInActiveConfigs.Pairwise (· < ·) := by + unfold State.otherNodesInActiveConfigs + have le := List.pairwise_mergeSort (le := fun a b : NodeId => decide (a <= b)) + (fun a b c hab hbc => by + simp only [decide_eq_true_eq] at hab hbc ⊢ + exact String.le_trans hab hbc) + (fun a b => by + simp only [Bool.or_eq_true, decide_eq_true_eq] + exact String.le_total a b) + ((v.configurations.flatMap (·.nodes.map Prod.fst)).filter (· != v.nodeId)) + generalize ((v.configurations.flatMap (·.nodes.map Prod.fst)).filter (· != v.nodeId)).mergeSort + (fun a b => decide (a <= b)) = l at le ⊢ + have p := pairwise_eraseDups (R := fun a b : NodeId => decide (a <= b) = true) l.length l + (Nat.le_refl _) le + have nd := ReplUpdateCommit.nodup_eraseDups l.length l (Nat.le_refl _) + refine (p.and (List.nodup_iff_pairwise_ne.mp nd)).imp fun ⟨h1, h2⟩ => ?_ + simp only [decide_eq_true_eq] at h1 + exact Std.lt_of_le_of_ne h1 h2 + +/-- The clean ids of the nodes M_tv asks, in its order, are sorted. -/ +theorem others_ids_sorted {names : Names} {v : State} + (sorted : names.known.toList.Pairwise (· < ·)) + (known : forall x, x ∈ v.configurations -> forall a, a ∈ x.nodes -> a.1 ∈ names.known) + : (v.otherNodesInActiveConfigs.map names.id).Pairwise (· < ·) := by + rw [List.pairwise_map] + refine others_sorted.imp_of_mem fun ma mb lt => id_lt sorted ?_ ?_ lt + · obtain ⟨⟨x, xm, a, am, rfl⟩, -⟩ := mem_others.mp ma + exact known x xm a am + · obtain ⟨⟨x, xm, a, am, rfl⟩, -⟩ := mem_others.mp mb + exact known x xm a am + +/-! ## The clean active configurations against the declared ones -/ + +open ReplUpdateCommit (absConfig Shifted Named named_inj) + +theorem mem_configurationMembers_iff {cs : List Configuration} {n : NodeID} + : n ∈ configurationMembers cs <-> exists x, x ∈ cs /\ n ∈ x.nodes := by + unfold configurationMembers + have general : forall (cs : List Configuration) (acc : CCF.Finset NodeID), + n ∈ cs.foldl (fun nodes configuration => nodes ∪ configuration.nodes) acc + <-> (n ∈ acc \/ exists x, x ∈ cs /\ n ∈ x.nodes) := by + intro cs + induction cs with + | nil => intro acc; simp + | cons y ys ih => + intro acc + rw [List.foldl_cons, ih, CCF.Finset.mem_union] + simp only [List.mem_cons, exists_eq_or_imp] + constructor + · rintro ((h | h) | h) + · exact Or.inl h + · exact Or.inr (Or.inl h) + · exact Or.inr (Or.inr h) + · rintro (h | h | h) + · exact Or.inl (Or.inl h) + · exact Or.inl (Or.inr h) + · exact Or.inr h + rw [general] + simp only [CCF.Finset.notMem_empty, false_or] + +theorem shifted_mem_rev {ci : Nat} {D E : List Config} (sh : Shifted ci D E) {x : Config} + (mem : x ∈ D) + : exists y, y ∈ E /\ y.nodes = x.nodes := by + rcases sh with rfl | ⟨x', y, rest, rfl, rfl, nodes, _⟩ + · exact ⟨x, mem, rfl⟩ + · rcases List.mem_cons.mp mem with rfl | mem + · exact ⟨y, List.mem_cons_self, nodes.symm⟩ + · exact ⟨x, List.mem_cons_of_mem _ mem, rfl⟩ + +theorem shifted_nil {ci : Nat} {D E : List Config} (sh : Shifted ci D E) + : D = [] <-> E = [] := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, _⟩ + · exact Iff.rfl + · simp + +variable {names : Names} + +theorem mem_absConfig {x : Config} {n : NodeID} + : n ∈ (absConfig names x).nodes <-> exists a, a ∈ x.nodes /\ names.id a.1 = n := by + simp only [absConfig, Names.set, CCF.Finset.mem_ofList, List.mem_map] + constructor + · rintro ⟨s, ⟨a, am, rfl⟩, rfl⟩ + exact ⟨a, am, rfl⟩ + · rintro ⟨a, am, rfl⟩ + exact ⟨a.1, ⟨a, am, rfl⟩, rfl⟩ + +/-- The clean active members are the declared members' clean ids. -/ +theorem active_members_iff {active : List Configuration} {D E : List Config} {ci : Nat} + (hD : active = D.map (absConfig names)) (sh : Shifted ci D E) {n : NodeID} + : n ∈ configurationMembers active + <-> exists y, y ∈ E /\ exists a, a ∈ y.nodes /\ names.id a.1 = n := by + rw [mem_configurationMembers_iff, hD] + simp only [List.mem_map] + constructor + · rintro ⟨_, ⟨x, xm, rfl⟩, nm⟩ + obtain ⟨y, ym, nodes⟩ := shifted_mem_rev sh xm + refine ⟨y, ym, ?_⟩ + rw [nodes] + exact mem_absConfig.mp nm + · rintro ⟨y, ym, nm⟩ + obtain ⟨x, xm, nodes⟩ := ReplUpdateCommit.shifted_mem sh ym + refine ⟨absConfig names x, ⟨x, xm, rfl⟩, mem_absConfig.mpr ?_⟩ + rw [nodes] + exact nm + +theorem card_absConfig {x : Config} (named : forall a, a ∈ x.nodes -> Named names a.1) + (distinct : (x.nodes.map Prod.fst).Nodup) + : (absConfig names x).nodes.card = x.nodes.length := by + simp only [absConfig, Names.set] + rw [CCF.Finset.card_ofList_of_nodup, List.length_map, List.length_map] + rw [List.Nodup, List.pairwise_map] + refine distinct.imp_of_mem fun ma mb ne same => ne ?_ + simp only [List.mem_map] at ma mb + obtain ⟨a, am, rfl⟩ := ma + obtain ⟨b, bm, rfl⟩ := mb + exact named_inj (named a am) (named b bm) same + +theorem self_mem_absConfig {x : Config} {self : NodeId} (selfNamed : Named names self) + (named : forall a, a ∈ x.nodes -> Named names a.1) + : names.id self ∈ (absConfig names x).nodes <-> Lists self x := by + rw [mem_absConfig] + simp only [Lists, List.any_eq_true, beq_iff_eq] + constructor + · rintro ⟨a, am, same⟩ + exact ⟨a, am, named_inj (named a am) selfNamed same⟩ + · rintro ⟨a, am, rfl⟩ + exact ⟨a, am, rfl⟩ + +/-- The self-vote is a majority of a configuration iff it is the node alone. -/ +theorem majority_self {x : Config} {self : NodeId} (selfNamed : Named names self) + (named : forall a, a ∈ x.nodes -> Named names a.1) + (distinct : (x.nodes.map Prod.fst).Nodup) + : hasConfigurationMajority {names.id self} (absConfig names x) + <-> Lists self x /\ x.nodes.length <= 1 := by + unfold hasConfigurationMajority + rw [card_absConfig named distinct, ← self_mem_absConfig selfNamed named] + generalize (absConfig names x).nodes = S + have card : ({names.id self} ∩ S : CCF.Finset NodeID).card + = if names.id self ∈ S then 1 else 0 := by + show ([names.id self].filter fun a => decide (a ∈ S)).length = _ + by_cases h : names.id self ∈ S <;> simp [h] + rw [card] + by_cases h : names.id self ∈ S + · rw [ite_eq_left h] + simp only [h, true_and] + omega + · rw [ite_eq_right h] + simp only [h, false_and, iff_false] + omega + +/-- The clean self-vote wins iff every declared configuration is the node alone. -/ +theorem hasQuorum_self {active : List Configuration} {D E : List Config} {ci : Nat} + (hD : active = D.map (absConfig names)) (sh : Shifted ci D E) {self : NodeId} + (selfNamed : Named names self) + (named : forall x, x ∈ E -> forall a, a ∈ x.nodes -> Named names a.1) + (distinct : forall x, x ∈ E -> (x.nodes.map Prod.fst).Nodup) + : hasQuorum active {names.id self} + <-> E ≠ [] /\ forall c, c ∈ E -> Lists self c /\ c.nodes.length <= 1 := by + subst hD + unfold hasQuorum + rw [ne_eq, List.map_eq_nil_iff, shifted_nil sh, List.all_eq_true] + refine and_congr_right fun _ => ?_ + simp only [List.mem_map, decide_eq_true_eq] + constructor + · intro h c cm + obtain ⟨x, xm, nodes⟩ := ReplUpdateCommit.shifted_mem sh cm + have := h _ ⟨x, xm, rfl⟩ + have nx : forall a, a ∈ x.nodes -> Named names a.1 := by rw [nodes]; exact named c cm + have dx : (x.nodes.map Prod.fst).Nodup := by rw [nodes]; exact distinct c cm + rw [majority_self selfNamed nx dx] at this + simp only [Lists, nodes] at this + exact this + · rintro h _ ⟨x, xm, rfl⟩ + obtain ⟨c, cm, nodes⟩ := shifted_mem_rev sh xm + have nx : forall a, a ∈ x.nodes -> Named names a.1 := by rw [← nodes]; exact named c cm + have dx : (x.nodes.map Prod.fst).Nodup := by rw [← nodes]; exact distinct c cm + rw [majority_self selfNamed nx dx] + have := h c cm + simp only [Lists, nodes] at this + exact this + +/-- The self-vote's voters are the node alone. -/ +theorem selfVotes_set (cs : List Config) (self : NodeId) + : names.set + (self + :: (cs.map + fun c => + ( + c.idx, + if Lists self c then [self] else [], + State.quorum c.nodes.length + )).flatMap + fun (_, vs, _) => vs) + = {names.id self} := by + apply CCF.Finset.ext + intro n + simp only [Names.set, CCF.Finset.mem_ofList, CCF.Finset.mem_singleton, List.map_cons, + List.mem_cons, List.mem_map, List.mem_flatMap] + constructor + · rintro (h | ⟨s, ⟨_, ⟨c, _, rfl⟩, sm⟩, rfl⟩) + · exact h + · by_cases P : Lists self c <;> simp_all + · exact Or.inl + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickPeers.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickPeers.lean new file mode 100644 index 000000000000..6ab8d04b0127 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickPeers.lean @@ -0,0 +1,565 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickViews +public import Consensus.TraceValidation.Proofs.Handlers.TickRun + +@[expose] public section + +/-! +# A leader's heartbeat, one range at a time (not reviewed; `Tick` obligation) + +During a heartbeat the declared state only changes in its peers' send indexes, and the +clean state only in `sentIndex`. `HbRel` relates the two throughout; `hb_step` shows that +one `send_append_entries_range` of the heartbeat is the clean `sendEntries` to that peer and +range, keeps `HbRel`, and sends an envelope satisfying `msgInv`. +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) +open ReplUpdateCommit (Named named_inj) + +/-! ## Peer lists -/ + +theorem lookup_iff_mem {l : List (NodeId × Peer)} (nd : (l.map Prod.fst).Nodup) + {k : NodeId} {p : Peer} + : l.lookup k = some p <-> (k, p) ∈ l := by + induction l with + | nil => simp + | cons q l ih => + obtain ⟨k', p'⟩ := q + simp only [List.map_cons, List.nodup_cons] at nd + by_cases e : k = k' + · subst e + simp only [List.lookup_cons_self, Option.some.injEq, List.mem_cons, Prod.mk.injEq, + true_and] + constructor + · intro h + exact Or.inl h.symm + · rintro (h | h) + · exact h.symm + · exact absurd (List.mem_map_of_mem (f := Prod.fst) h) nd.1 + · have ne : (k == k') = false := by simpa using e + simp only [List.lookup_cons, ne, List.mem_cons, Prod.mk.injEq, e, false_and, false_or] + exact ih nd.2 + +theorem mem_setPeer {v : State} {id k : NodeId} {p q : Peer} + : (k, q) ∈ (v.setPeer id p).allOtherNodes + <-> (k = id /\ q = p) \/ (k ≠ id /\ (k, q) ∈ v.allOtherNodes) := by + simp only [State.setPeer, List.mem_mergeSort, List.mem_append, List.mem_filter, + List.mem_singleton, Prod.mk.injEq, bne_iff_ne, ne_eq] + constructor + · rintro (⟨m, n⟩ | h) + · exact Or.inr ⟨n, m⟩ + · exact Or.inl h + · rintro (h | ⟨n, m⟩) + · exact Or.inr h + · exact Or.inl ⟨m, n⟩ + +theorem setPeer_nodup {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) + (id : NodeId) (p : Peer) + : ((v.setPeer id p).allOtherNodes.map Prod.fst).Nodup := by + simp only [State.setPeer] + refine (((List.mergeSort_perm _ _).map Prod.fst).nodup_iff).mpr ?_ + rw [List.map_append, List.nodup_append] + refine ⟨((List.filter_sublist).map Prod.fst).nodup nd, by simp, ?_⟩ + intro a ha b hb + simp only [List.map_cons, List.map_nil, List.mem_singleton] at hb + subst hb + obtain ⟨x, mem, rfl⟩ := List.mem_map.mp ha + have := (List.mem_filter.mp mem).2 + simpa using this + +theorem setPeer_lookup {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) + (id k : NodeId) (p : Peer) + : (v.setPeer id p).peer? k = if k = id then some p else v.peer? k := by + have nd' := setPeer_nodup nd id p + unfold State.peer? + split + · rename_i e + rw [lookup_iff_mem nd', mem_setPeer] + exact Or.inl ⟨e, rfl⟩ + · rename_i e + apply Option.ext + intro q + rw [lookup_iff_mem nd', lookup_iff_mem nd, mem_setPeer] + constructor + · rintro (⟨h, -⟩ | ⟨-, h⟩) + · exact absurd h e + · exact h + · intro h + exact Or.inr ⟨e, h⟩ + +theorem mem_keys {l : List (NodeId × Peer)} {k : NodeId} + : k ∈ l.map Prod.fst <-> exists q, (k, q) ∈ l := by + simp + +theorem setPeer_perm {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) {id : NodeId} + {p0 : Peer} (found : v.peer? id = some p0) (p : Peer) + : ((v.setPeer id p).allOtherNodes.map Prod.fst).Perm + (v.allOtherNodes.map Prod.fst) := by + refine (List.perm_ext_iff_of_nodup (setPeer_nodup nd id p) nd).mpr fun k => ?_ + rw [mem_keys, mem_keys] + constructor + · rintro ⟨q, mem⟩ + rcases mem_setPeer.mp mem with ⟨rfl, -⟩ | ⟨-, mem⟩ + · exact ⟨p0, (lookup_iff_mem nd).mp found⟩ + · exact ⟨q, mem⟩ + · rintro ⟨q, mem⟩ + by_cases e : k = id + · exact ⟨p, mem_setPeer.mpr (Or.inl ⟨e, rfl⟩)⟩ + · exact ⟨q, mem_setPeer.mpr (Or.inr ⟨e, mem⟩)⟩ + +/-! ## Clean and abstract peer indexes -/ + +/-- The clean send index of a peer is its declared one. -/ +theorem abs_sentIndex {names : Names} {v : State} + (peersNamed : forall p, p ∈ v.allOtherNodes -> Named names p.1) {id : NodeId} + (named : Named names id) {p : Peer} (found : v.peer? id = some p) + : (abs names v).sentIndex (names.id id) = p.sentIdx := by + simp only [abs] + unfold State.peer? at found + generalize v.allOtherNodes = l at peersNamed found + induction l with + | nil => simp at found + | cons q l ih => + obtain ⟨k, pk⟩ := q + by_cases same : id = k + · subst same + simp only [List.lookup_cons, beq_self_eq_true, Option.some.injEq] at found + subst found + simp + · have ne : (names.id k == names.id id) = false := by + simp only [beq_eq_false_iff_ne] + intro eq + exact same (named_inj named (peersNamed (k, pk) (by simp)) eq.symm) + have ne' : (id == k) = false := by simpa using same + simp only [List.lookup_cons, ne'] at found + simp only [List.find?_cons, ne] + exact ih (fun p mem => peersNamed p (List.mem_cons_of_mem _ mem)) found + +/-- A clean state that agrees with `d` is `abs d` but for the peer indexes and votes. -/ +theorem agrees_eq {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c + = { + abs names d with + sentIndex := c.sentIndex, + matchIndex := c.matchIndex, + votesGranted := c.votesGranted, + preVotesGranted := c.preVotesGranted + } := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, -⟩, h6⟩, h7⟩, h8⟩, -⟩, -⟩, h11⟩ := h + cases c + simp only at h1 h2 h3 h4 h6 h7 h8 h11 ⊢ + rw [h1, h2, h3, h4, h6, h7, h8, h11] + +/-! ## The heartbeat relation -/ + +/-- What a heartbeat needs of the leader it starts from. -/ +structure HbHyps (names : Names) (node : NodeID) (s0 : State) (clean0 : NodeState) + : Prop where + inv : inv names s0 = true + agrees : agrees names clean0 s0 = true + self : names.id s0.nodeId = node + leader : s0.leadership = .leader + notRC : s0.isRetiredCommitted = false + nodup : (s0.allOtherNodes.map Prod.fst).Nodup + eligible + : forall k, + k ∈ s0.allOtherNodes.map Prod.fst -> names.id k ∈ eligiblePeers clean0 node + bounds : forall k p, (k, p) ∈ s0.allOtherNodes -> p.sentIdx <= s0.lastIdx + +theorem HbHyps.ofInv {names : Names} {node : NodeID} {s0 : State} {clean0 : NodeState} + (invS : Consensus.TraceValidation.inv names s0 = true) + (ag : Consensus.TraceValidation.agrees names clean0 s0 = true) + (self : names.id s0.nodeId = node) (leader : s0.leadership = .leader) + : HbHyps names node s0 clean0 := by + have notRC : (s0.leadership != .leader || !s0.isRetiredCommitted) = true := by + inv_conj invS "leader_not_retired_committed" + have bounds : (s0.leadership != .leader + || s0.allOtherNodes.all fun (_, p) => p.sentIdx <= s0.lastIdx && p.matchIdx <= s0.lastIdx) + = true := by + inv_conj invS "peer_bounds" + simp only [leader, bne_self_eq_false, Bool.false_or, Bool.not_eq_true'] at notRC + simp only [leader, bne_self_eq_false, Bool.false_or, List.all_eq_true, Bool.and_eq_true, + decide_eq_true_eq] at bounds + have peers : forall k, k ∈ s0.allOtherNodes.map Prod.fst + -> (s0.allOtherNodes.map Prod.fst).Nodup /\ names.id k ∈ eligiblePeers clean0 node := by + intro k mem + by_cases z : s0.lastIdx = 0 + · have alone : (s0.lastIdx != 0 || s0.leadership != .leader || s0.allOtherNodes.isEmpty) + = true := by + inv_conj invS "empty_leader_alone" + simp only [z, leader, bne_self_eq_false, Bool.false_or, List.isEmpty_iff] at alone + simp [alone] at mem + · have hp : (s0.lastIdx == 0 || s0.leadership == .none + || s0.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names s0) (names.id s0.nodeId)).sort) = true := by + inv_conj invS "peers" + simp only [z, leader, beq_iff_eq, Bool.or_eq_true, reduceCtorEq, false_or] at hp + have ceq := agrees_eq ag + have congr : eligiblePeers clean0 node = eligiblePeers (abs names s0) (names.id s0.nodeId) := by + rw [self] + exact Ae.eligiblePeers_congr (by rw [ceq]) (by rw [ceq]) node + have mapEq : (s0.allOtherNodes.map Prod.fst).map names.id + = (eligiblePeers (abs names s0) (names.id s0.nodeId)).sort := by + rw [← hp, List.map_map] + rfl + refine ⟨List.Pairwise.of_map (S := fun x y : NodeID => x ≠ y) names.id + (fun a b h e => h (e ▸ rfl)) ?_, ?_⟩ + · rw [mapEq] + exact CCF.Finset.nodup_of_sorted (eligiblePeers _ _).sorted + · rw [congr, ← CCF.Finset.mem_sort, ← mapEq] + exact List.mem_map_of_mem mem + refine ⟨invS, ag, self, leader, notRC, ?_, fun k mem => (peers k mem).2, + fun k p mem => (bounds _ mem).1⟩ + cases h : s0.allOtherNodes with + | nil => simp + | cons q l => + exact h ▸ (peers q.1 (by simp [h])).1 + +/-- +The clean state and the declared state during a heartbeat from `clean0` and `s0`: only the +declared peers and the clean send indexes change, the peers keep their keys and match +indexes, and every peer's clean send index is its declared one, within the ledger. +-/ +def HbRel (names : Names) (s0 : State) (clean0 : NodeState) (clean : NodeState) + (v : State) + : Prop := + exists (L : List (NodeId × Peer)) (f : NodeID -> Nat), + v = { s0 with allOtherNodes := L } + /\ clean = { clean0 with sentIndex := f } + /\ (L.map Prod.fst).Perm (s0.allOtherNodes.map Prod.fst) + /\ forall k p, + L.lookup k = some p + -> (exists p0, s0.peer? k = some p0 /\ p0.matchIdx = p.matchIdx) + /\ f (names.id k) = p.sentIdx + /\ p.sentIdx <= s0.lastIdx + +variable {names : Names} {node : NodeID} {s0 : State} {clean0 : NodeState} + +theorem HbRel.start (H : HbHyps names node s0 clean0) + : HbRel names s0 clean0 clean0 s0 := by + have hy := ReplUpdateCommit.Hyps.ofInv H.inv + refine ⟨ + s0.allOtherNodes, + clean0.sentIndex, + rfl, + rfl, + List.Perm.refl _, + fun k p found => ?_ + ⟩ + have mem := (lookup_iff_mem H.nodup).mp found + refine ⟨⟨p, found, rfl⟩, ?_, H.bounds k p mem⟩ + have named := hy.peersNamed _ mem + rw [← abs_sentIndex hy.peersNamed named found] + have ag := H.agrees + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at ag + have tracked : names.id k ∈ Consensus.TraceValidation.trackedPeers names s0 := by + simp only [Consensus.TraceValidation.trackedPeers, H.leader] + simp only [beq_self_eq_true, ite_true, List.mem_map] + exact ⟨(k, p), mem, rfl⟩ + exact (ag.1.1.1.1.1.1.2 _ tracked).1 + +/-! ## One range of the heartbeat -/ + +theorem messageEntries_abs (size : s0.ledger.size = s0.lastIdx) (prev endIdx : Nat) + (eL : endIdx <= s0.lastIdx) + : messageEntries (abs names s0).log prev endIdx + = (List.range' (prev + 1) (endIdx - prev)).map + fun i => absEntry names s0.ledger[i - 1]! := by + unfold messageEntries + apply List.ext_getElem + · simp [abs, size] + omega + · intro j h1 h2 + simp only [List.length_map, List.length_range'] at h2 + simp only [abs, List.getElem_take, List.getElem_drop, List.getElem_map, + List.getElem_range', Array.getElem_toList] + congr 1 + have lt : prev + 1 + j - 1 < s0.ledger.size := by rw [size]; omega + rw [Nat.one_mul, getElem!_pos s0.ledger _ lt] + congr 1 + omega + +/-- The AppendEntries of `send_append_entries_range` from `start` to `endIdx`. -/ +def aeOf (names : Names) (v : State) (start endIdx : Nat) : AppendEntriesRequest := + { + term := v.currentView, + prevLogIndex := start - 1, + prevLogTerm := v.getTerm (start - 1), + entries := + (List.range' start (endIdx + 1 - start)).map + fun i => absEntry names v.ledger[i - 1]!, + primaryCommit := v.commitIdx + } + +theorem names_set_round_trip {l : List NodeId} (named : forall x, x ∈ l -> Named names x) + : forall i, i ∈ names.set l -> names.id (names.name i) = i := by + intro i mem + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] at mem + obtain ⟨x, mem, rfl⟩ := mem + rw [named x mem] + +/-- The entries of a range in one view. -/ +theorem hb_entry {v : State} (vh : ViewHyps v) {prev endIdx : Nat} + (eL : endIdx <= v.lastIdx) + (same : forall i, prev < i -> i <= endIdx -> v.viewAt i = v.viewAt endIdx) + : forall i, + prev + 1 <= i + -> i <= endIdx + -> v.ledger[i - 1]! ∈ v.ledger.toList + /\ v.ledger[i - 1]!.term = v.viewAt endIdx := by + intro i i1 iE + have lt : i - 1 < v.ledger.size := by rw [vh.size]; omega + rw [getElem!_pos v.ledger _ lt] + refine ⟨by simp, ?_⟩ + have t := vh.terms i (by omega) (by omega) + rw [Array.getElem?_eq_getElem lt] at t + simp only [Option.map_some, Option.some.injEq] at t + rw [t] + exact same i (by omega) iE + +theorem msgInv_hb (H : HbHyps names node s0 clean0) {to : NodeId} + (elig : names.id to ∈ eligiblePeers clean0 node) {prev endIdx : Nat} + (pL : prev <= s0.lastIdx) (e1 : prev <= endIdx) (eL : endIdx <= s0.lastIdx) + (same : forall i, prev < i -> i <= endIdx -> s0.viewAt i = s0.viewAt endIdx) + : msgInv names + ⟨ + names.id s0.nodeId, + names.id to, + .appendEntriesRequest (aeOf names s0 (prev + 1) endIdx) + ⟩ + = true := by + have hy := ReplUpdateCommit.Hyps.ofInv H.inv + have vh := ViewHyps.ofInv H.inv + have ledgerNamed : s0.ledger.all + (fun e => ((e.config.getD []).map Prod.fst ++ e.retired).all + fun id => names.name (names.id id) == id) = true := by + inv_conj H.inv "ledger_names_round_trip" + have ne : node ≠ names.id to := by + intro e + unfold eligiblePeers at elig + rw [← e, CCF.Finset.mem_erase] at elig + exact elig.1 rfl + have entry := hb_entry vh eL same + unfold msgInv aeOf + simp only [Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, List.all_eq_true, List.mem_map, + List.mem_range'_1, forall_exists_index, and_imp, decide_eq_true_eq, Bool.or_eq_true] + refine ⟨⟨⟨⟨?_, ?_⟩, ?_⟩, ?_, ?_⟩, ?_⟩ + · rw [hy.selfNamed] + · rw [H.self] + exact ne + · intro x i i1 iE xe y mem + subst xe + obtain ⟨inLedger, -⟩ := entry i i1 (by omega) + have all := (Array.all_eq_true_iff_forall_mem.mp ledgerNamed) _ (by simpa using inLedger) + simp only [List.all_eq_true, beq_iff_eq, List.mem_append] at all + simp only [absEntry] at mem + split at mem + · simp [EntryContent.metadata, CCF.Finset.notMem_empty] at mem + · simp only [EntryContent.metadata, List.mem_append, CCF.Finset.mem_sort] at mem + rcases mem with mem | mem + · cases hc : s0.ledger[i - 1]!.config with + | none => simp [hc] at mem + | some ns => + simp only [hc, Option.map_some, Option.getD_some, CCF.Finset.mem_sort] at mem + exact names_set_round_trip (fun x m => all x (Or.inl (by simpa [hc] using m))) + y mem + · exact names_set_round_trip (fun x m => all x (Or.inr m)) y mem + · intro x i i1 iE xe + subst xe + obtain ⟨inLedger, term⟩ := entry i i1 (by omega) + have pos := (Array.all_eq_true_iff_forall_mem.mp + (by inv_conj H.inv "positive_terms" : s0.ledger.all (0 < ·.term) = true)) _ + (by simpa using inLedger) + simp only [decide_eq_true_eq] at pos + have last : endIdx + 1 - (prev + 1) = (endIdx - prev - 1) + 1 := by omega + refine ⟨⟨?_, ?_⟩, ?_⟩ + · rw [last, List.range'_1_concat, List.map_append, List.getLast?_append] + simp only [List.map_cons, List.map_nil, List.getLast?_singleton, Option.some_or, + Option.map_some, absEntry, Option.some.injEq] + rw [term, (entry _ (by omega) (by omega)).2] + · simpa [absEntry] using pos + · simp only [absEntry] + rw [term] + exact Nat.le_trans (ReplUpdateCommit.viewAt_le_size _ _) hy.viewsBounded + · rcases Nat.eq_zero_or_pos prev with z | z + · exact Or.inl (by simp [z]) + · refine Or.inr ?_ + simp only [Nat.add_sub_cancel, State.getTerm] + split + · omega + · exact viewAt_pos vh z pL + · intro x i _ _ xe + subst xe + simp only [absEntry] + split + · rename_i h + split at h <;> simp_all + · rfl + +/-- +One range of the heartbeat to the peer `to` is the clean `sendEntries` to it, keeps `HbRel`, +and sends an envelope satisfying `msgInv`. +-/ +theorem hb_step (H : HbHyps names node s0 clean0) {clean : NodeState} {v : State} + (R : HbRel names s0 clean0 clean v) {to : NodeId} {p : Peer} + (found : v.peer? to = some p) {endIdx : Nat} (e1 : p.sentIdx <= endIdx) + (eL : endIdx <= s0.lastIdx) + (same : forall i, p.sentIdx < i -> i <= endIdx -> s0.viewAt i = s0.viewAt endIdx) + : Emits + (act (CCF.Capabilities.record node) node clean + (.sendEntries (names.id to) endIdx)) + { + clean with + sentIndex := CCF.Function.update clean.sentIndex (names.id to) endIdx + } + [⟨node, names.id to, .appendEntriesRequest (aeOf names v (p.sentIdx + 1) endIdx)⟩] + /\ HbRel names s0 clean0 + { + clean with + sentIndex := CCF.Function.update clean.sentIndex (names.id to) endIdx + } + (v.setPeer to { p with sentIdx := endIdx }) + /\ msgInv names + ⟨ + names.id v.nodeId, + names.id to, + .appendEntriesRequest (aeOf names v (p.sentIdx + 1) endIdx) + ⟩ + = true := by + obtain ⟨L, f, rfl, rfl, perm, rel⟩ := R + have hy := ReplUpdateCommit.Hyps.ofInv H.inv + have vh := ViewHyps.ofInv H.inv + have lfound : L.lookup to = some p := found + obtain ⟨⟨p0, found0, match0⟩, fto, pL⟩ := rel to p lfound + have ndL : (L.map Prod.fst).Nodup := perm.nodup_iff.mpr H.nodup + have key0 : to ∈ s0.allOtherNodes.map Prod.fst := + perm.mem_iff.mp (mem_keys.mpr ⟨p, (lookup_iff_mem ndL).mp lfound⟩) + have elig := H.eligible to key0 + have ceq := agrees_eq H.agrees + have hlog : clean0.log = (abs names s0).log := by rw [ceq] + have hrole : clean0.role = .primary := by rw [ceq]; simp [abs, H.leader, absRole] + have hterm : clean0.currentTerm = s0.currentView := by rw [ceq]; simp [abs] + have hcommit : clean0.commitIndex = s0.commitIdx := by rw [ceq]; simp [abs] + have hrc : Not (clean0.isRetiredCommitted node) := by + have rc : s0.isRetiredCommitted + = decide ((abs names s0).isRetiredCommitted (names.id s0.nodeId)) := by + inv_conj H.inv "retired_committed" + rw [H.notRC, H.self] at rc + have : Not ((abs names s0).isRetiredCommitted node) := by simpa using rc + rw [ceq] + exact this + have entry := hb_entry vh eL same + have endTerm : termAt (abs names s0).log endIdx = s0.viewAt endIdx := by + rw [← Ae.getTerm_eq H.inv] + unfold State.getTerm + split + · omega + · rfl + have entries : messageEntries (abs names s0).log p.sentIdx endIdx + = (List.range' (p.sentIdx + 1) (endIdx + 1 - (p.sentIdx + 1))).map + fun i => absEntry names s0.ledger[i - 1]! := by + rw [messageEntries_abs vh.size _ _ eL] + congr 2 + omega + refine ⟨?_, ?_, ?_⟩ + · have msg : makeAppendEntriesRequest { clean0 with sentIndex := f } (names.id to) endIdx + = aeOf names s0 (p.sentIdx + 1) endIdx := by + simp only [makeAppendEntriesRequest, aeOf, fto, hlog, hterm, hcommit, entries, + Nat.add_sub_cancel, Ae.getTerm_eq H.inv] + unfold act sendEntries + refine emits_congr + (emits_bind (emits_guard ?_) (emits_bind (emits_send _ _) (emits_pure _))) rfl ?_ + · refine ⟨hrole, elig, by simp [fto, e1], ?_, ?_, Or.inl hrc⟩ + · show endIdx <= clean0.log.length + rw [hlog, ReplUpdateCommit.abs_log_length vh.size] + exact eL + · show ((messageEntries clean0.log (f (names.id to)) endIdx).all + fun entry => entry.term == termAt clean0.log endIdx) = true + rw [hlog, fto, entries, endTerm] + simp only [List.all_eq_true, List.mem_map, List.mem_range'_1, beq_iff_eq, + forall_exists_index, and_imp] + intro x i i1 iE xe + subst xe + simp only [absEntry] + exact (entry i i1 (by omega)).2 + · simp only [List.nil_append, List.append_nil] + rw [msg] + rfl + · refine ⟨(({ s0 with allOtherNodes := L } : State).setPeer to + { p with sentIdx := endIdx }).allOtherNodes, + CCF.Function.update f (names.id to) endIdx, rfl, rfl, + (setPeer_perm ndL found _).trans perm, fun k q lk => ?_⟩ + have h2 : (({ s0 with allOtherNodes := L } : State).setPeer to + { p with sentIdx := endIdx }).peer? k = some q := lk + rw [setPeer_lookup ndL] at h2 + split at h2 + · rename_i e + subst e + simp only [Option.some.injEq] at h2 + subst h2 + exact ⟨⟨p0, found0, match0⟩, by simp [CCF.Function.update], eL⟩ + · rename_i e + obtain ⟨m, fk, qL⟩ := rel k q h2 + have keyk : k ∈ s0.allOtherNodes.map Prod.fst := + perm.mem_iff.mp (mem_keys.mpr ⟨q, (lookup_iff_mem ndL).mp h2⟩) + obtain ⟨qk, memk⟩ := mem_keys.mp keyk + obtain ⟨qt, memt⟩ := mem_keys.mp key0 + have ne : names.id k ≠ names.id to := fun eq => + e (named_inj (hy.peersNamed _ memk) (hy.peersNamed _ memt) eq) + refine ⟨m, ?_, qL⟩ + simp only [CCF.Function.update, ne, ↓reduceIte] + exact fk + · exact msgInv_hb H elig pL e1 eL same + +/-- At the end of a heartbeat the clean state agrees with the declared one. -/ +theorem HbRel.finish (H : HbHyps names node s0 clean0) {clean : NodeState} {v : State} + (R : HbRel names s0 clean0 clean v) + : agrees names clean v = true + /\ (UnnamedUnmatched node clean0 -> UnnamedUnmatched node clean) := by + obtain ⟨L, f, rfl, rfl, perm, rel⟩ := R + refine ⟨?_, fun um => um⟩ + have hy := ReplUpdateCommit.Hyps.ofInv H.inv + have ndL : (L.map Prod.fst).Nodup := perm.nodup_iff.mpr H.nodup + have namedL : forall k, k ∈ L.map Prod.fst -> Named names k := by + intro k mem + obtain ⟨q, mem⟩ := mem_keys.mp (perm.mem_iff.mp mem) + exact hy.peersNamed _ mem + have ag := H.agrees + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at ag ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨a1, a2⟩, a3⟩, a4⟩, a5⟩, a6⟩, a7⟩, a8⟩, a9⟩, a10⟩, a11⟩ := ag + refine ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨a1, a2⟩, a3⟩, a4⟩, ?_⟩, a6⟩, a7⟩, a8⟩, a9⟩, a10⟩, a11⟩ + intro n mem + simp only [Consensus.TraceValidation.trackedPeers, H.leader, beq_self_eq_true, ite_true, + List.mem_map] at mem + obtain ⟨⟨k, q⟩, memL, rfl⟩ := mem + have lk : L.lookup k = some q := (lookup_iff_mem ndL).mpr memL + obtain ⟨⟨p0, f0, m0⟩, fk, -⟩ := rel k q lk + have named := namedL k (mem_keys.mpr ⟨q, memL⟩) + have peersNamedV : forall p, p ∈ L -> Named names p.1 := + fun p mem => namedL p.1 (List.mem_map_of_mem mem) + have tracked : names.id k ∈ Consensus.TraceValidation.trackedPeers names s0 := by + simp only [Consensus.TraceValidation.trackedPeers, H.leader, beq_self_eq_true, ite_true, + List.mem_map] + exact ⟨(k, p0), (lookup_iff_mem H.nodup).mp f0, rfl⟩ + have m := (a5 _ tracked).2 + rw [ReplUpdateCommit.abs_matchIndex hy.peersNamed named f0] at m + refine ⟨?_, ?_⟩ + · show f (names.id k) = (abs names { s0 with allOtherNodes := L }).sentIndex (names.id k) + rw [abs_sentIndex (v := { s0 with allOtherNodes := L }) peersNamedV named lk] + exact fk + · show clean0.matchIndex (names.id k) + = (abs names { s0 with allOtherNodes := L }).matchIndex (names.id k) + rw [ReplUpdateCommit.abs_matchIndex (v := { s0 with allOtherNodes := L }) peersNamedV named + lk, m, m0] + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickRun.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickRun.lean new file mode 100644 index 000000000000..ee76b43cce61 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickRun.lean @@ -0,0 +1,190 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.LifeHoare + +import all Init.Control.State + +@[expose] public section + +/-! +# Clean runs alongside a hold (not reviewed; `Tick` obligation) + +A hold's declared run is related to clean internal steps through a ghost predicate on the +declared state and outbox: `Acc env node clean0 R v o` says the outbox `o` is the sends of +clean internal steps from `clean0` that reach a clean state related to `v` by `R`. Hoare +triples (`Life.Tri`) over `Acc` carry the clean run through binds and loops; a send of +the hold extends it by one clean step (`Acc.extend`), given that step as `Emits`. +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open CCF (Envelope Outputs Capabilities) +open CCF.Sections (LocalRun) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +theorem localRun_snoc {Node LocalState LocalAction Message Notification Input : Type} + {protocol + : CCF.MultiNodeTransitionSystem.Protocol Node LocalState LocalAction Message + Notification Input} + {node : Node} {start finish last : LocalState} {actions : List LocalAction} + {sends : List (Envelope Node Message)} {action : LocalAction} + {effects : Outputs Node Message Notification} + (run : LocalRun protocol node start actions finish sends) + (step + : (protocol.step (Capabilities.record node) node finish action).run {} + = some (last, effects)) + : LocalRun protocol node start (actions ++ [action]) last + (sends ++ effects.outgoing) := by + induction run with + | nil state => + have := LocalRun.cons step (LocalRun.nil (protocol := protocol) (node := node) last) + simpa using this + | cons first _ ih => + have := LocalRun.cons first (ih step) + simpa [List.append_assoc] using this + +/-! ## Clean effects that succeed with known sends -/ + +/-- `x` succeeds from any outputs with result `a`, appending exactly `sends`. -/ +def Emits {α : Type} (x : NodeEffect α) (a : α) (sends : List (Envelope NodeID Message)) + : Prop := + forall out : Outputs NodeID Message Notification, + x.run out = some (a, { out with outgoing := out.outgoing ++ sends }) + +theorem emits_pure {α : Type} (a : α) : Emits (pure a : NodeEffect α) a [] := by + intro out + cases out + simp [StateT.run, pure, StateT.pure] + +theorem emits_bind {α β : Type} {x : NodeEffect α} {f : α -> NodeEffect β} {a : α} {b : β} + {first later : List (Envelope NodeID Message)} + (hx : Emits x a first) (hf : Emits (f a) b later) + : Emits (x >>= f) b (first ++ later) := by + intro out + have := hx out + simp only [StateT.run, bind, StateT.bind] at this ⊢ + rw [this] + simp only [Option.bind] + have := hf { out with outgoing := out.outgoing ++ first } + simp only [StateT.run, List.append_assoc] at this + exact this + +theorem emits_send {node : NodeID} (message : Message) (target : NodeID) + : Emits ((Capabilities.record node).send message target) () + [⟨node, target, message⟩] := by + intro out + rfl + +theorem emits_guard {p : Prop} [Decidable p] (h : p) + : Emits (guard p : NodeEffect Unit) () [] := by + intro out + cases out + simp [guard, h, StateT.run, pure, StateT.pure] + +theorem emits_congr {α : Type} {x : NodeEffect α} {a b : α} + {first later : List (Envelope NodeID Message)} + (h : Emits x a first) (same : a = b) (sends : first = later) + : Emits x b later := by + subst same sends + exact h + +theorem emits_run {α : Type} {x : NodeEffect α} {a : α} + {sends : List (Envelope NodeID Message)} + (h : Emits x a sends) + : x.run {} = some (a, { outgoing := sends }) := by + have := h {} + simpa using this + +theorem emits_forIn {node : NodeID} (peers : List NodeID) (f : NodeID -> Message) + : Emits + (forIn peers PUnit.unit + fun peer _ => do + (Capabilities.record node).send (f peer) peer + pure (ForInStep.yield PUnit.unit) + : NodeEffect PUnit) + PUnit.unit (peers.map fun peer => ⟨node, peer, f peer⟩) := by + induction peers with + | nil => exact emits_pure _ + | cons peer rest ih => + rw [List.forIn_cons] + refine emits_congr (emits_bind + (x := do (Capabilities.record node).send (f peer) peer; pure (ForInStep.yield PUnit.unit)) + (a := ForInStep.yield PUnit.unit) + (emits_bind (f := fun _ => pure (ForInStep.yield PUnit.unit)) (emits_send _ _) + (emits_pure _)) ih) rfl ?_ + simp + +/-! ## The ghost clean run -/ + +/-- Admitted whatever the other nodes' states: any internal input but `initAsBackup`. -/ +def Admitted (node : NodeID) (input : Input) : Prop := + forall others, admit others node input = true + +/-- +The outbox `o` is the sends of admitted clean internal steps of `node` from `clean0`, +which reach a clean state related to the declared state `v` by `R`; every send satisfies +`msgInv`. +-/ +def Acc (env : Env) (node : NodeID) (clean0 : NodeState) (R : NodeState -> State -> Prop) + (v : State) (o : Outbox) + : Prop := + exists (inputs : List Input) (clean : NodeState), + LocalRun (protocol env) node clean0 (inputs.map (protocol env).internal) clean o + /\ (forall input, input ∈ inputs -> Admitted node input) + /\ (forall e, e ∈ o -> msgInv env.names e = true) + /\ R clean v + +variable {env : Env} {node : NodeID} {clean0 : NodeState} + +theorem Acc.start {R : NodeState -> State -> Prop} {v : State} (r : R clean0 v) + : Acc env node clean0 R v [] := + ⟨[], clean0, LocalRun.nil _, by simp, by simp, r⟩ + +theorem Acc.mono {R R' : NodeState -> State -> Prop} {v v' : State} {o : Outbox} + (acc : Acc env node clean0 R v o) (h : forall clean, R clean v -> R' clean v') + : Acc env node clean0 R' v' o := by + obtain ⟨inputs, clean, run, ad, inv, r⟩ := acc + exact ⟨inputs, clean, run, ad, inv, h _ r⟩ + +/-- One clean internal step that emits `sends` extends the ghost run. -/ +theorem Acc.extend {R R' : NodeState -> State -> Prop} {v v' : State} {o : Outbox} + {sends : Outbox} (acc : Acc env node clean0 R v o) + (h + : forall clean, + R clean v + -> exists (input : Input) (clean' : NodeState), + Emits (act (Capabilities.record node) node clean input) clean' sends + /\ Admitted node input + /\ R' clean' v') + (sendsInv : forall e, e ∈ sends -> msgInv env.names e = true) + : Acc env node clean0 R' v' (o ++ sends) := by + obtain ⟨inputs, clean, run, ad, inv, r⟩ := acc + obtain ⟨input, clean', emits, admitted, r'⟩ := h clean r + have step : ((protocol env).step (Capabilities.record node) node clean + ((protocol env).internal input)).run {} = some (clean', { outgoing := sends }) := + emits_run emits + refine ⟨inputs ++ [input], clean', ?_, ?_, ?_, r'⟩ + · have := localRun_snoc (effects := { outgoing := sends }) run step + simpa using this + · intro i mem + rcases List.mem_append.mp mem with mem | mem + · exact ad i mem + · simp only [List.mem_singleton] at mem + exact mem ▸ admitted + · intro e mem + rcases List.mem_append.mp mem with mem | mem + · exact inv e mem + · exact sendsInv e mem + +theorem admitted_sendEntries (destination : NodeID) (endIndex : Nat) + : Admitted node (.sendEntries destination endIndex) := + fun _ => rfl + +theorem admitted_timeout (kind : TimeoutKind) : Admitted node (.timeout kind) := + fun _ => rfl + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickSend.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickSend.lean new file mode 100644 index 000000000000..53e6a3bd211e --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickSend.lean @@ -0,0 +1,254 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickPeers + +@[expose] public section + +/-! +# A leader's heartbeat (not reviewed; `Tick` obligation) + +Every run of the heartbeat's `send_append_entries` calls extends the ghost clean run by one +clean `sendEntries` per `send_append_entries_range`, keeping `HbRel`. +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) +open Life (Tri Pres) + +variable {env : Env} {α β : Type} + +/-! ## Triple helpers -/ + +theorem tri_keeps_bind {x : M α} {f : α -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} (k : Spec.Keeps env x) + (hf : forall a, Tri env P (f a) R) + : Tri env P (x >>= f) R := + Tri.bind (Tri.keeps k) hf + +theorem tri_pres_bind {x : M α} {f : α -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} (hx : Pres env P x) + (hf : forall a, Tri env P (f a) R) + : Tri env P (x >>= f) R := + Tri.bind hx hf + +/-- Read the declared state, pinning the state and outbox it was read in. -/ +theorem tri_getV {f : State -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} + (h : forall v o, P v o -> Tri env (fun w o' => w = v /\ o' = o) (f v) R) + : Tri env P (getV >>= f) R := + Tri.getV_bind fun v c a c' e ⟨p, eq⟩ r => h v c.outbox (eq ▸ p) c a c' e ⟨eq, rfl⟩ r + +theorem tri_names {f : Names -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} (h : Tri env P (f env.names) R) + : Tri env P (Exec.names >>= f) R := by + refine Tri.bind (Tri.ofSpec (Q := fun a w o => a = env.names /\ P w o) Spec.names + fun _ _ _ _ _ p s => by obtain ⟨rfl, rfl, rfl⟩ := s; exact ⟨rfl, p⟩) fun a => ?_ + intro c b c' e ⟨ha, p⟩ r + subst ha + exact h c b c' e p r + +/-! ## One range -/ + +variable {node : NodeID} {s0 : State} {clean0 : NodeState} + +/-- The heartbeat invariant: the outbox is a ghost clean run reaching `HbRel`. -/ +abbrev HbAcc (env : Env) (node : NodeID) (s0 : State) (clean0 : NodeState) (v : State) + (o : Outbox) + : Prop := + Acc env node clean0 (HbRel env.names s0 clean0) v o + +theorem HbAcc.shape {v : State} {o : Outbox} (acc : HbAcc env node s0 clean0 v o) + : exists L, + v = { s0 with allOtherNodes := L } + /\ (L.map Prod.fst).Perm (s0.allOtherNodes.map Prod.fst) := by + obtain ⟨_, _, _, _, _, L, _, hv, _, perm, _⟩ := acc + exact ⟨L, hv, perm⟩ + +theorem tri_range (H : HbHyps env.names node s0 clean0) (to : NodeId) (start endIdx : Nat) + (ext : Bool) + : Tri env + (fun v o => + HbAcc env node s0 clean0 v o + /\ exists p, + v.peer? to = some p + /\ p.sentIdx + 1 = start + /\ p.sentIdx <= endIdx + /\ endIdx <= s0.lastIdx + /\ forall i, p.sentIdx < i -> i <= endIdx -> s0.viewAt i = s0.viewAt endIdx) + (sendAppendEntriesRange to start endIdx ext) + (fun _ v o => + HbAcc env node s0 clean0 v o + /\ exists p, v.peer? to = some p /\ p.sentIdx = endIdx) := by + unfold sendAppendEntriesRange + refine tri_getV fun v o ⟨acc, p, found, ps, e1, eL, same⟩ => ?_ + obtain ⟨L, hv, perm⟩ := acc.shape + have ndv : (v.allOtherNodes.map Prod.fst).Nodup := by + subst hv + exact perm.nodup_iff.mpr H.nodup + have self : env.names.id v.nodeId = node := by + subst hv + exact H.self + subst ps + simp only [found] + refine tri_keeps_bind (Spec.emit _ _) fun _ => ?_ + refine tri_keeps_bind (Spec.emitStr _ _) fun _ => ?_ + refine tri_names ?_ + refine Tri.bind + (Tri.send + (Q := + fun _ w o' => + w = v + /\ o' + = o + ++ [⟨ + node, + env.names.id to, + .appendEntriesRequest (aeOf env.names v (p.sentIdx + 1) endIdx) + ⟩]) + fun w o' ⟨hw, ho⟩ => ⟨hw, by subst hw ho; rw [self]; rfl⟩) + fun _ => ?_ + refine tri_keeps_bind (Spec.note _) fun _ => ?_ + refine Tri.setV fun w o' ⟨hw, ho⟩ => ?_ + subst hw ho + obtain ⟨_, _, _, _, _, r⟩ := id acc + have step := hb_step H r found e1 eL same + refine ⟨Acc.extend acc (fun clean r => ?_) ?_, ?_⟩ + · obtain ⟨em, rel, _⟩ := hb_step H r found e1 eL same + exact ⟨_, _, em, admitted_sendEntries _ _, rel⟩ + · intro e mem + simp only [List.mem_singleton] at mem + subst mem + have := step.2.2 + rw [self] at this + exact this + · refine ⟨{ p with sentIdx := endIdx }, ?_, rfl⟩ + rw [setPeer_lookup ndv] + simp + +/-! ## One `send_append_entries` -/ + +/-- The loop's precondition: the peer's next index is `start`. -/ +abbrev HbFrom (env : Env) (node : NodeID) (s0 : State) (clean0 : NodeState) (to : NodeId) + (start : Nat) (v : State) (o : Outbox) + : Prop := + HbAcc env node s0 clean0 v o + /\ exists p, v.peer? to = some p /\ p.sentIdx + 1 = start /\ p.sentIdx <= s0.lastIdx + +/-- The range end the loop accepts lies in the ledger and in one view. -/ +theorem hb_ok (H : HbHyps env.names node s0 clean0) {prev endIdx : Nat} + (pL : prev <= s0.lastIdx) + (ok + : (if prev + 1 > maxIdx s0 (prev + 1) then + endIdx == maxIdx s0 (prev + 1) + else + decide (prev + 1 <= endIdx) && decide (endIdx <= maxIdx s0 (prev + 1))) + = true) + : prev <= endIdx + /\ endIdx <= s0.lastIdx + /\ forall i, prev < i -> i <= endIdx -> s0.viewAt i = s0.viewAt endIdx := by + have vh := ViewHyps.ofInv H.inv + by_cases past : prev = s0.lastIdx + · subst past + rw [maxIdx_past vh] at ok + simp only [Nat.lt_add_one, ↓reduceIte, beq_iff_eq] at ok + subst ok + exact ⟨Nat.le_refl _, Nat.le_refl _, fun i lo hi => absurd hi (by omega)⟩ + · obtain ⟨lo, hi, same⟩ := maxIdx_range vh (start := prev + 1) (by omega) (by omega) + simp only [show Not (prev + 1 > maxIdx s0 (prev + 1)) by omega, ↓reduceIte, + Bool.and_eq_true, decide_eq_true_eq] at ok + refine ⟨by omega, by omega, fun i l h => ?_⟩ + rw [same i (by omega) (by omega), same endIdx ok.1 ok.2] + +theorem tri_tail (H : HbHyps env.names node s0 clean0) {to : NodeId} {ext : Bool} + {fuel : Nat} + (ih + : forall start batch, + Tri env (HbFrom env node s0 clean0 to start) + (sendAppendEntries.loop to ext fuel start batch) + (fun _ => HbAcc env node s0 clean0)) + {v : State} {o : Outbox} (acc : HbAcc env node s0 clean0 v o) {p : Peer} + (found : v.peer? to = some p) (pL : p.sentIdx <= s0.lastIdx) {endIdx : Nat} + {batch : Option Nat} + (ok + : (if p.sentIdx + 1 > maxIdx v (p.sentIdx + 1) then + endIdx == maxIdx v (p.sentIdx + 1) + else + decide (p.sentIdx + 1 <= endIdx) + && decide (endIdx <= maxIdx v (p.sentIdx + 1))) + = true) + : Tri env (fun w o' => w = v /\ o' = o) + (do + sendAppendEntriesRange to (p.sentIdx + 1) endIdx ext + let v ← getV + unless endIdx == v.lastIdx do + sendAppendEntries.loop to ext fuel (min (endIdx + 1) v.lastIdx) batch) + (fun _ => HbAcc env node s0 clean0) := by + obtain ⟨L, hv, _⟩ := acc.shape + have mx : maxIdx v (p.sentIdx + 1) = maxIdx s0 (p.sentIdx + 1) := by subst hv; rfl + rw [mx] at ok + obtain ⟨e1, eL, same⟩ := hb_ok H pL ok + refine Tri.bind (Tri.conseq (tri_range H to (p.sentIdx + 1) endIdx ext) + (fun w o' ⟨hw, ho⟩ => by subst hw ho; exact ⟨acc, p, found, rfl, e1, eL, same⟩) + (fun _ _ _ h => h)) fun _ => ?_ + refine tri_getV fun v' o' ⟨acc', p', found', ps'⟩ => ?_ + obtain ⟨L', hv', _⟩ := acc'.shape + have last : v'.lastIdx = s0.lastIdx := by subst hv'; rfl + refine Tri.ite (fun _ => ?_) (fun ne => ?_) + · exact Tri.conseq (Tri.pure' (Q := fun _ => HbAcc env node s0 clean0) ()) + (fun w o'' ⟨hw, ho⟩ => by subst hw ho; exact acc') (fun _ _ _ h => h) + · simp only [beq_iff_eq, last] at ne + exact Tri.conseq (ih _ _) + (fun w o'' ⟨hw, ho⟩ => by + subst hw ho + exact ⟨acc', p', found', by rw [ps', last]; omega, by omega⟩) + (fun _ _ _ h => h) + +theorem tri_loop (H : HbHyps env.names node s0 clean0) (to : NodeId) (ext : Bool) + (fuel start : Nat) (batch : Option Nat) + : Tri env (HbFrom env node s0 clean0 to start) + (sendAppendEntries.loop to ext fuel start batch) + (fun _ => HbAcc env node s0 clean0) := by + induction fuel generalizing start batch with + | zero => + unfold sendAppendEntries.loop + exact tri_keeps_bind Spec.curLoc fun _ => Tri.fail _ + | succ fuel ih => + rw [sendAppendEntries.loop] + dsimp only + refine tri_getV fun v o ⟨acc, p, found, ps, pL⟩ => ?_ + obtain ⟨L, hv, _⟩ := acc.shape + have nrc : v.isRetiredCommitted = false := by subst hv; exact H.notRC + subst ps + simp only [nrc, Bool.false_and, Bool.false_eq_true, ↓reduceIte] + repeat' + first + | exact Tri.fail_bind _ + | exact Tri.fail _ + | exact tri_tail H ih acc found pL (by assumption) + | refine tri_keeps_bind Spec.curLoc fun _ => ?_ + | refine Tri.ite (fun _ => ?_) (fun _ => ?_) + | refine tri_pres_bind (by repeat' pres_step) fun _ => ?_ + +theorem tri_sendAE (H : HbHyps env.names node s0 clean0) (to : NodeId) (start : Nat) + (ext : Bool) + : Tri env (HbFrom env node s0 clean0 to start) (sendAppendEntries to start ext) + (fun _ => HbAcc env node s0 clean0) := by + unfold sendAppendEntries + exact Tri.getV_bind fun _ => + Tri.conseq (tri_loop H to ext _ start none) (fun _ _ h => h.1) (fun _ _ _ h => h) + +/-- A peer of the heartbeat's declared state has sent no index beyond the ledger. -/ +theorem HbAcc.bound {v : State} {o : Outbox} (acc : HbAcc env node s0 clean0 v o) + {to : NodeId} {p : Peer} (found : v.peer? to = some p) + : p.sentIdx <= s0.lastIdx := by + obtain ⟨_, _, _, _, _, L, f, hv, _, _, rel⟩ := acc + subst hv + exact (rel to p found).2.2 + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickViews.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickViews.lean new file mode 100644 index 000000000000..b49b9f72167d --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickViews.lean @@ -0,0 +1,189 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeLemmas +public import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit + +@[expose] public section + +/-! +# The batch range of `send_append_entries` (not reviewed; `Tick` obligation) + +`send_append_entries` sends from `start` up to an end chosen in `[start, maxIdx]`, where +`maxIdx` is the end of the view of `start` (or the last index). On a declared state whose +view history is sorted, positive, at most one past the ledger, and assigns every entry its +term (`ViewHyps`, from `inv`), that range is inside the ledger and in one view +(`maxIdx_range`, `viewAt_const`), and from `lastIdx + 1` it is empty (`maxIdx_past`). +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec + +/-- A list whose adjacent elements are ordered is sorted. -/ +theorem pairwise_of_adjacent + : forall {l : List Nat}, + (l.zip l.tail).all (fun (x, y) => decide (x <= y)) = true -> l.Pairwise (· <= ·) + | [], _ => .nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: t, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true, + decide_eq_true_eq] at h + have rest : (b :: t).Pairwise (· <= ·) := pairwise_of_adjacent (by simpa using h.2) + refine List.Pairwise.cons ?_ rest + intro x mem + rcases List.mem_cons.mp mem with rfl | mem + · exact h.1 + · exact Nat.le_trans h.1 (List.rel_of_pairwise_cons rest mem) + +/-- In a sorted list, the `k`-th element is at most `i` iff more than `k` elements are. -/ +theorem lt_length_filter_iff + : forall {l : List Nat}, + l.Pairwise (· <= ·) + -> forall {k : Nat} (hk : k < l.length) (i : Nat), + k < (l.filter fun x => decide (x <= i)).length <-> l[k] <= i + | [], _, k, hk, _ => by simp at hk + | a :: t, sorted, k, hk, i => by + have rest := List.Pairwise.of_cons sorted + by_cases ai : a <= i + · rw [List.filter_cons_of_pos (by simpa using ai), List.length_cons] + cases k with + | zero => simp [ai] + | succ k => + simp only [List.getElem_cons_succ] + have := lt_length_filter_iff rest (k := k) (by simpa using hk) i + omega + · rw [List.filter_cons_of_neg (by simpa using ai)] + have none_ : (t.filter fun x => decide (x <= i)) = [] := + List.filter_eq_nil_iff.mpr fun y mem => by + have := List.rel_of_pairwise_cons sorted mem + simp only [decide_eq_true_eq] + omega + rw [none_] + cases k with + | zero => simp [ai] + | succ k => + simp only [List.length_nil, Nat.not_lt_zero, false_iff, List.getElem_cons_succ] + have := List.rel_of_pairwise_cons sorted (List.getElem_mem (l := t) + (show k < t.length by simpa using hk)) + omega + +/-- What the batch range needs of the view history, from `inv`. -/ +structure ViewHyps (v : State) : Prop where + size : v.ledger.size = v.lastIdx + sorted : v.views.toList.Pairwise (· <= ·) + positive : forall x, x ∈ v.views.toList -> 0 < x + leLast : forall x, x ∈ v.views.toList -> x <= v.lastIdx + 1 + terms + : forall i, + 1 <= i -> i <= v.lastIdx -> v.ledger[i - 1]?.map (·.term) = some (v.viewAt i) + posTerms : forall e, e ∈ v.ledger.toList -> 0 < e.term + +open Consensus.TraceValidation (Names) in +theorem ViewHyps.ofInv {names : Names} {v : State} (h : inv names v = true) + : ViewHyps v := by + obtain ⟨size, _, _, _, terms, _, positive⟩ := Ae.inv_parts h + have sorted : (v.views.toList.zip v.views.toList.tail).all + (fun (x, y) => decide (x <= y)) = true := by + inv_conj h "views_sorted" + have leLast : v.views.all (· <= v.lastIdx + 1) = true := by inv_conj h "views_le_last" + have posTerms : v.ledger.all (0 < ·.term) = true := by inv_conj h "positive_terms" + refine ⟨size, pairwise_of_adjacent sorted, ?_, ?_, terms, ?_⟩ + · intro x mem + have := Array.all_eq_true_iff_forall_mem.mp positive x (by simpa using mem) + simpa using this + · intro x mem + have := Array.all_eq_true_iff_forall_mem.mp leLast x (by simpa using mem) + simpa using this + · intro e mem + have := Array.all_eq_true_iff_forall_mem.mp posTerms e (by simpa using mem) + simpa using this + +/-- `send_append_entries`'s `max_idx` from `start`. -/ +def maxIdx (v : State) (start : Nat) : Nat := + match v.endOfView (v.viewAt start) with + | 0 => v.lastIdx + | e => e + +variable {v : State} + +theorem viewAt_ge_iff (h : ViewHyps v) {k : Nat} (hk : k < v.views.size) (i : Nat) + : k < v.viewAt i <-> v.views[k] <= i := by + unfold State.viewAt + have := lt_length_filter_iff h.sorted (k := k) (by simpa using hk) i + simpa using this + +theorem viewAt_pos (h : ViewHyps v) {i : Nat} (i1 : 1 <= i) (iL : i <= v.lastIdx) + : 0 < v.viewAt i := by + have t := h.terms i i1 iL + have lt : i - 1 < v.ledger.size := by rw [h.size]; omega + rw [Array.getElem?_eq_getElem lt] at t + simp only [Option.map_some, Option.some.injEq] at t + rw [← t] + exact h.posTerms _ (by simp) + +theorem viewAt_past (h : ViewHyps v) : v.viewAt (v.lastIdx + 1) = v.views.size := by + unfold State.viewAt + rw [List.filter_eq_self.mpr (fun x mem => by simpa using h.leLast x mem)] + simp + +/-- The range from `start` within the ledger: it ends in the ledger, in the view of `start`. -/ +theorem maxIdx_range (h : ViewHyps v) {start : Nat} (s1 : 1 <= start) + (sL : start <= v.lastIdx) + : start <= maxIdx v start + /\ maxIdx v start <= v.lastIdx + /\ forall i, start <= i -> i <= maxIdx v start -> v.viewAt i = v.viewAt start := by + have w1 := viewAt_pos h s1 sL + have wS := ReplUpdateCommit.viewAt_le_size v start + generalize hw : v.viewAt start = w at w1 wS + have prevLe : v.views[w - 1] <= start := + (viewAt_ge_iff h (k := w - 1) (by omega) start).mp (by omega) + have prevPos : 0 < v.views[w - 1] := h.positive _ (by simp) + by_cases last : w < v.views.size + · have nextGt : start < v.views[w] := by + have := viewAt_ge_iff h (k := w) last start + omega + have nextLe : v.views[w] <= v.lastIdx + 1 := h.leLast _ (by simp) + have eov : v.endOfView w = v.views[w] - 1 := by + have ne : Not (v.views[w] = v.views[w - 1]) := by omega + simp [State.endOfView, State.startOfView, last, Nat.not_lt.mpr (Nat.le_of_lt last), + Nat.ne_of_gt w1, ne, Nat.succ_le_of_lt last, + getElem!_pos v.views (w - 1) (by omega), Nat.ne_of_gt prevPos, Nat.not_le.mpr last] + have mx : maxIdx v start = v.views[w] - 1 := by + unfold maxIdx + rw [hw, eov] + split + · omega + · rfl + rw [mx] + refine ⟨by omega, by omega, fun i si im => ?_⟩ + have lo := ReplUpdateCommit.viewAt_mono v si + have hi : Not (w < v.viewAt i) := fun lt => by + have := (viewAt_ge_iff h last i).mp lt + omega + omega + · have eq : w = v.views.size := by omega + have eov : v.endOfView w = 0 := by + simp [State.endOfView, eq] + have mx : maxIdx v start = v.lastIdx := by + unfold maxIdx + rw [hw, eov] + rfl + rw [mx] + refine ⟨sL, Nat.le_refl _, fun i si _ => ?_⟩ + have lo := ReplUpdateCommit.viewAt_mono v si + have hi := ReplUpdateCommit.viewAt_le_size v i + omega + +/-- From one past the ledger, the range is empty: it ends at the last index. -/ +theorem maxIdx_past (h : ViewHyps v) : maxIdx v (v.lastIdx + 1) = v.lastIdx := by + unfold maxIdx + rw [viewAt_past h] + have eov : v.endOfView v.views.size = 0 := by simp [State.endOfView] + rw [eov] + rfl + +end Consensus.TraceValidation.Proofs.Tick diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickVotes.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickVotes.lean new file mode 100644 index 000000000000..ffa9279995cb --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/TickVotes.lean @@ -0,0 +1,225 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.TickSend + +@[expose] public section + +/-! +# The self-vote of an election timeout (not reviewed; `Tick` obligation) +-/ + +namespace Consensus.TraceValidation.Proofs.Tick + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv) +open Life (Tri Pres) + +variable {env : Env} + +theorem tri_pre_prop {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} {p : Prop} (h : p -> Tri env P x Q) + : Tri env (fun w o => P w o /\ p) x Q := by + intro c a c' e q run + exact h q.2 c a c' e q.1 run + +/-- A loop whose body leaves the state and outbox alone is a fold. -/ +theorem tri_forIn_pure {α β : Type} {l : List α} {init : β} + {f : α -> β -> M (ForInStep β)} (g : β -> α -> β) {v : State} {O : Outbox} + (h + : forall a b, + a ∈ l + -> Tri env (fun w o => w = v /\ o = O) (f a b) + (fun r w o => w = v /\ o = O /\ r = .yield (g b a))) + : Tri env (fun w o => w = v /\ o = O) (forIn l init f) + (fun r w o => w = v /\ o = O /\ r = l.foldl g init) := by + induction l generalizing init with + | nil => + rw [List.forIn_nil] + exact Tri.conseq (Tri.pure' (Q := fun r w o => w = v /\ o = O /\ r = init) init) + (fun _ _ ⟨hw, ho⟩ => ⟨hw, ho, rfl⟩) (fun _ _ _ h => h) + | cons a rest ih => + rw [List.forIn_cons] + refine Tri.bind (h a init List.mem_cons_self) fun r => ?_ + refine Tri.conseq (P' := fun w o => w = v /\ o = O /\ r = .yield (g init a)) ?_ + (fun _ _ h => h) (fun _ _ _ h => h) + intro c x c' e ⟨hw, ho, hr⟩ run + subst hr + exact ih (fun a' b' m => h a' b' (List.mem_cons_of_mem _ m)) c x c' e ⟨hw, ho⟩ run + +/-- One configuration's round of `recordVote`'s loop. -/ +def voteStep (self : NodeId) (votes : List (Nat × List NodeId × Nat)) (c : Config) + : List (Nat × List NodeId × Nat) := + if (c.nodes.any fun x => x.fst == self) = true then + match votes.find? (fun x => x.fst == c.idx) with + | some _ => + votes.map + fun (i, vs, q) => + if (i == c.idx) = true then + (i, if vs.contains self = true then vs else vs ++ [self], q) + else + (i, vs, q) + | none => (votes ++ [(c.idx, [self], 0)]).mergeSort fun a b => decide (a.fst ≤ b.fst) + else + votes + +theorem tri_recordVote (self : NodeId) (v : State) (O : Outbox) + (ne : v.configurations ≠ []) + : Tri env (fun w o => w = v /\ o = O) (recordVote self) + (fun b w o => + let votes := v.configurations.foldl (voteStep self) v.votesForMe + w = { v with votesForMe := votes } + /\ o = O + /\ b = votes.all fun (_, vs, q) => decide (vs.length ≥ q)) := by + unfold recordVote + refine tri_getV fun w o ⟨hw, ho⟩ => ?_ + subst w o + simp only [List.isEmpty_iff, ne, ↓reduceIte] + refine Tri.bind (tri_forIn_pure (voteStep self) fun c b _ => ?_) fun r => ?_ + · unfold voteStep + split + · exact Tri.conseq (Tri.pure' _) (fun _ _ h => by obtain ⟨hw, ho⟩ := h; exact ⟨hw, ho, rfl⟩) + (fun _ _ _ h => h) + · exact Tri.conseq (Tri.pure' _) (fun _ _ h => by obtain ⟨hw, ho⟩ := h; exact ⟨hw, ho, rfl⟩) + (fun _ _ _ h => h) + · refine Tri.conseq (tri_pre_prop (P := fun w o => w = v /\ o = O) + (p := r = v.configurations.foldl (voteStep self) v.votesForMe) fun hr => ?_) + (fun _ _ h => by obtain ⟨hw, ho, hr⟩ := h; exact ⟨⟨hw, ho⟩, hr⟩) (fun _ _ _ h => h) + subst hr + exact Tri.bind (Tri.setV (Q := fun _ w o => + w = { v with votesForMe := v.configurations.foldl (voteStep self) v.votesForMe } /\ o = O) + fun _ _ h => by obtain ⟨hw, ho⟩ := h; exact ⟨by rw [hw], ho⟩) + (fun _ => Tri.conseq (Tri.pure' _) (fun _ _ h => by obtain ⟨hw, ho⟩ := h; exact ⟨hw, ho, rfl⟩) + (fun _ _ _ h => h)) + +/-- Whether configuration `c` lists `self`. -/ +def Lists (self : NodeId) (c : Config) : Prop := + (c.nodes.any fun x => x.fst == self) = true + +instance (self : NodeId) (c : Config) : Decidable (Lists self c) := by + unfold Lists; infer_instance + +/-- The vote record of `c` once the configurations `S` have recorded `self`'s vote. -/ +def voteRec (self : NodeId) (S : List Config) (c : Config) : Nat × List NodeId × Nat := + ( + c.idx, + if (S.any fun c' => c'.idx == c.idx && decide (Lists self c')) then [self] else [], + State.quorum c.nodes.length + ) + +theorem voteStep_rec (self : NodeId) (cs S : List Config) {c : Config} (mem : c ∈ cs) + : voteStep self (cs.map (voteRec self S)) c = cs.map (voteRec self (S ++ [c])) := by + unfold voteStep + by_cases P : Lists self c + · have P' : (c.nodes.any fun x => x.fst == self) = true := P + simp only [P', ↓reduceIte] + cases hf : (cs.map (voteRec self S)).find? (fun x => x.fst == c.idx) with + | none => + have := List.find?_eq_none.mp hf (voteRec self S c) (List.mem_map_of_mem mem) + simp [voteRec] at this + | some _ => + simp only [List.map_map] + apply List.map_congr_left + intro c'' _ + simp only [Function.comp, voteRec, List.any_append, List.any_cons, List.any_nil, + Bool.or_false] + by_cases hi : c''.idx = c.idx + · simp only [hi, BEq.rfl, ↓reduceIte, P, decide_true, Bool.and_true, Bool.or_true] + split <;> simp + · have : (c''.idx == c.idx) = false := by simpa using hi + have h2 : (c.idx == c''.idx) = false := by simpa using Ne.symm hi + simp [this, h2] + · have P' : (c.nodes.any fun x => x.fst == self) = false := by + unfold Lists at P; exact Bool.eq_false_iff.mpr P + simp only [P', Bool.false_eq_true, ↓reduceIte] + apply List.map_congr_left + intro c'' _ + have hP : decide (Lists self c) = false := decide_eq_false P + simp only [voteRec, List.any_append, List.any_cons, List.any_nil, Bool.or_false, hP, + Bool.and_false] + +theorem foldl_voteStep (self : NodeId) (cs : List Config) + : forall (S rest : List Config), + (forall c, c ∈ rest -> c ∈ cs) + -> rest.foldl (voteStep self) (cs.map (voteRec self S)) + = cs.map (voteRec self (S ++ rest)) := by + intro S rest + induction rest generalizing S with + | nil => intro _; simp + | cons c rest ih => + intro sub + rw [List.foldl_cons, voteStep_rec self cs S (sub c List.mem_cons_self), + ih _ fun c' m => sub c' (List.mem_cons_of_mem _ m)] + simp + +theorem idx_inj {cs : List Config} (sorted : cs.Pairwise fun a b => a.idx < b.idx) + {a b : Config} (ma : a ∈ cs) (mb : b ∈ cs) (h : a.idx = b.idx) + : a = b := by + induction cs with + | nil => cases ma + | cons x rest ih => + obtain ⟨lt, sorted⟩ := List.pairwise_cons.mp sorted + rcases List.mem_cons.mp ma with ha | ma <;> rcases List.mem_cons.mp mb with hb | mb + · rw [ha, hb] + · have := lt b mb; rw [ha] at h; omega + · have := lt a ma; rw [hb] at h; omega + · exact ih sorted ma mb + +/-- +After a reset, `self`'s own vote leaves each configuration's record with `self` alone if it +lists `self` and empty otherwise, provided the configurations have distinct indexes. +-/ +theorem selfVote_eq (self : NodeId) (cs : List Config) + (sorted : cs.Pairwise fun a b => a.idx < b.idx) + : cs.foldl (voteStep self) (cs.map fun c => (c.idx, [], State.quorum c.nodes.length)) + = cs.map + fun c => + ( + c.idx, + if Lists self c then [self] else [], + State.quorum c.nodes.length + ) := by + have h0 := foldl_voteStep self cs [] cs (fun _ m => m) + simp only [List.nil_append] at h0 + have e0 : (cs.map fun c => (c.idx, ([] : List NodeId), State.quorum c.nodes.length)) + = cs.map (voteRec self []) := by + simp [voteRec] + rw [e0, h0] + apply List.map_congr_left + intro c mem + simp only [voteRec] + congr 2 + by_cases P : Lists self c + · simp only [P, ↓reduceIte] + simp only [List.any_eq_true, Bool.and_eq_true, beq_iff_eq, decide_eq_true_eq] + simp only [ite_eq_left_iff, reduceCtorEq, imp_false, Classical.not_not] + exact ⟨c, mem, rfl, P⟩ + · simp only [P, ↓reduceIte] + simp only [ite_eq_right_iff, reduceCtorEq, imp_false, List.any_eq_true, Bool.and_eq_true, + beq_iff_eq, decide_eq_true_eq, not_exists, not_and] + intro c' mem' hi P' + exact P (idx_inj sorted mem' mem hi ▸ P') + +/-- The self-vote elects iff every configuration is `self` alone. -/ +theorem selfVote_all (self : NodeId) (cs : List Config) + : ((cs.map + fun c => + (c.idx, if Lists self c then [self] else [], State.quorum c.nodes.length)).all + fun (_, vs, q) => decide (vs.length ≥ q)) + = decide (forall c, c ∈ cs -> Lists self c /\ c.nodes.length <= 1) := by + rw [Bool.eq_iff_iff] + simp only [List.all_map, List.all_eq_true, Function.comp, decide_eq_true_eq, State.quorum] + apply forall_congr'; intro c; apply imp_congr_right; intro _ + by_cases P : Lists self c <;> simp only [P, ↓reduceIte, List.length_singleton, + List.length_nil, true_and, false_and] + · generalize c.nodes.length = n + constructor + · intro h; omega + · intro h; omega + · generalize c.nodes.length = n + simp only [iff_false]; omega + +end Consensus.TraceValidation.Proofs.Tick From 20db0b5f94bd6d82b9fbe884ed981a292da72399 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:32 +0000 Subject: [PATCH 14/25] Prove the replicate obligation A leader's `replicate` of a batch (entry admission, configuration and retirement hooks, peer creation, flushing AppendEntries and committing) refines the clean append and send steps. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 2 +- .../Proofs/Handlers/ReplAppend.lean | 809 ++++++++++++++++++ .../Proofs/Handlers/ReplBatch.lean | 119 +++ .../Proofs/Handlers/ReplClean.lean | 94 ++ .../Proofs/Handlers/ReplCommit.lean | 459 ++++++++++ .../Proofs/Handlers/ReplCreate.lean | 192 +++++ .../Proofs/Handlers/ReplEmits.lean | 106 +++ .../Proofs/Handlers/ReplEntry.lean | 487 +++++++++++ .../Proofs/Handlers/ReplFlush.lean | 326 +++++++ .../Proofs/Handlers/ReplMid.lean | 382 +++++++++ .../Proofs/Handlers/ReplPeerSend.lean | 99 +++ .../Proofs/Handlers/ReplPeers.lean | 275 ++++++ .../Proofs/Handlers/ReplPush.lean | 173 ++++ .../Proofs/Handlers/ReplSend.lean | 383 +++++++++ .../Proofs/Handlers/Replicate.lean | 380 ++++++++ 15 files changed, 4285 insertions(+), 1 deletion(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplAppend.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplBatch.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplClean.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCommit.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCreate.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEmits.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEntry.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplFlush.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplMid.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeerSend.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeers.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPush.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplSend.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Replicate.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 38ba99223683..777f34303701 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -6,12 +6,12 @@ public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks import Consensus.TraceValidation.Proofs.Handlers.AppendEntries -import Consensus.TraceValidation.Proofs.Handlers.AppendEntriesResponse import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup import Consensus.TraceValidation.Proofs.Handlers.OutOfLockHook import Consensus.TraceValidation.Proofs.Handlers.ProposeRequestVote +import Consensus.TraceValidation.Proofs.Handlers.Replicate import Consensus.TraceValidation.Proofs.Handlers.RequestPreVote import Consensus.TraceValidation.Proofs.Handlers.RequestPreVoteResponse import Consensus.TraceValidation.Proofs.Handlers.RequestVote diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplAppend.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplAppend.lean new file mode 100644 index 000000000000..ff61634429ad --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplAppend.lean @@ -0,0 +1,809 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplPush + +@[expose] public section + +/-! +# Appending one entry: the declared side (not reviewed; `Replicate` obligation) + +`replicate_entry` checks an entry (`Guards`), runs its hooks, which change only the fields +`Hooked` lists, and appends it. The peers its configuration adds are the nodes the clean +`appendEntry` adds, with the same heartbeats, so the ghost extends by one clean entry +(`push_ghost`). +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation (Names abs absEntry msgInv) +open Consensus.TraceValidation.Exec +open ReplUpdateCommit (Named named_inj Hyps shifted_mem absConfig) +open CCF (Finset) + +/-- The declared entry `replicate_entry` appends. -/ +def entryOf (v : State) (sig : Bool) (config : Option Nodes) (retired : List NodeId) + : Exec.Entry := + { term := v.currentView, sig, config, retired } + +/-- The clean content of that entry. -/ +def contentOf (names : Names) (v : State) (sig : Bool) (config : Option Nodes) + (retired : List NodeId) + : EntryContent := + (absEntry names (entryOf v sig config retired)).content + +/-- The configuration the entry adds to the declared configurations. -/ +def cfgsOf (v : State) (config : Option Nodes) : List Config := + (config.map + fun nodes => ({ idx := v.lastIdx + 1, nodes, rid := v.lastIdx + 1 } : Config)).toList + +/-- The nodes the entry's configuration adds as peers. -/ +def newE (v : State) (config : Option Nodes) : List NodeId := + newOf v + (((v.configurations ++ cfgsOf v config).flatMap (·.nodes.map Prod.fst)).mergeSort + (· <= ·) + |>.eraseDups) + +/-- What `replicate_entry` checks of an entry before appending it. -/ +structure Guards (names : Names) (v : State) (sig : Bool) (config : Option Nodes) + (retired : List NodeId) + : Prop where + sigNonempty : sig = true -> v.lastIdx ≠ 0 + sigPlain : sig = true -> retired = [] /\ config = none + rc + : retired ≠ [] + -> names.set retired + ⊆ (abs names v).retirementCompletedNodes + \ retiredCommittedNodes (abs names v).log + known + : forall id, + id ∈ (config.getD []).map Prod.fst ++ retired -> names.known.contains id = true + sorted : (config.getD []).map Prod.fst ++ retired ≠ [] -> SortedNames names + cfg + : forall nodes, + config = some nodes + -> (nodes.map Prod.fst).Nodup + /\ nodes ≠ [] + /\ names.set (nodes.map Prod.fst) + ≠ latestConfigurationMembers (configurationHistory (abs names v).log) + /\ forall a, a ∈ nodes -> names.id a.1 ∉ removedNodes (abs names v).log + +/-- The retirement confirmations the entry adds to the declared ones. -/ +def rcsOf (v : State) (retired : List NodeId) : List (Nat × List NodeId) := + if retired.isEmpty then [] else [(v.lastIdx + 1, retired)] + +/-- The state after the hooks: only these fields have changed. -/ +def Hooked (v1 : State) (K : List Nat) (cfgs : List Config) (R : List (Nat × List NodeId)) + (w : State) + : Prop := + exists tk r ph ri rci ps, + w + = { + v1 with + committable := v1.committable ++ K, + configurations := v1.configurations ++ cfgs, + allOtherNodes := ps, + rcEntries := v1.rcEntries ++ R, + ticking := tk, + retired := r, + retirementPhase := ph, + retirementIdx := ri, + retirementCommittableIdx := rci + } + +/-- The state after the entry is appended and the view history extended. -/ +def pushed (v1 w : State) (e : Exec.Entry) : State := + { + w with + lastIdx := v1.lastIdx + 1, + ledger := w.ledger.push e + views := w.views ++ Array.replicate (w.currentView - w.views.size) (v1.lastIdx + 1) + } + +variable {env : Env} {names : Names} {node : NodeID} {v0 : State} {cl0 : NodeState} + +section +variable (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) +include S M + +theorem Mid.mem_newE {config : Option Nodes} {k : NodeId} + : k ∈ newE v1 config + <-> (exists nodes, config = some nodes /\ k ∈ nodes.map Prod.fst) + /\ k ≠ v1.nodeId + /\ v1.peer? k = none := by + unfold newE + rw [mem_newOf, (sortDedup_spec _).2, List.mem_flatMap] + constructor + · rintro ⟨⟨x, memX, memK⟩, ne, none⟩ + refine ⟨?_, ne, none⟩ + rcases List.mem_append.mp memX with memX | memX + · obtain ⟨a, ma, rfl⟩ := List.mem_map.mp memK + rcases M.member S memX ma with e | e + · exact absurd e ne + · have := peer_isSome_iff.mpr e + rw [none] at this + cases this + · cases hc : config with + | none => simp [cfgsOf, hc] at memX + | some nodes => + simp only [cfgsOf, hc, Option.map_some, Option.toList_some, List.mem_singleton] at memX + subst memX + exact ⟨nodes, rfl, memK⟩ + · rintro ⟨⟨nodes, rfl, memK⟩, ne, none⟩ + exact ⟨⟨{ idx := v1.lastIdx + 1, nodes, rid := v1.lastIdx + 1 }, List.mem_append_right _ (by simp [cfgsOf]), memK⟩, ne, none⟩ + +theorem Mid.named_of_newE {config : Option Nodes} {k : NodeId} {sig : Bool} + {retired : List NodeId} (G : Guards names v1 sig config retired) + (mem : k ∈ newE v1 config) + : names.known.contains k = true := by + obtain ⟨⟨nodes, rfl, memK⟩, -, -⟩ := (M.mem_newE S).mp mem + exact G.known k (List.mem_append_left _ (by simpa using memK)) + +theorem Mid.addedOf_iff {sig : Bool} {config : Option Nodes} {retired : List NodeId} + (G : Guards names v1 sig config retired) {p : NodeID} + : p ∈ addedOf cl1 node (contentOf names v1 sig config retired) + <-> exists k, k ∈ newE v1 config /\ names.id k = p := by + have self := M.self S + have none : forall k, k ∉ newE v1 none := by + intro k mem + obtain ⟨⟨_, e, _⟩, -⟩ := (M.mem_newE S).mp mem + cases e + cases sig with + | true => + obtain ⟨-, rfl⟩ := G.sigPlain rfl + simp only [addedOf, contentOf, absEntry, entryOf, ite_true, EntryContent.metadata, + CCF.Finset.notMem_empty, false_iff, not_exists, not_and] + exact fun k mem => absurd mem (none k) + | false => + cases config with + | none => + simp only [addedOf, contentOf, absEntry, entryOf, Bool.false_eq_true, ite_false, + EntryContent.metadata, Option.map_none, CCF.Finset.notMem_empty, false_iff, not_exists, + not_and] + exact fun k mem => absurd mem (none k) + | some nodes => + simp only [addedOf, contentOf, absEntry, entryOf, Bool.false_eq_true, ite_false, + EntryContent.metadata, Option.map_some, CCF.Finset.mem_erase, CCF.Finset.mem_sdiff, + Names.set, CCF.Finset.mem_ofList, List.mem_map] + constructor + · rintro ⟨ne, ⟨k, memK, rfl⟩, notEl⟩ + refine ⟨ + k, + (M.mem_newE S).mpr ⟨⟨nodes, rfl, List.mem_map.mpr memK⟩, ?_, ?_⟩, + rfl + ⟩ + · rintro rfl + exact ne self + · cases h : v1.peer? k with + | none => rfl + | some q => + refine absurd ((M.eligible _).mpr ⟨k, ?_, rfl⟩) notEl + exact peer_isSome_iff.mp (by rw [h]; rfl) + · rintro ⟨k, mem, rfl⟩ + have known := M.named_of_newE S G mem + obtain ⟨⟨nodes', e, memK⟩, ne, none⟩ := (M.mem_newE S).mp mem + cases e + refine ⟨fun e => ne (named_inj (named_of_known known) M.hy.selfNamed + (e.trans self.symm)), ⟨k, List.mem_map.mp memK, rfl⟩, fun el => ?_⟩ + obtain ⟨k', memK', e⟩ := (M.eligible _).mp el + obtain ⟨q, memQ⟩ := mem_keys.mp memK' + have := named_inj (M.hy.peersNamed _ memQ) (named_of_known known) e + subst this + have := peer_isSome_iff.mpr memK' + rw [none] at this + cases this + +theorem Mid.addedOf_sort {sig : Bool} {config : Option Nodes} {retired : List NodeId} + (G : Guards names v1 sig config retired) + : (addedOf cl1 node (contentOf names v1 sig config retired)).sort + = (newE v1 config).map names.id := by + refine CCF.Finset.eq_of_sorted_of_mem_iff (addedOf _ _ _).sorted ?_ fun p => ?_ + · cases h : newE v1 config with + | nil => exact List.Pairwise.nil + | cons k rest => + have mem : k ∈ newE v1 config := by rw [h]; exact List.mem_cons_self + obtain ⟨⟨nodes, hc, memK⟩, -, -⟩ := (M.mem_newE S).mp mem + have sorted := G.sorted (by + subst hc + intro e + rw [Option.getD_some, List.append_eq_nil_iff] at e + rw [e.1] at memK + cases memK) + rw [← h] + refine map_id_sorted sorted ?_ fun x m => M.named_of_newE S G m + exact ((sortDedup_spec _).1).filter _ + · rw [CCF.Finset.mem_sort, M.addedOf_iff S G, List.mem_map] + +end + +theorem Mid.hb_eq {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + (S : Start env.names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid env.names node v0 cl0 cl1 v1) (k : NodeId) + : hbClean node cl1 (env.names.id k) = hb env v1 k := by + unfold hbClean hb rangeRequest + rw [M.self S, M.cleanTerm S, M.cleanCommit S, M.cleanLog, + ReplUpdateCommit.abs_log_length M.hy.size, getTerm_vh (names := env.names) M.vh] + simp + +theorem Mid.msgInv_hb {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + (S : Start env.names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid env.names node v0 cl0 cl1 v1) {k : NodeId} (named : Named env.names k) + (ne : k ≠ v1.nodeId) + : msgInv env.names (hb env v1 k) = true := by + have := msgInv_range S M (to := k) + (fun e => ne (named_inj named M.hy.selfNamed (e.symm.trans (M.self S).symm))) + (Nat.le_refl _) (Nat.le_refl _) (Nat.le_refl _) fun i a b => absurd b (by omega) + unfold hb + rw [M.self S] + exact this + +/-! ## The appended declared state -/ + +theorem abs_log_push {u v : State} (e : Exec.Entry) (size : v.ledger.size = v.lastIdx) + (hl : u.ledger = v.ledger.push e) (hL : u.lastIdx = v.lastIdx + 1) + : (abs names u).log = (abs names v).log ++ [absEntry names e] := by + show (u.ledger.toList.take u.lastIdx).map _ + = (v.ledger.toList.take v.lastIdx).map _ ++ _ + rw [hl, hL, Array.toList_push, List.take_of_length_le (by simp [size]), + List.take_of_length_le (by simp [size]), List.map_append, List.map_singleton] + +theorem signaturesIn_push {u v : State} (e : Exec.Entry) + (size : v.ledger.size = v.lastIdx) (hl : u.ledger = v.ledger.push e) {c : Nat} + (hc : c <= v.lastIdx) + : signaturesIn u c (v.lastIdx + 1) + = signaturesIn v c v.lastIdx ++ (if e.sig then [v.lastIdx + 1] else []) := by + unfold signaturesIn + rw [show v.lastIdx + 1 - c = (v.lastIdx - c) + 1 by omega, List.range'_concat, + List.filter_append] + congr 1 + · refine List.filter_congr fun i mem => ?_ + rw [List.mem_range'_1] at mem + rw [hl, Array.getElem?_push_lt (by omega), Array.getElem?_eq_getElem (by omega)] + · rw [hl, Nat.one_mul, show c + 1 + (v.lastIdx - c) = v.lastIdx + 1 by omega] + cases h : e.sig <;> simp [Array.getElem?_push, size, h] + +theorem viewAt_ext {u v : State} {n L : Nat} + (hv : u.views = v.views ++ Array.replicate n (L + 1)) {i : Nat} (hi : i <= L) + : u.viewAt i = v.viewAt i := by + unfold State.viewAt + rw [hv, Array.toList_append, List.filter_append, Array.toList_replicate, List.length_append] + simp only [List.filter_replicate, show ¬ (L + 1 <= i) by omega, decide_false, Bool.false_eq_true, + ite_false, List.length_nil, Nat.add_zero] + +theorem viewAt_ext_last {u v : State} {n L : Nat} + (hv : u.views = v.views ++ Array.replicate n (L + 1)) + (le : forall x, x ∈ v.views.toList -> x <= L + 1) + : u.viewAt (L + 1) = v.views.size + n := by + unfold State.viewAt + rw [hv, Array.toList_append, List.filter_append, Array.toList_replicate, List.length_append, + List.filter_eq_self.mpr fun x m => decide_eq_true (le x m)] + simp + +theorem latest_active {log : List Consensus.Model.Node.Entry} {c : Nat} {n : NodeID} + (mem : n ∈ latestConfigurationMembers (configurationHistory log)) + : n ∈ configurationMembers (activeConfigurations log c) := by + unfold latestConfigurationMembers at mem + cases h : (configurationHistory log).getLast? with + | none => simp [h, CCF.Finset.notMem_empty] at mem + | some x => + simp only [h, Option.map_some, Option.getD_some] at mem + refine Repl.mem_members_iff.mpr ⟨x, ?_, mem⟩ + unfold activeConfigurations + dsimp only + have len := List.length_filter_le (fun c' : Configuration => decide (c'.index <= c)) + (configurationHistory log) + have pos : 0 < (configurationHistory log).length := by + cases e : configurationHistory log with + | nil => rw [e] at h; cases h + | cons _ _ => simp + apply List.mem_of_getLast? (l := (configurationHistory log).drop _) + rw [List.getLast?_drop, h] + simp only [show ¬ ((configurationHistory log).length + <= ((configurationHistory log).filter fun c' => decide (c'.index <= c)).length - 1) by omega, + ite_false] + +theorem Start.viewPos (S : Start names node v0 cl0) : 0 < v0.currentView := by + have invS := S.inv + have vz : (v0.currentView != 0 + || (v0.lastIdx == 0 && v0.leadership != .leader && v0.leadership != .candidate)) = true := by + inv_conj invS "view_zero" + simp only [S.leader, bne_self_eq_false, Bool.and_false, Bool.false_and, Bool.or_false, + bne_iff_ne, ne_eq] at vz + omega + +theorem shifted_append {c : Nat} {D E : List Config} (h : ReplUpdateCommit.Shifted c D E) + (X : List Config) + : ReplUpdateCommit.Shifted c (D ++ X) (E ++ X) := by + rcases h with rfl | ⟨x, y, rest, rfl, rfl, n, i, j⟩ + · exact Or.inl rfl + · exact Or.inr ⟨x, y, rest ++ X, rfl, rfl, n, i, j⟩ + +theorem cfgs_abs {v : State} {sig : Bool} {config : Option Nodes} {retired : List NodeId} + (plain : sig = true -> config = none) + : entryConfig (absEntry names (entryOf v sig config retired)) (v.lastIdx + 1) + = (cfgsOf v config).map (absConfig names) := by + cases sig with + | true => + rw [plain rfl] + simp [entryConfig, absEntry, entryOf, cfgsOf, EntryContent.metadata] + | false => + cases config <;> simp [entryConfig, absEntry, entryOf, cfgsOf, EntryContent.metadata, absConfig] + +section +variable (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) +include S M + +/-- The appended declared state satisfies `Hyps` and `ViewHyps`. -/ +theorem Mid.push_hyps {sig : Bool} {config : Option Nodes} {retired : List NodeId} + (G : Guards names v1 sig config retired) {R : List (Nat × List NodeId)} {w : State} + (hw : Hooked v1 (if sig then [v1.lastIdx + 1] else []) (cfgsOf v1 config) R w) + (named : forall p, p ∈ w.allOtherNodes -> Named names p.1) + : Hyps names (pushed v1 w (entryOf v1 sig config retired)) + /\ ViewHyps (pushed v1 w (entryOf v1 sig config retired)) := by + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := hw + have hy := M.hy + have vh := M.vh + have cv : 0 < v1.currentView := M.frame.view ▸ S.viewPos + generalize he : entryOf v1 sig config retired = e + have eTerm : e.term = v1.currentView := by rw [← he]; rfl + have eSig : e.sig = sig := by rw [← he]; rfl + have hl : (pushed v1 { v1 with + committable := v1.committable ++ (if sig then [v1.lastIdx + 1] else []), + configurations := v1.configurations ++ cfgsOf v1 config, allOtherNodes := ps, + rcEntries := v1.rcEntries ++ R, ticking := tk, retired := r, retirementPhase := ph, retirementIdx := ri, + retirementCommittableIdx := rci } e).ledger = v1.ledger.push e := rfl + generalize hP : pushed v1 { v1 with + committable := v1.committable ++ (if sig then [v1.lastIdx + 1] else []), + configurations := v1.configurations ++ cfgsOf v1 config, allOtherNodes := ps, + rcEntries := v1.rcEntries ++ R, ticking := tk, retired := r, retirementPhase := ph, retirementIdx := ri, + retirementCommittableIdx := rci } e = P at hl named + have hL : P.lastIdx = v1.lastIdx + 1 := by rw [← hP]; rfl + have hv : P.views = v1.views ++ Array.replicate (v1.currentView - v1.views.size) + (v1.lastIdx + 1) := by rw [← hP]; rfl + have hcv : P.currentView = v1.currentView := by rw [← hP]; rfl + have hc : P.commitIdx = v1.commitIdx := by rw [← hP]; rfl + have hcom : P.committable = v1.committable ++ (if sig then [v1.lastIdx + 1] else []) := by + rw [← hP]; rfl + have hcfg : P.configurations = v1.configurations ++ cfgsOf v1 config := by rw [← hP]; rfl + have hid : P.nodeId = v1.nodeId := by rw [← hP]; rfl + have hps : P.allOtherNodes = ps := by rw [← hP]; rfl + have size : P.ledger.size = P.lastIdx := by rw [hl, hL, Array.size_push, hy.size] + have leLast := vh.leLast + have terms : forall i, 1 <= i -> i <= P.lastIdx + -> P.ledger[i - 1]?.map (·.term) = some (P.viewAt i) := by + intro i i1 iL + rw [hL] at iL + rcases Nat.lt_or_ge i (v1.lastIdx + 1) with lt | ge + · rw [hl, Array.getElem?_push_lt (by rw [hy.size]; omega), ← Array.getElem?_eq_getElem, + viewAt_ext hv (by omega)] + exact hy.terms i i1 (by omega) + · rw [show i = v1.lastIdx + 1 by omega, viewAt_ext_last hv leLast, hl, Nat.add_sub_cancel, + Array.getElem?_push] + simp only [hy.size, ite_true, Option.map_some, eTerm, Option.some.injEq] + have := hy.viewsBounded + omega + have vsize : P.views.size <= P.currentView := by + rw [hv, hcv, Array.size_append, Array.size_replicate] + have := hy.viewsBounded + omega + have hlog : (abs names P).log = (abs names v1).log ++ [absEntry names e] := + abs_log_push e hy.size hl hL + have len1 : (abs names v1).log.length = v1.lastIdx := ReplUpdateCommit.abs_log_length hy.size + refine ⟨ + ⟨ + size, + by rw [hc, hL]; have := hy.commitLe; omega, + ?_, + terms, + vsize, + ?_, + ?_, + ?_, + ?_, + ?_ + ⟩, + ⟨size, ?_, ?_, ?_, terms, ?_⟩ + ⟩ + · rw [hcom, hc, hL, signaturesIn_push e hy.size hl hy.commitLe, ← hy.committable, eSig] + · intro _ + rw [hlog, hc, active_snoc _ _ (by rw [len1]; exact hy.commitLe), len1, ← he, + cfgs_abs fun s => (G.sigPlain s).2, hcfg] + by_cases z : v1.lastIdx = 0 + · have nil : (abs names v1).log = [] := List.eq_nil_of_length_eq_zero (len1.trans z) + rw [nil, M.unconf z] + exact ⟨cfgsOf v1 config, by simp [activeConfigurations, configurationHistory], Or.inl rfl⟩ + · obtain ⟨D, hD, sh⟩ := hy.configs (Nat.pos_of_ne_zero z) + exact ⟨D ++ cfgsOf v1 config, by rw [hD, List.map_append], shifted_append sh _⟩ + · rw [hid]; exact hy.selfNamed + · rw [hps]; exact named + · rw [hcfg] + intro x mem a ma + rcases List.mem_append.mp mem with mem | mem + · exact hy.membersNamed x mem a ma + · cases hcf : config with + | none => simp [cfgsOf, hcf] at mem + | some nodes => + simp only [cfgsOf, hcf, Option.map_some, Option.toList_some, + List.mem_singleton] at mem + subst mem + exact named_of_known + (G.known a.1 + (List.mem_append_left _ + (by + simp only [hcf, Option.getD_some, List.mem_map] + exact ⟨a, ma, rfl⟩))) + · rw [hcfg] + intro x mem + rcases List.mem_append.mp mem with mem | mem + · exact hy.distinct x mem + · cases hcf : config with + | none => simp [cfgsOf, hcf] at mem + | some nodes => + simp only [cfgsOf, hcf, Option.map_some, Option.toList_some, + List.mem_singleton] at mem + subst mem + exact (G.cfg nodes hcf).1 + · rw [hv, Array.toList_append, Array.toList_replicate, List.pairwise_append] + refine ⟨vh.sorted, List.pairwise_replicate.mpr (Or.inr (Nat.le_refl _)), fun a ma b mb => ?_⟩ + rw [(List.eq_of_mem_replicate mb)] + exact leLast a ma + · intro x mem + rw [hv, Array.toList_append, Array.toList_replicate, List.mem_append] at mem + rcases mem with mem | mem + · exact vh.positive x mem + · rw [List.eq_of_mem_replicate mem]; omega + · intro x mem + rw [hL] + rw [hv, Array.toList_append, Array.toList_replicate, List.mem_append] at mem + rcases mem with mem | mem + · have := leLast x mem; omega + · rw [List.eq_of_mem_replicate mem]; omega + · intro x mem + rw [hl, Array.toList_push, List.mem_append, List.mem_singleton] at mem + rcases mem with mem | rfl + · exact vh.posTerms x mem + · rw [eTerm]; exact cv + +end + +theorem Mid.entryOk (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) {sig : Bool} {config : Option Nodes} + {retired : List NodeId} (G : Guards names v1 sig config retired) + : EntryOk cl1 (contentOf names v1 sig config retired) := by + have hlog := M.cleanLog + have hcomm : cl1.committedLog = (abs names v1).committedLog := by + unfold NodeState.committedLog + rw [hlog, M.cleanCommit S] + rfl + have rcn : cl1.retirementCompletedNodes = (abs names v1).retirementCompletedNodes := by + unfold NodeState.retirementCompletedNodes + rw [hcomm] + refine ⟨fun h e => ?_, fun ne => ?_, fun nodes h => ?_⟩ + · cases sig with + | false => simp [contentOf, absEntry, entryOf, EntryContent.isSignature] at h + | true => + rw [hlog] at e + have := congrArg List.length e + rw [ReplUpdateCommit.abs_log_length M.hy.size] at this + exact G.sigNonempty rfl this + · cases sig with + | true => + obtain ⟨a, mem⟩ := ne + simp [contentOf, absEntry, entryOf, EntryContent.metadata] at mem + | false => + simp only [contentOf, absEntry, entryOf, Bool.false_eq_true, ite_false, + EntryContent.metadata] at ne ⊢ + rw [rcn, hlog] + refine G.rc fun e => ?_ + obtain ⟨a, mem⟩ := ne + rw [e] at mem + simp [Names.set] at mem + · cases sig with + | true => simp [contentOf, absEntry, entryOf, EntryContent.metadata] at h + | false => + cases config with + | none => simp [contentOf, absEntry, entryOf, EntryContent.metadata] at h + | some ns => + simp only [contentOf, absEntry, entryOf, Bool.false_eq_true, ite_false, + EntryContent.metadata, Option.map_some, Option.some.injEq] at h + subst h + obtain ⟨-, ne, latest, back⟩ := G.cfg ns rfl + refine ⟨?_, by rw [hlog]; exact latest, fun x mem => ?_⟩ + · obtain ⟨a, rest, rfl⟩ := List.exists_cons_of_ne_nil ne + exact ⟨names.id a.1, by simp [Names.set]⟩ + · simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] at mem + obtain ⟨_, ⟨a, ma, rfl⟩, rfl⟩ := mem + rw [hlog] + exact back a ma + +theorem contentOf_cfg {v : State} {sig : Bool} {config : Option Nodes} + {retired : List NodeId} (plain : sig = true -> config = none) + : (contentOf names v sig config retired).metadata.configuration + = config.map fun ns => names.set (ns.map Prod.fst) := by + cases sig with + | false => simp [contentOf, absEntry, entryOf, EntryContent.metadata] + | true => + rw [plain rfl] + simp [contentOf, absEntry, entryOf, EntryContent.metadata] + +theorem removed_snoc (log : List Model.Node.Entry) (x : Model.Node.Entry) + (h + : forall ns, + x.content.metadata.configuration = some ns + -> forall n, n ∈ ns -> n ∉ removedNodes log) + : forall n, n ∈ removedNodes log -> n ∈ removedNodes (log ++ [x]) := by + intro n mem + unfold removedNodes at mem ⊢ + dsimp only at mem ⊢ + rw [history_snoc] + cases hc : x.content.metadata.configuration with + | none => simpa [entryConfig, hc] using mem + | some ns => + have notIn := h ns hc n + simp only [entryConfig, hc, Option.map_some, Option.toList_some] + obtain ⟨m1, -⟩ := CCF.Finset.mem_sdiff.mp mem + refine CCF.Finset.mem_sdiff.mpr ⟨(members_append _ _).mpr (Or.inl m1), ?_⟩ + simp only [latestConfigurationMembers, List.getLast?_append, List.getLast?_singleton, + Option.some_or, Option.map_some, Option.getD_some] + exact fun m => notIn m mem + +/-- The batch keeps the committed log, so the retirement-completed nodes. -/ +theorem Mid.rcnEq (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) + : (abs names v1).retirementCompletedNodes + = (abs names v0).retirementCompletedNodes := by + have hy0 := (Mid.start S).hy + have len0 := ReplUpdateCommit.abs_log_length (names := names) hy0.size + have hc : (abs names v1).committedLog = (abs names v0).committedLog := by + unfold NodeState.committedLog + obtain ⟨t, ht⟩ := M.isPrefix + rw [S.log] at ht + show (abs names v1).log.take v1.commitIdx = (abs names v0).log.take v0.commitIdx + rw [← ht, M.frame.commit, List.take_append_of_le_length (by rw [len0]; exact hy0.commitLe)] + unfold NodeState.retirementCompletedNodes + rw [hc] + +/-- The nodes a hook confirms were removed before the batch. -/ +theorem Mid.retiredRemoved (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) {sig : Bool} {config : Option Nodes} + {retired : List NodeId} (G : Guards names v1 sig config retired) + : forall id, id ∈ retired -> names.id id ∈ removedNodes (abs names v0).log := by + intro id mem + have ne : retired ≠ [] := by rintro rfl; cases mem + have h := G.rc ne (by simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map]; exact ⟨id, mem, rfl⟩) + rw [M.rcnEq S] at h + have e : (v0.leadership != .leader + || decide ((abs names v0).retirementCompletedNodes ⊆ removedNodes (abs names v0).log)) + = true := by + inv_conj S.inv "retirement_completed_removed" + simp only [S.leader, bne_self_eq_false, Bool.false_or, decide_eq_true_eq] at e + exact e (CCF.Finset.mem_sdiff.mp h).1 + +/-- Appending the entry keeps the batch relation. -/ +theorem Mid.push (S : Start names node v0 cl0) {cl1 : NodeState} {v1 : State} + (M : Mid names node v0 cl0 cl1 v1) {sig : Bool} {config : Option Nodes} + {retired : List NodeId} (G : Guards names v1 sig config retired) {w : State} + (hw + : Hooked v1 (if sig then [v1.lastIdx + 1] else []) (cfgsOf v1 config) + (rcsOf v1 retired) w) + (rcw : w.isRetiredCommitted = false) + (added : Added v1 (newE v1 config) w.allOtherNodes) + : Mid names node v0 cl0 (appended node cl1 (contentOf names v1 sig config retired)) + (pushed v1 w (entryOf v1 sig config retired)) := by + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := hw + have self := M.self S + obtain ⟨f, hcl, PR⟩ := M.clean + have namedK : forall k, k ∈ newE v1 config -> Named names k := + fun k m => named_of_known (M.named_of_newE S G m) + have v1peerNamed : forall k p, v1.peer? k = some p -> Named names k := fun k p h => + M.hy.peersNamed (k, p) ((lookup_iff_mem PR.nodup).mp h) + have named : forall p, p ∈ ps -> Named names p.1 := by + intro ⟨k, q⟩ mem + have h := (lookup_iff_mem added.1).mpr mem + rw [added.2 k] at h + split at h + · exact namedK k ‹_› + · exact v1peerNamed k q h + obtain ⟨hy, vh⟩ := M.push_hyps S G ⟨tk, r, ph, ri, rci, ps, rfl⟩ named + have hlog := abs_log_push (names := names) (u := pushed v1 { v1 with + committable := v1.committable ++ (if sig then [v1.lastIdx + 1] else []), + configurations := v1.configurations ++ cfgsOf v1 config, allOtherNodes := ps, + rcEntries := v1.rcEntries ++ rcsOf v1 retired, ticking := tk, retired := r, retirementPhase := ph, retirementIdx := ri, + retirementCommittableIdx := rci } (entryOf v1 sig config retired)) + (entryOf v1 sig config retired) M.hy.size rfl rfl + have len1 := ReplUpdateCommit.abs_log_length (names := names) M.hy.size + have commitLe : cl1.commitIndex <= cl1.log.length := by + rw [M.cleanCommit S, M.cleanLog, len1]; exact M.hy.commitLe + have keysIff : forall k, k ∈ ps.map Prod.fst + <-> k ∈ newE v1 config \/ k ∈ v1.allOtherNodes.map Prod.fst := by + intro k + rw [← peer_isSome_iff (v := { v1 with allOtherNodes := ps }), ← peer_isSome_iff] + show (ps.lookup k).isSome = true <-> _ + rw [added.2 k] + by_cases m : k ∈ newE v1 config <;> simp [m] + have cfg := contentOf_cfg (names := names) (v := v1) (retired := retired) + fun s => (G.sigPlain s).2 + refine ⟨ + by frame_step M.frame, + rcw, + hy, + vh, + fun h => absurd h (Nat.succ_ne_zero _), + ?_, + ?_, + ?_, + ?_, + ?_, + ?_, + ?_, + ?_ + ⟩ + · intro x mem id hid + change x ∈ (v1.ledger.push (entryOf v1 sig config retired)).toList at mem + rw [Array.toList_push, List.mem_append, List.mem_singleton] at mem + rcases mem with mem | rfl + · exact M.ledgerNamed x mem id hid + · exact named_of_known (G.known id hid) + · subst hcl + refine ⟨fun p => if p ∈ addedOf { cl0 with log := (abs names v1).log, sentIndex := f } node + (contentOf names v1 sig config retired) then (abs names v1).log.length else f p, ?_, + added.1, fun k p hp => ?_⟩ + · rw [hlog] + have ht : cl0.currentTerm = v1.currentView := M.cleanTerm S + unfold appended + dsimp only + rw [ht] + rfl + · change ps.lookup k = some p at hp + rw [added.2 k] at hp + split at hp + · rename_i mem + cases hp + have inA := (M.addedOf_iff S G).mpr ⟨k, mem, rfl⟩ + refine ⟨by simp [inA, len1], Nat.le_succ _, ?_⟩ + obtain ⟨⟨nodes, hc, memK⟩, neK, noneK⟩ := (M.mem_newE S).mp mem + have ne : names.id k ≠ node := fun e => + neK (named_inj (namedK k mem) M.hy.selfNamed (e.trans self.symm)) + refine S.um S.role (names.id k) ne fun inMem => ?_ + have h1 := members_prefix M.isPrefix inMem + obtain ⟨-, -, -, back⟩ := G.cfg nodes hc + obtain ⟨a, ma, rfl⟩ := List.mem_map.mp memK + have lat : names.id a.1 + ∈ latestConfigurationMembers (configurationHistory (abs names v1).log) := + Classical.byContradiction fun nl => back a ma (CCF.Finset.mem_sdiff.mpr ⟨h1, nl⟩) + have el : names.id a.1 ∈ eligiblePeers + { cl0 with log := (abs names v1).log, sentIndex := f } node := + CCF.Finset.mem_erase.mpr ⟨ne, CCF.Finset.mem_union.mpr (Or.inl (latest_active lat))⟩ + obtain ⟨k', memk', e⟩ := (M.eligible _).mp el + obtain ⟨q, memQ⟩ := mem_keys.mp memk' + have := named_inj (M.hy.peersNamed _ memQ) (namedK _ mem) e + subst this + have := peer_isSome_iff.mpr memk' + rw [noneK] at this + cases this + · rename_i notMem + obtain ⟨h1, h2, h3⟩ := PR.rel k p hp + have notIn : names.id k ∉ addedOf { cl0 with log := (abs names v1).log, sentIndex := f } + node (contentOf names v1 sig config retired) := by + intro inA + obtain ⟨k', m', e⟩ := (M.addedOf_iff S G).mp inA + have := named_inj (namedK k' m') (v1peerNamed k p hp) e + subst this + exact notMem m' + simp only [notIn, ↓reduceIte] + exact ⟨h1, Nat.le_succ_of_le h2, h3⟩ + · intro n + rw [Ae.eligiblePeers_congr (a := appended node cl1 (contentOf names v1 sig config retired)) + (b := { cl1 with + log := cl1.log ++ [{ term := cl1.currentTerm, content := contentOf names v1 sig config retired }] }) + rfl rfl, eligible_snoc _ commitLe node n, M.eligible n, cfg] + constructor + · rintro (⟨k, mk, rfl⟩ | ⟨ne, nodes, hc, mn⟩) + · exact ⟨k, (keysIff k).mpr (Or.inr mk), rfl⟩ + · obtain ⟨ns, rfl, rfl⟩ := Option.map_eq_some_iff.mp hc + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] at mn + obtain ⟨_, ⟨a, ma, rfl⟩, rfl⟩ := mn + refine ⟨a.1, (keysIff _).mpr ?_, rfl⟩ + cases hp : v1.peer? a.1 with + | some q => exact Or.inr (peer_isSome_iff.mp (by rw [hp]; rfl)) + | none => + refine Or.inl ((M.mem_newE S).mpr ⟨⟨ns, rfl, List.mem_map.mpr ⟨a, ma, rfl⟩⟩, + fun e => ne ?_, hp⟩) + rw [e, self] + · rintro ⟨k, mk, rfl⟩ + rcases (keysIff k).mp mk with m | m + · obtain ⟨⟨ns, hc, memK⟩, neK, -⟩ := (M.mem_newE S).mp m + refine Or.inr ⟨fun e => neK (named_inj (namedK k m) M.hy.selfNamed (e.trans self.symm)), + _, by rw [hc]; rfl, ?_⟩ + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] + exact ⟨k, List.mem_map.mp memK, rfl⟩ + · exact Or.inl ⟨k, m, rfl⟩ + · rw [hlog] + exact M.isPrefix.trans (List.prefix_append _ _) + · intro x mem id hid + rcases List.mem_append.mp mem with mem | mem + · exact M.rcRemoved x mem id hid + · cases hr : retired.isEmpty with + | true => simp [rcsOf, hr] at mem + | false => + simp only [rcsOf, hr, Bool.false_eq_true, ite_false, List.mem_singleton] at mem + subst mem + exact M.retiredRemoved S G id hid + · intro j x cj hx n mem + rw [hlog] at hx + rcases Nat.lt_or_ge j (abs names v1).log.length with lt | ge + · rw [List.getElem?_append_left lt] at hx + exact M.confRemoved j x cj hx n mem + · rw [List.getElem?_append_right ge] at hx + have z : j - (abs names v1).log.length = 0 := by + have := (List.getElem?_eq_some_iff.mp hx).1 + simp only [List.length_singleton] at this + omega + simp only [z, List.getElem?_singleton, ↓reduceIte, Option.some.injEq] at hx + subst hx + cases sig with + | true => + simp [absEntry, entryOf, EntryContent.metadata, CCF.Finset.notMem_empty] at mem + | false => + simp only [absEntry, entryOf, Bool.false_eq_true, ite_false, EntryContent.metadata, + Names.set, CCF.Finset.mem_ofList, List.mem_map] at mem + obtain ⟨id, mid, rfl⟩ := mem + exact M.retiredRemoved S G id mid + · intro n mem + rw [hlog] + refine removed_snoc _ _ (fun ns hns m mn => ?_) n (M.removedMono n mem) + change (contentOf names v1 sig config retired).metadata.configuration = some ns at hns + rw [cfg] at hns + obtain ⟨nodes, hc, rfl⟩ := Option.map_eq_some_iff.mp hns + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] at mn + obtain ⟨_, ⟨a, ma, rfl⟩, rfl⟩ := mn + exact (G.cfg nodes hc).2.2.2 a ma + · obtain ⟨new, hn, hnew⟩ := M.cfgNew + refine ⟨new ++ cfgsOf v1 config, ?_, fun c mc a ma => ?_⟩ + · show v1.configurations ++ cfgsOf v1 config = _ + rw [hn, List.append_assoc] + · rcases List.mem_append.mp mc with mc | mc + · exact hnew c mc a ma + · rcases config with _ | nodes + · simp [cfgsOf] at mc + · simp only [cfgsOf, Option.map_some, Option.toList_some, List.mem_singleton] at mc + subst mc + exact fun r => (G.cfg nodes rfl).2.2.2 a ma (M.removedMono _ r) + +/-- Appending the entry extends the ghost by one clean entry and the added peers' heartbeats. -/ +theorem push_ghost {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + (S : Start env.names node v0 cl0) {es : List AppendEntryInput} {v1 : State} + {o1 : Outbox} (g : Ghost env node v0 cl0 es v1 o1) {sig : Bool} + {config : Option Nodes} {retired : List NodeId} + (G : Guards env.names v1 sig config retired) {w : State} + (hw + : Hooked v1 (if sig then [v1.lastIdx + 1] else []) (cfgsOf v1 config) + (rcsOf v1 retired) w) + (rcw : w.isRetiredCommitted = false) + (added : Added v1 (newE v1 config) w.allOtherNodes) + : Ghost env node v0 cl0 + (es + ++ [({ content := contentOf env.names v1 sig config retired, flushes := [] } + : AppendEntryInput)]) + (pushed v1 w (entryOf v1 sig config retired)) + (o1 ++ (newE v1 config).map (hb env v1)) := by + obtain ⟨cl1, em, M, mi⟩ := g + refine ⟨_, ?_, M.push S G hw rcw added, fun x mem => ?_⟩ + · rw [List.foldlM_append] + refine emits_bind em ?_ + simp only [List.foldlM_cons, List.foldlM_nil, entryStep] + refine emits_congr (emits_bind (emits_bind (emits_appendEntry (M.entryOk S G)) + (emits_pure _)) (emits_pure _)) rfl ?_ + simp only [List.append_nil, M.addedOf_sort S G, List.map_map] + exact List.map_congr_left fun k _ => M.hb_eq S k + · rcases List.mem_append.mp mem with mem | mem + · exact mi x mem + · obtain ⟨k, mk, rfl⟩ := List.mem_map.mp mem + exact M.msgInv_hb S (named_of_known (M.named_of_newE S G mk)) ((M.mem_newE S).mp mk).2.1 + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplBatch.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplBatch.lean new file mode 100644 index 000000000000..d844f01d9acd --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplBatch.lean @@ -0,0 +1,119 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplFlush +public import Consensus.TraceValidation.Proofs.Handlers.ReplPeerSend + +@[expose] public section + +/-! +# The clean batch alongside a hold (not reviewed; `Replicate` obligation) + +`Ghost env node v0 cl0 es v o`: the clean entries `es`, appended and flushed as +`appendBatch` does, run from `cl0` and emit exactly the outbox `o`, into a clean state that +`Mid` relates to the declared state `v`. A range a flush sends extends the last entry's +flushes. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees inv msgInv UnnamedUnmatched) + +/-- One entry of `appendBatch`: append it, then send its flushes. -/ +def entryStep (node : NodeID) (state : NodeState) (entry : AppendEntryInput) + : NodeEffect NodeState := do + let state <- appendEntry (CCF.Capabilities.record node) node state entry.content + entry.flushes.foldlM + (fun state (destination, endIndex) => + sendEntries (CCF.Capabilities.record node) node state destination endIndex) + state + +def Ghost (env : Env) (node : NodeID) (v0 : State) (cl0 : NodeState) + (es : List AppendEntryInput) (v : State) (o : Outbox) + : Prop := + exists cl, + Emits (es.foldlM (entryStep node) cl0) cl o + /\ Mid env.names node v0 cl0 cl v + /\ forall x, x ∈ o -> msgInv env.names x = true + +theorem foldl_flush (node : NodeID) (cl0 : NodeState) (es : List AppendEntryInput) + (c : EntryContent) (fl : List (NodeID × Nat)) (x : NodeID × Nat) + : (es ++ [({ content := c, flushes := fl ++ [x] } : AppendEntryInput)]).foldlM + (entryStep node) cl0 + = (es ++ [({ content := c, flushes := fl } : AppendEntryInput)]).foldlM + (entryStep node) cl0 + >>= fun s => sendEntries (CCF.Capabilities.record node) node s x.1 x.2 := by + simp [List.foldlM_append, entryStep, bind_assoc] + +variable {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + +theorem Ghost.base {es : List AppendEntryInput} {v : State} {o : Outbox} + (g : Ghost env node v0 cl0 es v o) + : ViewHyps v + /\ v.isRetiredCommitted = false + /\ (v.allOtherNodes.map Prod.fst).Nodup := by + obtain ⟨cl, -, M, -⟩ := g + obtain ⟨f, -, P⟩ := M.clean + exact ⟨M.vh, M.notRC, P.nodup⟩ + +theorem Ghost.bound {es : List AppendEntryInput} {v : State} {o : Outbox} + (g : Ghost env node v0 cl0 es v o) {k : NodeId} {p : Peer} + (found : v.peer? k = some p) + : p.sentIdx <= v.lastIdx := by + obtain ⟨cl, -, M, -⟩ := g + obtain ⟨f, -, P⟩ := M.clean + exact (P.rel k p found).2.1 + +/-- A range a flush sends extends the last entry's flushes. -/ +theorem Ghost.flush (S : Start env.names node v0 cl0) {es : List AppendEntryInput} + {c : EntryContent} {fl : List (NodeID × Nat)} {v : State} {o : Outbox} + (g + : Ghost env node v0 cl0 + (es ++ [({ content := c, flushes := fl } : AppendEntryInput)]) v o) + {to : NodeId} {p : Peer} (found : v.peer? to = some p) {e : Nat} (ok : RangeOk v p e) + : Ghost env node v0 cl0 + (es + ++ [({ content := c, flushes := fl ++ [(env.names.id to, e)] } + : AppendEntryInput)]) + (v.setPeer to { p with sentIdx := e }) (o ++ [rangeEnv env v to p e]) := by + obtain ⟨cl, em, M, mi⟩ := g + obtain ⟨em', M', mi'⟩ := range_step S M found ok.1 ok.2.1 ok.2.2 + have self := M.self S + refine ⟨_, ?_, M', ?_⟩ + · rw [foldl_flush] + refine emits_congr (emits_bind em em') rfl ?_ + simp only [rangeEnv, self] + · intro x mem + rcases List.mem_append.mp mem with mem | mem + · exact mi x mem + · simp only [List.mem_singleton] at mem + subst mem + simp only [rangeEnv, self] + exact mi' + +/-- A flush ghost: some entries, the last with some flushes. -/ +def FlushGhost (env : Env) (node : NodeID) (v0 : State) (cl0 : NodeState) (v : State) + (o : Outbox) + : Prop := + exists es c fl, + Ghost env node v0 cl0 (es ++ [({ content := c, flushes := fl } : AppendEntryInput)]) v + o + +open Consensus.TraceValidation.Proofs.Life in +/-- `send_append_entries` from a peer's send frontier during a flush keeps the flush ghost. -/ +theorem flushSend_tri (S : Start env.names node v0 cl0) {to : NodeId} {ext : Bool} + {start : Nat} + : Tri env + (fun v o => + FlushGhost env node v0 cl0 v o + /\ exists p, + v.peer? to = some p /\ start = p.sentIdx + 1 /\ p.sentIdx <= v.lastIdx) + (sendAppendEntries to start ext) fun _ => FlushGhost env node v0 cl0 := + peerSend_tri (fun _ _ ⟨_, _, _, g⟩ => g.base) + fun _ _ _ _ ⟨_, _, _, g⟩ found ok => ⟨_, _, _, g.flush S found ok⟩ + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplClean.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplClean.lean new file mode 100644 index 000000000000..919fcd7979a9 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplClean.lean @@ -0,0 +1,94 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplEmits +public import CCF.Proofs.Finset + +@[expose] public section + +/-! +# The clean `appendEntry` of an admissible entry + +What the clean primary does for one admissible entry: the peers a configuration adds get +heartbeats from the end of the log and the entry is appended. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open CCF (Finset) + +/-- The peers a content's configuration adds: its nodes that are neither eligible nor the node. -/ +def addedOf (cl : NodeState) (node : NodeID) (c : EntryContent) : Finset NodeID := + match c.metadata.configuration with + | none => ∅ + | some nodes => (nodes \ eligiblePeers cl node).erase node + +/-- The clean state after `appendEntry`. -/ +def appended (node : NodeID) (cl : NodeState) (c : EntryContent) : NodeState := + { + cl with + sentIndex := + fun p => if p ∈ addedOf cl node c then cl.log.length else cl.sentIndex p + log := cl.log ++ [{ term := cl.currentTerm, content := c }] + } + +/-- The heartbeat an added peer gets from the end of the log. -/ +def hbClean (node : NodeID) (cl : NodeState) (p : NodeID) : CCF.Envelope NodeID Message := + ⟨ + node, + p, + .appendEntriesRequest + { + term := cl.currentTerm, + prevLogIndex := cl.log.length + prevLogTerm := termAt cl.log cl.log.length, + entries := [] + primaryCommit := cl.commitIndex + } + ⟩ + +/-- `appendEntry`'s admission guards. -/ +structure EntryOk (cl : NodeState) (c : EntryContent) : Prop where + sig : c.isSignature = true -> Not (cl.log = []) + rc + : c.metadata.retirementConfirmations.Nonempty + -> c.metadata.retirementConfirmations + ⊆ cl.retirementCompletedNodes \ retiredCommittedNodes cl.log + cfg + : forall nodes, + c.metadata.configuration = some nodes + -> nodes.Nonempty + /\ Not (nodes = latestConfigurationMembers (configurationHistory cl.log)) + /\ Finset.Disjoint nodes (removedNodes cl.log) + +variable {node : NodeID} + +theorem emits_appendEntry {cl : NodeState} {c : EntryContent} (ok : EntryOk cl c) + : Emits (appendEntry (CCF.Capabilities.record node) node cl c) (appended node cl c) + ((addedOf cl node c).sort.map (hbClean node cl)) := by + unfold appendEntry + dsimp only + refine emits_ite_guard_bind ok.sig ?_ + refine emits_ite_guard_bind ok.rc ?_ + cases hc : c.metadata.configuration with + | none => + refine emits_congr (emits_bind (emits_pure _) (emits_pure _)) ?_ ?_ + · simp only [appended, addedOf, hc, CCF.Finset.notMem_empty, ite_false] + · simp only [addedOf, hc] + rfl + | some nodes => + dsimp only + refine emits_congr (emits_bind (emits_guard (ok.cfg nodes hc)) + (emits_bind (emits_forIn_send _ _) (emits_pure _))) ?_ ?_ + · simp only [appended, addedOf, hc] + · simp only [List.nil_append, List.append_nil, addedOf, hc] + apply List.map_congr_left + intro peer member + simp only [CCF.Finset.mem_sort] at member + simp only [hbClean, makeAppendEntriesRequest, member, ite_true, messageEntries, + Nat.sub_self, List.take_zero] + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCommit.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCommit.lean new file mode 100644 index 000000000000..ea90fabf7c1d --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCommit.lean @@ -0,0 +1,459 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplEntry +public import Consensus.TraceValidation.Proofs.Handlers.AppendEntriesResponse + +@[expose] public section + +/-! +# After the batch: the commit (not reviewed; `Replicate` obligation) + +The clean `appendBatch` ends with `advanceCommit`. With other nodes in the active +configurations before the batch, it cannot move (`hc_stuck`): the new entries are above every +peer's match index, and the commit index was already maximal. Without them, the declared +`update_commit` runs, and it chooses the clean `highestCommittableIndex` (`updateCommit_tri`). +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open CCF (Finset) + +/-! ## The clean commit -/ + +variable {node : NodeID} + +theorem emits_advance (st : NodeState) (primary : st.role = .primary) + : Emits (advanceCommit (CCF.Capabilities.record node) st node) + (if highestCommittableIndex st node <= st.commitIndex then + st + else + st.recordCommit node (highestCommittableIndex st node)) + (if ¬ highestCommittableIndex st node <= st.commitIndex + /\ (st.recordCommit node (highestCommittableIndex st node)).isRetiredCommitted + node then + AeResp.nomSends node st + else + []) := by + unfold advanceCommit + by_cases h : highestCommittableIndex st node <= st.commitIndex + · simp only [h, ↓reduceIte, not_true_eq_false, false_and] + exact emits_pure _ + · by_cases r : + (st.recordCommit node (highestCommittableIndex st node)).isRetiredCommitted node + · simp only [h, ↓reduceIte, primary, not_false_eq_true, true_and] + rw [ite_eq_left_of_eq_true _ _ (eq_true r), ite_eq_left_of_eq_true _ _ (eq_true r)] + refine emits_congr + (emits_bind (a := st) + (b := st.recordCommit node (highestCommittableIndex st node)) (later := []) ?_ + (emits_pure _)) + rfl (List.append_nil _) + unfold nominateSuccessor + refine emits_congr (emits_bind (emits_guard primary) ?_) rfl (List.nil_append _) + unfold AeResp.nomSends + cases findSuccessor st node with + | none => exact emits_pure _ + | some t => + exact emits_congr (emits_bind (emits_send _ _) (emits_pure _)) rfl rfl + · simp only [h, ↓reduceIte, not_false_eq_true, true_and] + rw [ite_eq_right_of_eq_false _ _ (eq_false r), ite_eq_right_of_eq_false _ _ (eq_false r)] + exact emits_pure _ + +/-! ## Folds that stay put -/ + +theorem foldl_ge {g : Nat -> Nat -> Nat} (mono : forall a x, a <= g a x) + : forall (l : List Nat) (a : Nat), a <= l.foldl g a + | [], _ => Nat.le_refl _ + | x :: l, a => Nat.le_trans (mono a x) (foldl_ge mono l (g a x)) + +theorem foldl_fixed {g : Nat -> Nat -> Nat} (mono : forall a x, a <= g a x) + : forall (l : List Nat) (a : Nat), l.foldl g a <= a -> forall x, x ∈ l -> g a x = a + | [], _, _, _, mem => absurd mem List.not_mem_nil + | y :: l, a, h, x, mem => by + have hy : g a y = a := + Nat.le_antisymm (Nat.le_trans (foldl_ge mono l (g a y)) h) (mono a y) + rcases List.mem_cons.mp mem with rfl | mem + · exact hy + · simp only [List.foldl_cons, hy] at h + exact foldl_fixed mono l a h x mem + +theorem foldl_const {g : Nat -> Nat -> Nat} + : forall (l : List Nat) (a : Nat), (forall x, x ∈ l -> g a x = a) -> l.foldl g a = a + | [], _, _ => rfl + | y :: l, a, h => by + simp only [List.foldl_cons, h y List.mem_cons_self] + exact foldl_const l a fun x mem => h x (List.mem_cons_of_mem _ mem) + +theorem le_ite_self {p : Prop} [Decidable p] {a x : Nat} (h : p -> a <= x) + : a <= if p then x else a := by + by_cases c : p + · simp only [c, ↓reduceIte] + exact h c + · simp only [c, ↓reduceIte, Nat.le_refl] + +/-! ## The clean commit cannot move past a batch with other nodes -/ + +theorem history_append (L0 T : List Model.Node.Entry) + : exists R, + configurationHistory (L0 ++ T) = configurationHistory L0 ++ R + /\ forall c, c ∈ R -> L0.length < c.index := by + unfold configurationHistory + rw [List.zipIdx_append, List.filterMap_append] + refine ⟨_, rfl, fun c mem => ?_⟩ + obtain ⟨⟨e, i⟩, memZ, found⟩ := List.mem_filterMap.mp mem + have := List.mem_zipIdx memZ + cases h : e.content.metadata.configuration with + | none => simp [h] at found + | some nodes => + simp only [h, Option.map_some, Option.some.injEq] at found + subst found + simp only + omega + +theorem active_append {L0 : List Model.Node.Entry} (T : List Model.Node.Entry) {ci : Nat} + (le : ci <= L0.length) + : exists R, + activeConfigurations (L0 ++ T) ci = activeConfigurations L0 ci ++ R + /\ forall c, c ∈ R -> L0.length < c.index := by + obtain ⟨R, hR, above⟩ := history_append L0 T + refine ⟨R, ?_, above⟩ + unfold activeConfigurations + dsimp only + rw [hR, List.filter_append] + have none : R.filter (fun c => decide (c.index <= ci)) = [] := + List.filter_eq_nil_iff.mpr fun c mem => by + have := above c mem + simp only [decide_eq_true_eq] + omega + rw [none, List.append_nil, List.drop_append_of_le_length] + have := List.length_filter_le (fun c => decide (c.index <= ci)) (configurationHistory L0) + omega + +theorem entryAt_append {L0 : List Model.Node.Entry} (T : List Model.Node.Entry) + {idx : Nat} (le : idx <= L0.length) + : entryAt? (L0 ++ T) idx = entryAt? L0 idx := by + unfold entryAt? + split + · rfl + · rw [List.getElem?_append_left (by omega)] + +/-- +Appending entries to a primary whose commit index is maximal does not let it commit, when an +active configuration has another member and no other member has reached the old log's end. +-/ +theorem hc_stuck {st st' : NodeState} {self : NodeID} {T : List Model.Node.Entry} + (log : st'.log = st.log ++ T) (commit : st'.commitIndex = st.commitIndex) + (term : st'.currentTerm = st.currentTerm) (match_ : st'.matchIndex = st.matchIndex) + (hmax : highestCommittableIndex st self <= st.commitIndex) + (ciLe : st.commitIndex <= st.log.length) + {X : Configuration} (hX : X ∈ activeConfigurations st.log st.commitIndex) + {m : NodeID} (hm : m ∈ X.nodes) (mne : m ≠ self) + (low : forall n, n ∈ X.nodes -> n ≠ self -> st.matchIndex n <= st.log.length) + : highestCommittableIndex st' self <= st'.commitIndex := by + obtain ⟨R, hA, above⟩ := active_append T ciLe + unfold highestCommittableIndex at hmax ⊢ + simp only [NodeState.activeMembers, NodeState.activeConfigurations, log, commit, term, + match_] at hmax ⊢ + have hfix := foldl_fixed (fun a x => le_ite_self fun c => Nat.le_of_lt c.1) _ _ hmax + refine Nat.le_of_eq (foldl_const _ _ fun idx mem => ?_) + split + · rename_i c + exfalso + obtain ⟨gt, sig, tm, q⟩ := c + rw [hA, List.filter_append] at q + have range := List.mem_range.mp mem + have hXh : X ∈ configurationHistory st.log := by + unfold activeConfigurations at hX + exact List.mem_of_mem_drop hX + have members : forall Y, Y ∈ activeConfigurations st.log st.commitIndex -> forall n, + n ∈ Y.nodes -> n ∈ configurationMembers (activeConfigurations st.log st.commitIndex ++ R) + /\ n ∈ configurationMembers (activeConfigurations st.log st.commitIndex) := + fun Y memY n member => ⟨ReplUpdateCommit.mem_configurationMembers + (List.mem_append_left _ memY) member, + ReplUpdateCommit.mem_configurationMembers memY member⟩ + by_cases le : idx <= st.log.length + · have fx := hfix idx (List.mem_range.mpr (by omega)) + rw [(List.filter_eq_nil_iff (l := R)).mpr (fun c memR => by + have := above c memR + simp only [decide_eq_true_eq] + omega), List.append_nil] at q + split at fx + · omega + · rename_i nc + refine nc ⟨gt, by simpa only [isSignatureAt, entryAt_append T le] using sig, + by simpa only [termAt, entryAt_append T le] using tm, q.1, + List.all_eq_true.mpr fun Y memY => decide_eq_true ?_⟩ + have maj := of_decide_eq_true (List.all_eq_true.mp q.2 Y memY) + have memY' := (List.mem_filter.mp memY).1 + unfold hasConfigurationMajority at maj ⊢ + refine Nat.lt_of_lt_of_le maj (Nat.mul_le_mul_right _ (CCF.Finset.card_le_card ?_)) + intro n inS + obtain ⟨inR, inY⟩ := CCF.Finset.mem_inter.mp inS + obtain ⟨-, which⟩ := CCF.Finset.mem_filter.mp inR + exact CCF.Finset.mem_inter.mpr ⟨CCF.Finset.mem_filter.mpr + ⟨(members Y memY' n inY).2, which⟩, inY⟩ + · have XLe := history_index_le st.log X hXh + have memF : X ∈ (activeConfigurations st.log st.commitIndex ++ R).filter + fun c => decide (c.index <= idx) := + List.mem_filter.mpr ⟨List.mem_append_left _ hX, decide_eq_true (by omega)⟩ + rw [← List.filter_append] at q + have maj := of_decide_eq_true (List.all_eq_true.mp q.2 X memF) + unfold hasConfigurationMajority at maj + generalize hs : (CCF.Finset.filter (fun n => n = self \/ st.matchIndex n >= idx) + (configurationMembers (activeConfigurations st.log st.commitIndex ++ R)) ∩ X.nodes) = s + at maj + have only : forall n, n ∈ s -> n = self := by + intro n inS + rw [← hs] at inS + obtain ⟨inR, inY⟩ := CCF.Finset.mem_inter.mp inS + obtain ⟨-, which⟩ := CCF.Finset.mem_filter.mp inR + refine Decidable.by_contra fun ne => ?_ + have := low n inY ne + rcases which with e | ge + · exact ne e + · omega + have one : s.card <= 1 := by + have := CCF.Finset.card_le_card (s := s) (t := {self}) + fun n inS => CCF.Finset.mem_singleton.mpr (only n inS) + exact this + have disj : CCF.Finset.Disjoint s {m} := fun n inS inM => + mne ((CCF.Finset.mem_singleton.mp inM).symm.trans (only n inS) |>.symm.symm) + have sub : s ∪ {m} ⊆ X.nodes := by + intro n inU + rcases CCF.Finset.mem_union.mp inU with inS | inM + · rw [← hs] at inS + exact (CCF.Finset.mem_inter.mp inS).2 + · rw [CCF.Finset.mem_singleton.mp inM] + exact hm + have := CCF.Finset.card_le_card sub + rw [CCF.Finset.card_union_of_disjoint disj] at this + have m1 : ({m} : Finset NodeID).card = 1 := rfl + omega + · rfl + +/-! ## The clean batch run -/ + +section CleanRun + +open CCF.Sections (LocalRun) +open Consensus.TraceValidation (Env protocol) + +theorem emits_appendBatch {cl0 cl cl' : NodeState} {es : List AppendEntryInput} + {o o2 : List (CCF.Envelope NodeID Message)} (prim : cl0.role = .primary) + (notRC : ¬ cl0.isRetiredCommitted node) (ne : es ≠ []) + (em : Emits (es.foldlM (entryStep node) cl0) cl o) + (ha : Emits (advanceCommit (CCF.Capabilities.record node) cl node) cl' o2) + : Emits (appendBatch (CCF.Capabilities.record node) node cl0 es) cl' (o ++ o2) := by + unfold appendBatch + exact emits_congr (emits_bind (emits_guard ⟨prim, notRC, ne⟩) (emits_bind em ha)) rfl + (List.nil_append _) + +theorem localRun_append (env : Env) {cl0 cl' : NodeState} {es : List AppendEntryInput} + {o : List (CCF.Envelope NodeID Message)} + (h : Emits (appendBatch (CCF.Capabilities.record node) node cl0 es) cl' o) + : LocalRun (protocol env) node cl0 (cleanActions env none [.append es]) cl' o := by + have := LocalRun.cons (protocol := protocol env) (node := node) (state := cl0) + (action := (protocol env).internal (.append es)) (effects := { outgoing := o }) + (emits_run h) (LocalRun.nil cl') + simpa [cleanActions] using this + +end CleanRun + +/-! ## The batch's commit, against the declared state -/ + +section Declared + +open Consensus.TraceValidation (Names abs agrees trackedPeers inv UnnamedUnmatched) +open Consensus.TraceValidation.Exec +open ReplUpdateCommit (Named named_inj Hyps shifted_mem absConfig) +open AeResp (Agrees hc_of_agrees) + +theorem eraseDups_eq_nil_iff {l : List NodeId} : l.eraseDups = [] <-> l = [] := by + cases l with + | nil => simp + | cons x xs => simp [List.eraseDups_cons] + +/-- No other node is in the active configurations iff every member is the node itself. -/ +theorem others_empty_iff (v : State) + : v.otherNodesInActiveConfigs.isEmpty = true + <-> forall c, c ∈ v.configurations -> forall a, a ∈ c.nodes -> a.1 = v.nodeId := by + unfold State.otherNodesInActiveConfigs + rw [List.isEmpty_iff, eraseDups_eq_nil_iff, ← List.length_eq_zero_iff, List.length_mergeSort, + List.length_eq_zero_iff, List.filter_eq_nil_iff] + simp only [List.mem_flatMap, List.mem_map, bne_iff_ne, ne_eq, Decidable.not_not] + constructor + · intro h c mc a ma + exact h a.1 ⟨c, mc, a, ma, rfl⟩ + · rintro h x ⟨c, mc, a, ma, rfl⟩ + exact h c mc a ma + +variable {names : Names} {node : NodeID} {v0 : State} {cl0 : NodeState} + +/-- The clean match index of a node of the starting active configurations is in the log. -/ +theorem Start.matchLow (S : Start names node v0 cl0) {n : NodeID} + (act : n ∈ cl0.activeMembers) (ne : n ≠ node) + : cl0.matchIndex n <= v0.lastIdx := by + have M := Mid.start S + obtain ⟨k, memK, rfl⟩ := (M.eligible n).mp + (CCF.Finset.mem_erase.mpr ⟨ne, CCF.Finset.mem_union.mpr (Or.inl act)⟩) + obtain ⟨p, memP⟩ := mem_keys.mp memK + obtain ⟨f, -, P⟩ := M.clean + have bounds : (v0.leadership != .leader + || v0.allOtherNodes.all fun (_, p) => p.sentIdx <= v0.lastIdx && p.matchIdx <= v0.lastIdx) + = true := by + inv_conj S.inv "peer_bounds" + simp only [S.leader, bne_self_eq_false, Bool.false_or, List.all_eq_true, + Bool.and_eq_true, decide_eq_true_eq] at bounds + rw [(P.rel k p ((lookup_iff_mem P.nodup).mpr memP)).2.2] + exact (bounds _ memP).2 + +/-- The clean commit before the batch is maximal (`commit_maximal`). -/ +theorem Start.maximal (S : Start names node v0 cl0) + : highestCommittableIndex cl0 node <= cl0.commitIndex := by + have M0 := Mid.start S + have e : (v0.leadership != .leader + || decide (highestCommittableIndex (abs names v0) (names.id v0.nodeId) + <= v0.commitIdx)) = true := by + inv_conj S.inv "commit_maximal" + simp only [S.leader, bne_self_eq_false, Bool.false_or, decide_eq_true_eq] at e + rw [← S.self, hc_of_agrees (Agrees.of S.agrees) fun n el => ?_, S.commit] + · exact e + · rw [S.self] at el + obtain ⟨k, memK, rfl⟩ := (M0.eligible n).mp el + obtain ⟨p, memP⟩ := mem_keys.mp memK + exact (tracked_iff S.leader).mpr ⟨k, p, memP, rfl⟩ + +/-- With other nodes before the batch, the clean commit after it does not move. -/ +theorem Mid.stuck (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + (others : v0.otherNodesInActiveConfigs.isEmpty = false) + : highestCommittableIndex cl node <= cl.commitIndex := by + obtain ⟨c, mc, a, ma, ne⟩ : exists c, c ∈ v0.configurations /\ exists a, a ∈ c.nodes + /\ a.1 ≠ v0.nodeId := by + refine Decidable.by_contra fun h => ?_ + have := (others_empty_iff v0).mpr fun c mc a ma => + Decidable.by_contra fun e => h ⟨c, mc, a, ma, e⟩ + rw [this] at others + cases others + have M0 := Mid.start S + have hy := M0.hy + have L0 := M0.pos (List.ne_nil_of_mem mc) + have len : cl0.log.length = v0.lastIdx := by + rw [S.log] + exact ReplUpdateCommit.abs_log_length hy.size + obtain ⟨D, hD, sh⟩ := hy.configs L0 + obtain ⟨x', memD, nodes⟩ := shifted_mem sh mc + have named : Named names a.1 := hy.membersNamed c mc a ma + have hX : absConfig names x' ∈ activeConfigurations cl0.log cl0.commitIndex := by + rw [S.log, S.commit, hD] + exact List.mem_map_of_mem memD + have inX : names.id a.1 ∈ (absConfig names x').nodes := by + simp only [absConfig, nodes, Names.set, CCF.Finset.mem_ofList, List.mem_map] + exact ⟨a.1, ⟨a, ma, rfl⟩, rfl⟩ + have mne : names.id a.1 ≠ node := fun e => + ne (named_inj named hy.selfNamed (e.trans (S.self).symm)) + have hmax := S.maximal + obtain ⟨f, rfl, -⟩ := M.clean + obtain ⟨T, hT⟩ := M.isPrefix + refine hc_stuck (st := cl0) (T := T) hT.symm rfl rfl rfl hmax ?_ hX inX mne + fun n mem nne => ?_ + · rw [len, S.commit] + exact hy.commitLe + · rw [len] + exact S.matchLow (ReplUpdateCommit.mem_configurationMembers hX mem) nne + +theorem Mid.cover (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : AeResp.Cover v := by + rintro id ⟨c, memC, a, ma, rfl⟩ ne + rcases M.member S memC ma with e | k + · exact absurd e ne + · obtain ⟨q, memQ⟩ := mem_keys.mp k + exact ⟨(a.1, q), memQ, rfl⟩ + +/-- Without other nodes before the batch, no pending record names a node `v` keeps. -/ +theorem Mid.rcRetired {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) (alone : v0.otherNodesInActiveConfigs.isEmpty = true) + (i : Nat) + : AeResp.RcRetired v i := by + intro e memE _ id memId ne mem + obtain ⟨c, memC, a, ma, rfl⟩ := mem.suffix (AeResp.pop_suffix _ _) + obtain ⟨new, hv, fresh⟩ := M.cfgNew + rw [hv] at memC + rcases List.mem_append.mp memC with old | memN + · exact ne (((others_empty_iff v0).mp alone c old a ma).trans M.frame.nodeId.symm) + · exact fresh c memN a ma (M.rcRemoved e memE a.1 memId) + +end Declared + +/-! ## `update_commit` after the batch -/ + +section Uc + +open Consensus.TraceValidation (Env) +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae +open AeResp (RInv Cover RcRetired commit_spec hoare_assume hoare_curLoc_fail) + +/-- What `update_commit` by a leader `v1` with outbox `o1` leaves. -/ +def UcOut (env : Env) (v1 : State) (o1 : Outbox) (v : State) (o : Outbox) : Prop := + exists res, + ReplUpdateCommit.updateCommitOf v1 0 none (v1.lastIdx + 2) = .ok res + /\ ((res.getD v1.commitIdx <= v1.commitIdx /\ v = v1 /\ o = o1) + \/ exists i, + res = some i /\ v1.commitIdx < i /\ i <= v1.lastIdx /\ RInv env v1 i o1 v o) + +theorem updateCommit_hoare (env : Env) {v1 : State} {o1 : Outbox} + (lead : v1.leadership = .leader) (cover : Cover v1) (hrc : forall i, RcRetired v1 i) + : Hoare env (fun v o => v = v1 /\ o = o1) Exec.updateCommit + fun _ => UcOut env v1 o1 := by + unfold Exec.updateCommit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = v1) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst s + have l1 : (v1.leadership == .leader) = true := by simp [lead] + simp only [l1, ↓reduceIte] + refine Hoare.bind (Hoare.of_spec (ReplUpdateCommit.updateCommitGo_spec _ _ _) + (Q := fun res v o => v = v1 /\ o = o1 + /\ ReplUpdateCommit.updateCommitOf v1 0 none (v1.lastIdx + 2) = .ok res) + fun v o a v' o' p q => ?_) fun res => ?_ + · obtain ⟨⟨e, f⟩, -⟩ := p + obtain ⟨q1, q2, q3⟩ := q + rw [q1, q2, e, f] + exact ⟨rfl, rfl, e ▸ q3⟩ + have out : forall (v : State) (o : Outbox), (v = v1 /\ o = o1 + /\ ReplUpdateCommit.updateCommitOf v1 0 none (v1.lastIdx + 2) = .ok res) + -> res.getD v1.commitIdx <= v1.commitIdx -> UcOut env v1 o1 v o := + fun v o p le => ⟨res, p.2.2, Or.inl ⟨le, p.1, p.2.1⟩⟩ + cases res with + | none => exact Hoare.pure _ fun v o p => out v o p (Nat.le_refl _) + | some i => + simp only + by_cases gt : i > v1.lastIdx + · unfold Exec.commit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = v1) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst s + simp only [gt, ↓reduceIte] + exact hoare_curLoc_fail _ + by_cases le : i <= v1.commitIdx + · unfold Exec.commit + refine Hoare.getV_bind fun s => ?_ + refine hoare_assume (φ := s = v1) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst s + simp only [gt, le, ↓reduceIte] + exact Hoare.pure _ fun v o p => out v o p.1 le + refine hoare_assume (φ := ReplUpdateCommit.updateCommitOf v1 0 none (v1.lastIdx + 2) + = .ok (some i)) (fun _ _ p => p.2.2) fun ran => ?_ + exact Hoare.post + (Hoare.pre + (commit_spec env (v1 := v1) (o0 := o1) lead (by omega) (by omega) cover (hrc i)) + fun v o p => ⟨p.1, p.2.1⟩) + fun _ v o q => ⟨some i, ran, Or.inr ⟨i, rfl, by omega, by omega, q⟩⟩ + +end Uc + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCreate.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCreate.lean new file mode 100644 index 000000000000..6ae882f65181 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplCreate.lean @@ -0,0 +1,192 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplPeerSend +public import Consensus.TraceValidation.Proofs.Handlers.ReplFlush + +@[expose] public section + +/-! +# `create_and_remove_node_state` on a leader (not reviewed; `Replicate` obligation) + +On a leader whose ledger satisfies `ViewHyps`, `create_and_remove_node_state` gives each node +of its configurations that is neither itself nor a peer a peer state at the end of the ledger, +unmatched, and sends it one empty AppendEntries from one past the ledger, in node id order. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Life + +variable {env : Env} + +/-- A loop over `l` that always continues, with an invariant indexed by the visited prefix. -/ +theorem forIn_prefix {α : Type} {l : List α} {f : α -> PUnit -> M (ForInStep PUnit)} + {I : List α -> State -> Outbox -> Prop} + (h + : forall pre a rest, + pre ++ a :: rest = l + -> Tri env (I pre) (f a PUnit.unit) + fun r v o => r = .yield PUnit.unit /\ I (pre ++ [a]) v o) + : Tri env (I []) (forIn l PUnit.unit f) fun _ => I l := by + suffices gen : forall rest pre, pre ++ rest = l + -> Tri env (I pre) (forIn rest PUnit.unit f) fun _ => I l from gen l [] rfl + intro rest + induction rest with + | nil => + intro pre e + rw [List.append_nil] at e + subst e + rw [List.forIn_nil] + exact Tri.pure' (Q := fun _ => I pre) _ + | cons a rest ih => + intro pre e + rw [List.forIn_cons] + refine Tri.bind (h pre a rest e) fun r => ?_ + refine tri_fact (φ := r = .yield PUnit.unit) (fun _ _ p => p.1) fun yr => ?_ + subst yr + exact Tri.conseq (ih (pre ++ [a]) (by rw [List.append_assoc]; exact e)) + (fun _ _ p => p.2) fun _ _ _ q => q + +/-- The empty AppendEntries a new peer gets from one past the ledger. -/ +def hb (env : Env) (w : State) (id : NodeId) : CCF.Envelope NodeID Message := + ⟨ + env.names.id w.nodeId, + env.names.id id, + .appendEntriesRequest (rangeRequest env.names w (w.lastIdx + 1) w.lastIdx) + ⟩ + +/-- The nodes of `ids` that are neither the node nor its peers. -/ +def newOf (w : State) (ids : List NodeId) : List NodeId := + ids.filter fun id => id != w.nodeId && (w.peer? id).isNone + +/-- `ps` holds `w`'s peers and, for each node of `new`, an unmatched peer at the ledger's end. -/ +def Added (w : State) (new : List NodeId) (ps : List (NodeId × Peer)) : Prop := + (ps.map Prod.fst).Nodup + /\ forall k, + ps.lookup k + = if k ∈ new then some { sentIdx := w.lastIdx, matchIdx := 0 } else w.peer? k + +/-- What `create_and_remove_node_state` leaves after visiting `pre` of the node ids. -/ +def CarInv (env : Env) (w : State) (o0 : Outbox) (pre : List NodeId) (v : State) + (o : Outbox) + : Prop := + exists ps, + v = { w with allOtherNodes := ps } + /\ Added w (newOf w pre) ps + /\ o = o0 ++ (newOf w pre).map (hb env w) + +theorem newOf_snoc (w : State) (pre : List NodeId) (id : NodeId) + : newOf w (pre ++ [id]) + = newOf w pre ++ (if id != w.nodeId && (w.peer? id).isNone then [id] else []) := by + simp only [newOf, List.filter_append, List.filter_cons, List.filter_nil] + +theorem mem_newOf {w : State} {pre : List NodeId} {k : NodeId} + : k ∈ newOf w pre <-> k ∈ pre /\ k ≠ w.nodeId /\ w.peer? k = none := by + simp [newOf] + +theorem car_spec {w : State} (lead : w.leadership = .leader) (vh : ViewHyps w) + (rc : w.isRetiredCommitted = false) (nd : (w.allOtherNodes.map Prod.fst).Nodup) + {o0 : Outbox} + : Tri env (fun v o => v = w /\ o = o0) createAndRemoveNodeState + fun _ => + CarInv env w o0 + ((w.configurations.flatMap (·.nodes.map Prod.fst)).mergeSort (· <= ·) + |>.eraseDups) := by + unfold createAndRemoveNodeState + refine Tri.getV_bind fun v => ?_ + refine tri_fact (φ := v = w) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + dsimp only + have sd := sortDedup_spec (v.configurations.flatMap (·.nodes.map Prod.fst)) + refine Tri.bind + (Tri.conseq (forIn_prefix (I := CarInv env v o0) fun pre id rest e => ?_) + (fun v' o p => ?_) fun _ _ _ q => q) + fun _ => Tri.pure' (Q := fun _ => _) _ + · have ndl : (pre ++ id :: rest).Nodup := by rw [e]; exact sd.1.imp fun h e => by subst e; exact String.lt_irrefl _ h + have notPre : id ∉ pre := fun m => (List.nodup_append.mp ndl).2.2 id m id + (List.mem_cons_self ..) rfl + refine Tri.ite (fun self => ?_) (fun notSelf => ?_) + · refine Tri.conseq (Tri.pure' (Q := fun r w o => r = .yield PUnit.unit + /\ CarInv env v o0 (pre ++ [id]) w o) _) (fun v' o p => ⟨rfl, ?_⟩) fun _ _ _ q => q + have : (id != v.nodeId && (v.peer? id).isNone) = false := by + simp only [beq_iff_eq] at self; simp [self] + unfold CarInv + rw [newOf_snoc, this] + simp only [Bool.false_eq_true, ite_false, List.append_nil] + exact p + · refine Tri.getV_bind fun u => ?_ + refine tri_pin fun u' o' hp => ?_ + obtain ⟨⟨ps, e1, ⟨ndps, lk⟩, e2⟩, e3⟩ := hp + subst e3 e1 e2 + have look : ({ v with allOtherNodes := ps } : State).peer? id = v.peer? id := by + show ps.lookup id = _ + rw [lk] + simp [mem_newOf, notPre] + simp only [look] + cases hv : v.peer? id with + | some q => + simp only [Option.isNone_some, Bool.false_eq_true, ite_false] + refine Tri.conseq + (Tri.pure' + (Q := + fun r w o => r = .yield PUnit.unit /\ CarInv env v o0 (pre ++ [id]) w o) + _) + (fun v' o p => ⟨rfl, ?_⟩) fun _ _ _ q => q + have : (id != v.nodeId && (v.peer? id).isNone) = false := by simp [hv] + obtain ⟨rfl, rfl⟩ := p + unfold CarInv + rw [newOf_snoc, this] + simp only [Bool.false_eq_true, ite_false, List.append_nil] + exact ⟨ps, rfl, ⟨ndps, lk⟩, trivial⟩ + | none => + simp only [Option.isNone_none, ite_true] + have new : (id != v.nodeId && (v.peer? id).isNone) = true := by + simp only [beq_iff_eq] at notSelf; simp [notSelf, hv] + let p : Peer := { sentIdx := v.lastIdx + 1, matchIdx := 0 } + let u1 := ({ v with allOtherNodes := ps } : State).setPeer id p + have nd1 : (u1.allOtherNodes.map Prod.fst).Nodup := setPeer_nodup ndps id p + refine Tri.bind + (Q := fun _ w o => w = u1 /\ o = o0 ++ (newOf v pre).map (hb env v)) + (Tri.setV fun _ _ p => by rw [p.1]; exact ⟨rfl, p.2⟩) fun _ => ?_ + have lead' : (({ v with allOtherNodes := ps } : State).leadership == .leader) = true := by + simp [lead] + simp only [lead', ↓reduceIte] + refine Tri.bind + (heartbeat_tri (v0 := u1) (p := p) (viewHyps_withPeers vh _) rc + (by rw [setPeer_lookup ndps]; simp)) + fun _ => ?_ + refine Tri.conseq + (Tri.pure' + (Q := + fun r w o => r = .yield PUnit.unit /\ CarInv env v o0 (pre ++ [id]) w o) + _) + (fun v' o h => ⟨rfl, ?_⟩) fun _ _ _ q => q + obtain ⟨rfl, rfl⟩ := h + unfold CarInv + rw [newOf_snoc, new] + refine ⟨_, rfl, ⟨setPeer_nodup nd1 id _, fun k => ?_⟩, ?_⟩ + · show (u1.setPeer id _).peer? k = _ + rw [setPeer_lookup nd1] + show _ = if k ∈ newOf v pre ++ [id] then _ else _ + by_cases hk : k = id + · subst hk + simp only [ite_true, List.mem_append, List.mem_singleton, or_true] + rfl + · simp only [hk, ↓reduceIte] + rw [setPeer_lookup ndps] + simp only [hk, ↓reduceIte] + show ps.lookup k = _ + rw [lk] + simp [hk] + · simp only [List.map_append, List.append_assoc] + rfl + · obtain ⟨⟨rfl, rfl⟩, -⟩ := p + refine ⟨v'.allOtherNodes, rfl, ⟨nd, fun k => ?_⟩, by simp [newOf]⟩ + simp [newOf, State.peer?] + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEmits.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEmits.lean new file mode 100644 index 000000000000..47f4d114a7dc --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEmits.lean @@ -0,0 +1,106 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Obligation + +import all Init.Control.State + +@[expose] public section + +/-! +# Clean effects that succeed with known sends (not reviewed) + +`Emits x a sends`: the clean effect `x` succeeds from any outputs with result `a`, appending +exactly `sends` (and no notification). The `replicate` proof builds the clean `append` run +entry by entry with these rules. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node + +def Emits {α : Type} (x : NodeEffect α) (a : α) + (sends : List (CCF.Envelope NodeID Message)) + : Prop := + forall out : CCF.Outputs NodeID Message Notification, + x.run out = some (a, { out with outgoing := out.outgoing ++ sends }) + +variable {node : NodeID} + +theorem emits_pure {α : Type} (a : α) : Emits (pure a : NodeEffect α) a [] := by + intro out + cases out + simp [StateT.run, pure, StateT.pure] + +theorem emits_bind {α β : Type} {x : NodeEffect α} {f : α -> NodeEffect β} {a : α} {b : β} + {first later : List (CCF.Envelope NodeID Message)} + (hx : Emits x a first) (hf : Emits (f a) b later) + : Emits (x >>= f) b (first ++ later) := by + intro out + have := hx out + simp only [StateT.run, bind, StateT.bind] at this ⊢ + rw [this] + simp only [Option.bind] + have := hf { out with outgoing := out.outgoing ++ first } + simp only [StateT.run, List.append_assoc] at this + exact this + +theorem emits_send (message : Message) (target : NodeID) + : Emits ((CCF.Capabilities.record node).send message target) () + [⟨node, target, message⟩] := by + intro out + rfl + +theorem emits_guard {p : Prop} [Decidable p] (h : p) + : Emits (guard p : NodeEffect Unit) () [] := by + intro out + cases out + simp [guard, h, StateT.run, pure, StateT.pure] + +theorem emits_congr {α : Type} {x : NodeEffect α} {a b : α} + {first later : List (CCF.Envelope NodeID Message)} + (h : Emits x a first) (same : a = b) (sends : first = later) + : Emits x b later := by + subst same sends + exact h + +theorem emits_run {α : Type} {x : NodeEffect α} {a : α} + {sends : List (CCF.Envelope NodeID Message)} + (h : Emits x a sends) + : x.run {} = some (a, { outgoing := sends }) := + h {} + +theorem emits_ite_guard_bind {β : Type} {c : Prop} [Decidable c] {p : Prop} [Decidable p] + {k : Unit -> NodeEffect β} {b : β} {sends : List (CCF.Envelope NodeID Message)} + (h : c -> p) (hk : Emits (k ()) b sends) + : Emits (if c then (guard p : NodeEffect Unit) >>= k else k ()) b sends := by + split + · rename_i yes + exact emits_congr (emits_bind (emits_guard (h yes)) hk) rfl (List.nil_append _) + · exact hk + +theorem emits_forIn_send (peers : List NodeID) (f : NodeID -> Message) + : Emits + (forIn peers PUnit.unit + fun peer _ => do + (CCF.Capabilities.record node).send (f peer) peer + pure (ForInStep.yield PUnit.unit) + : NodeEffect PUnit) + PUnit.unit (peers.map fun peer => ⟨node, peer, f peer⟩) := by + induction peers with + | nil => exact emits_pure _ + | cons peer rest ih => + rw [List.forIn_cons] + exact emits_congr + (emits_bind + (x := do + (CCF.Capabilities.record node).send (f peer) peer; + pure (ForInStep.yield PUnit.unit)) + (a := ForInStep.yield PUnit.unit) + (emits_bind (f := fun _ => pure (ForInStep.yield PUnit.unit)) (emits_send _ _) + (emits_pure _)) ih) + rfl (by simp) + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEntry.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEntry.lean new file mode 100644 index 000000000000..9e32195288dd --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplEntry.lean @@ -0,0 +1,487 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplAppend + +@[expose] public section + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation (Names abs absEntry msgInv) +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Life + +variable {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + +theorem retiredHooks_pres {I : State -> Outbox -> Prop} (index : Nat) + : forall (fuel : Nat) (acc : List NodeId), Pres env I (retiredHooks index fuel acc) + | 0, _ => by + unfold retiredHooks + repeat' pres_step + | fuel + 1, acc => by + unfold retiredHooks + repeat' (first | exact retiredHooks_pres index fuel _ | pres_step) + +theorem hooked_refl (v : State) : Hooked v [] [] [] v := + ⟨ + v.ticking, + v.retired, + v.retirementPhase, + v.retirementIdx, + v.retirementCommittableIdx, + v.allOtherNodes, + by simp + ⟩ + +theorem tri_setV_eq {Y : State} {O : Outbox} {f : State -> State} + : Tri env (fun v o => v = Y /\ o = O) (setV f) fun _ v o => v = f Y /\ o = O := + Tri.setV fun v o p => by rw [p.1, p.2]; exact ⟨rfl, rfl⟩ + +theorem becomeOrdered_tri {Y : State} {O : Outbox} {idx : Nat} + : Tri env (fun v o => v = Y /\ o = O) (becomeRetired idx .ordered) + fun _ v o => + v + = { + Y with + retirementIdx := some idx, + retired := true, + retirementPhase := some Phase.ordered + } + /\ o = O := by + unfold becomeRetired + dsimp only + refine Tri.getV_bind fun x => ?_ + refine Tri.ite (fun _ => ?_) (fun _ => ?_) + · exact Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _ + · exact Tri.bind (Tri.conseq tri_setV_eq (fun _ _ p => p.1) fun _ _ _ q => q) + fun _ => Tri.conseq tri_setV_eq (fun _ _ p => p) fun _ _ _ q => q + +theorem becomeSigned_tri {Y : State} {O : Outbox} {idx : Nat} + : Tri env (fun v o => v = Y /\ o = O) (becomeRetired idx .signed) + fun _ v o => + v + = { + Y with + retirementCommittableIdx := some idx, + retired := true, + retirementPhase := some Phase.signed + } + /\ o = O := by + unfold becomeRetired + dsimp only + exact Tri.bind tri_setV_eq fun _ => Tri.conseq tri_setV_eq (fun _ _ p => p) fun _ _ _ q => q + +/-- What `add_configuration` leaves: possibly a retirement, then a new configuration. -/ +def AddPost (env : Env) (X : State) (O : Outbox) (idx : Nat) (nodes : Nodes) (v : State) + (o : Outbox) + : Prop := + exists Y : State, + (Y = X + \/ Y + = { + X with + retirementIdx := some idx, + retired := true, + retirementPhase := some Phase.ordered + }) + /\ ((X.configurations.getLast?.map (fun c : Config => c.nodes) = some nodes + /\ v = Y + /\ o = O) + \/ CarInv env + { + Y with + configurations := + X.configurations ++ [({ idx, nodes, rid := idx } : Config)] + } + O + (((X.configurations ++ [({ idx, nodes, rid := idx } : Config)]).flatMap + (·.nodes.map Prod.fst)).mergeSort + (· <= ·) + |>.eraseDups) + v o) + +theorem addConfiguration_tri {X : State} {O : Outbox} {idx : Nat} + (lead : X.leadership = .leader) (vh : ViewHyps X) (rc : X.isRetiredCommitted = false) + (nd : (X.allOtherNodes.map Prod.fst).Nodup) + : Tri env (fun v o => v = X /\ o = O) (addConfiguration (some idx) none) + fun nodes => AddPost env X O idx nodes := by + unfold addConfiguration + refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.getV_bind fun v => ?_ + dsimp only + refine Tri.bind (Tri.keeps (Spec.emitNat _ _)) fun _ => ?_ + simp only [pure_bind] + refine Tri.bind (Tri.keeps (Spec.emitNat _ _)) fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.use _)) fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.liftE _)) fun nodes => ?_ + refine tri_fact (φ := v = X) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + have tail : forall Y : State, (Y = v \/ Y = { v with retirementIdx := some idx, retired := true, retirementPhase := some Phase.ordered }) + -> Tri env (fun w o => w = Y /\ o = O) (do + let w ← getV + if (w.configurations.isEmpty + || some nodes != w.configurations.getLast?.map (·.nodes)) = true then + do + setV fun w => { w with configurations := w.configurations ++ [{ idx, nodes, rid := idx }] } + createAndRemoveNodeState + pure nodes + else pure nodes) fun r => AddPost env v O idx r := by + intro Y hY + have cfgY : Y.configurations = v.configurations := by rcases hY with rfl | rfl <;> rfl + refine Tri.getV_bind fun w => ?_ + refine tri_fact (φ := w = Y) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst e + refine Tri.ite (fun _ => ?_) (fun hn => ?_) + · let W : State := { w with configurations := v.configurations ++ [{ idx, nodes, rid := idx }] } + have rcW : W.isRetiredCommitted = false := by + rcases hY with rfl | rfl + · exact rc + · rfl + have hW : W.leadership = .leader := by rcases hY with rfl | rfl <;> exact lead + have ndW : (W.allOtherNodes.map Prod.fst).Nodup := by rcases hY with rfl | rfl <;> exact nd + have vhW : ViewHyps W := by + rcases hY with rfl | rfl <;> + exact ⟨vh.size, vh.sorted, vh.positive, vh.leLast, vh.terms, vh.posTerms⟩ + refine Tri.bind (Q := fun _ u o => u = W /\ o = O) + (Tri.setV fun u o p => by rw [p.1.1, p.1.2, cfgY]; exact ⟨rfl, rfl⟩) fun _ => ?_ + refine Tri.bind (car_spec hW vhW rcW ndW) fun _ => ?_ + exact Tri.pure' (Q := fun r => AddPost env v O idx r) _ |>.conseq + (fun u o p => ⟨w, hY, Or.inr p⟩) fun _ _ _ q => q + · refine Tri.conseq (Tri.pure' (Q := fun r => AddPost env v O idx r) _) + (fun u o p => ⟨w, hY, Or.inl ⟨?_, p.1.1, p.1.2⟩⟩) fun _ _ _ q => q + rw [← cfgY] + simp only [Bool.or_eq_true, bne_iff_ne, ne_eq, not_or, Decidable.not_not] at hn + exact hn.2.symm + split + · rename_i last _ + refine Tri.ite (fun _ => ?_) (fun _ => ?_) + · exact Tri.bind (Tri.conseq becomeOrdered_tri (fun _ _ p => p.1) fun _ _ _ q => q) + fun _ => tail _ (Or.inr rfl) + · exact Tri.conseq (tail _ (Or.inl rfl)) (fun _ _ p => p.1) fun _ _ _ q => q + · exact Tri.conseq (tail _ (Or.inl rfl)) (fun _ _ p => p.1) fun _ _ _ q => q + +theorem names_set_congr {names : Names} {l1 l2 : List NodeId} + (h : forall x, x ∈ l1 <-> x ∈ l2) + : names.set l1 = names.set l2 := by + apply CCF.Finset.ext + intro n + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map, h] + +theorem shifted_last {c : Nat} {D E : List Config} (sh : ReplUpdateCommit.Shifted c D E) + : D.getLast?.map (fun x : Config => x.nodes) + = E.getLast?.map (fun x : Config => x.nodes) := by + rcases sh with rfl | ⟨x, y, rest, rfl, rfl, n, -⟩ + · rfl + · cases rest with + | nil => simp [n] + | cons a r => simp [List.getLast?_cons_cons] + +theorem active_last {log : List Consensus.Model.Node.Entry} {c : Nat} {x : Configuration} + (h : (activeConfigurations log c).getLast? = some x) + : (configurationHistory log).getLast? = some x := by + unfold activeConfigurations at h + dsimp only at h + rw [List.getLast?_drop] at h + split at h + · cases h + · exact h + +/-- The node set of the last declared configuration is the clean latest configuration. -/ +theorem Mid.latest_of_last {names : Names} {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) {nodes : Nodes} + (hl : v.configurations.getLast?.map (fun c : Config => c.nodes) = some nodes) + : names.set (nodes.map Prod.fst) + = latestConfigurationMembers (configurationHistory (abs names v).log) := by + have pos : 0 < v.lastIdx := by + rcases Nat.eq_zero_or_pos v.lastIdx with h | h + · rw [M.unconf h] at hl + cases hl + · exact h + obtain ⟨D, hD, sh⟩ := M.hy.configs pos + rw [← shifted_last sh, Option.map_eq_some_iff] at hl + obtain ⟨d, hd, rfl⟩ := hl + have h1 : (activeConfigurations (abs names v).log v.commitIdx).getLast? + = some (ReplUpdateCommit.absConfig names d) := by + rw [hD, List.getLast?_map, hd] + rfl + simp only [latestConfigurationMembers, active_last h1, Option.map_some, Option.getD_some, + ReplUpdateCommit.absConfig] + +theorem Mid.newE_none {names : Names} (S : Start names node v0 cl0) {cl1 : NodeState} + {v1 : State} (M : Mid names node v0 cl0 cl1 v1) + : newE v1 none = [] := + List.eq_nil_iff_forall_not_mem.mpr + fun _ m => by + obtain ⟨⟨_, h, _⟩, _⟩ := (M.mem_newE S).mp m + cases h + +theorem added_nil {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) + : Added v [] v.allOtherNodes := + ⟨nd, fun k => by simp only [List.not_mem_nil, ↓reduceIte]; rfl⟩ + +theorem Hooked.signed {v1 w : State} {K : List Nat} {cfgs : List Config} + {R : List (Nat × List NodeId)} (h : Hooked v1 K cfgs R w) (idx : Nat) + : Hooked v1 K cfgs R + { + w with + retirementCommittableIdx := some idx, + retired := true, + retirementPhase := some Phase.signed + } := by + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := h + exact ⟨tk, true, some Phase.signed, ri, some idx, ps, rfl⟩ + +theorem Hooked.commit {v1 w : State} {cfgs : List Config} {R : List (Nat × List NodeId)} + (h : Hooked v1 [] cfgs R w) (k : Nat) + : Hooked v1 [k] cfgs R { w with committable := w.committable ++ [k] } := by + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := h + exact ⟨tk, r, ph, ri, rci, ps, by simp⟩ + +theorem Hooked.tick {v1 w : State} {K : List Nat} {cfgs : List Config} + {R : List (Nat × List NodeId)} (h : Hooked v1 K cfgs R w) + : Hooked v1 K cfgs R { w with ticking := true } := by + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := h + exact ⟨true, r, ph, ri, rci, ps, rfl⟩ + +/-- The state and outbox after an entry's hooks, before it is appended. -/ +def Stage (env : Env) (u : State) (o1 : Outbox) (K : List Nat) (cfgs : List Config) + (R : List (Nat × List NodeId)) (new : List NodeId) (v : State) (o : Outbox) + : Prop := + Hooked u K cfgs R v + /\ v.isRetiredCommitted = false + /\ Added u new v.allOtherNodes + /\ o = o1 ++ new.map (hb env u) + +theorem tri_getV_pin {β : Type} {f : State -> M β} {X : State} {O : Outbox} + {R : β -> State -> Outbox -> Prop} (h : Tri env (fun v o => v = X /\ o = O) (f X) R) + : Tri env (fun v o => v = X /\ o = O) (getV >>= f) R := + Tri.getV_bind + fun v => + tri_fact (φ := v = X) (fun _ _ p => p.2.symm.trans p.1.1) + fun e => by + subst e + exact Tri.conseq h (fun _ _ p => p.1) fun _ _ _ q => q + +theorem tri_names_bind {β : Type} {f : Names -> M β} {P : State -> Outbox -> Prop} + {R : β -> State -> Outbox -> Prop} (h : Tri env P (f env.names) R) + : Tri env P (Exec.names >>= f) R := + Tri.bind (Tri.ofSpec (Q := fun a w o => P w o /\ a = env.names) Spec.names + fun _ _ _ _ _ p h => by obtain ⟨rfl, rfl, rfl⟩ := h; exact ⟨p, rfl⟩) + fun a => tri_fact (φ := a = env.names) (fun _ _ q => q.2) fun e => by + subst e + exact Tri.conseq h (fun _ _ q => q.1) fun _ _ _ q => q + +/-- Some batch prefix relates the state and outbox. -/ +def Batch (env : Env) (node : NodeID) (v0 : State) (cl0 : NodeState) (v : State) + (o : Outbox) + : Prop := + exists es, Ghost env node v0 cl0 es v o + +theorem entry_tri (S : Start env.names node v0 cl0) + : Tri env (Batch env node v0 cl0) replicateEntry + fun _ => FlushGhost env node v0 cl0 := by + refine tri_pin fun u o1 ⟨es, g⟩ => ?_ + obtain ⟨vhU, rcU, ndU⟩ := g.base + obtain ⟨cl1, -, M, -⟩ := id g + unfold replicateEntry + refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.getV_bind fun v => ?_ + refine tri_fact (φ := v = u) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst v + refine Tri.conseq (P' := fun w o => w = u /\ o = o1) ?_ (fun _ _ p => p.1) + fun _ _ _ q => q + extract_lets index config0 jpV + refine Tri.bind (Tri.keeps (Spec.inBool _)) fun sig => ?_ + extract_lets jp0 + -- The flush after the views check. + have hV : forall X O, FlushGhost env node v0 cl0 + { X with views := X.views ++ Array.replicate (X.currentView - X.views.size) index } O + -> Tri env (fun w o => w = X /\ o = O) (jpV ()) fun _ => FlushGhost env node v0 cl0 := by + intro X O fg + refine Tri.bind (Q := fun _ w o => FlushGhost env node v0 cl0 w o) + (Tri.setV fun w o p => by rw [p.1, p.2]; exact fg) fun _ => ?_ + refine Tri.bind (Tri.keeps Spec.lookFn) fun l => ?_ + refine Tri.ite (fun _ => ?_) (fun _ => ?_) + · refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.note _)) fun _ => ?_ + refine Tri.bind pres_otherNodesSorted fun ids => ?_ + refine Tri.bind (Tri.forIn_list fun id _ _ => ?_) fun _ => + Tri.pure' (Q := fun _ => FlushGhost env node v0 cl0) _ |>.conseq (fun _ _ p => p) + fun _ _ _ q => q + refine Tri.getV_bind fun x => ?_ + split + · rename_i p hp + refine Tri.bind (Tri.conseq (flushSend_tri S) (fun w o q => ⟨q.1, p, by rw [q.2]; exact hp, + rfl, by obtain ⟨_, _, _, gq⟩ := q.1; exact gq.bound (by rw [q.2]; exact hp)⟩) + fun _ _ _ q => q) fun _ => Tri.pure' (Q := fun _ => FlushGhost env node v0 cl0) _ + · exact Tri.pure' (Q := fun _ => FlushGhost env node v0 cl0) _ |>.conseq + (fun _ _ p => p.1) fun _ _ _ q => q + · exact Tri.pure' (Q := fun _ => FlushGhost env node v0 cl0) _ |>.conseq (fun _ _ p => p) + fun _ _ _ q => q + refine Tri.ite (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + (fun hs0 => ?_) + refine Tri.bind (Tri.keeps Spec.Keeps.get) fun ctx => ?_ + refine Tri.bind (retiredHooks_pres index _ _) fun retired => ?_ + extract_lets jp2 jp1 jpR + have h2 : (retired ≠ [] -> env.names.set retired + ⊆ (abs env.names u).retirementCompletedNodes \ retiredCommittedNodes (abs env.names u).log) + -> forall config : Option Nodes, (forall nodes, config = some nodes + -> (nodes.map Prod.fst).Nodup /\ nodes ≠ [] + /\ env.names.set (nodes.map Prod.fst) + ≠ latestConfigurationMembers (configurationHistory (abs env.names u).log) + /\ forall a, a ∈ nodes -> env.names.id a.1 ∉ removedNodes (abs env.names u).log) + -> Tri env (Stage env u o1 [] (cfgsOf u config) (rcsOf u retired) (newE u config)) (jp2 () config) + fun _ => FlushGhost env node v0 cl0 := by + intro hrc config hcfg + refine tri_names_bind ?_ + extract_lets ids jpPush jp6 jpS jp4 + refine Tri.ite (fun hk => ?_) (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + refine Tri.ite (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) (fun hp => ?_) + have G : Guards env.names u sig config retired := { + sigNonempty := fun hs h0 => hs0 (by simp [hs, h0]) + sigPlain := fun hs => by subst hs; simpa using hp + rc := hrc + known := fun id m => by + simp only [ids, Bool.or_eq_true, Bool.and_eq_true, List.isEmpty_iff, List.all_eq_true] at hk + rcases hk with he | ⟨ha, -⟩ + · rw [he] at m + cases m + · exact ha id m + sorted := fun ne => by + simp only [ids, Bool.or_eq_true, Bool.and_eq_true, List.isEmpty_iff] at hk + rcases hk with he | ⟨-, hs⟩ + · exact absurd he ne + · exact hs + cfg := hcfg } + have hP : Tri env (Stage env u o1 (if sig then [u.lastIdx + 1] else []) (cfgsOf u config) + (rcsOf u retired) (newE u config)) (jpPush ()) fun _ => FlushGhost env node v0 cl0 := by + refine tri_pin fun w O ⟨hw, rcw, added, eo⟩ => ?_ + have pg := push_ghost S g G hw rcw added + rw [← eo] at pg + obtain ⟨tk, r, ph, ri, rci, ps, rfl⟩ := hw + refine tri_getV_pin ?_ + extract_lets entry + refine Tri.bind tri_setV_eq fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.note _)) fun _ => ?_ + refine Tri.getV_bind fun y => ?_ + refine Tri.ite (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) fun _ => ?_ + exact Tri.conseq (hV _ _ ⟨_, _, _, pg⟩) (fun _ _ p => p.1) fun _ _ _ q => q + refine Tri.ite (fun hs => ?_) (fun hs => ?_) + · obtain ⟨rfl, rfl⟩ := G.sigPlain hs + subst hs + rw [M.newE_none S] at hP ⊢ + have h6 : Tri env (Stage env u o1 [] (cfgsOf u none) (rcsOf u []) []) (jp6 ()) + fun _ => FlushGhost env node v0 cl0 := by + refine Tri.bind (Q := fun _ => Stage env u o1 [index] (cfgsOf u none) (rcsOf u []) []) + (Tri.setV fun w o ⟨hw, rcw, added, eo⟩ => ⟨hw.commit _, rcw, added, eo⟩) fun _ => ?_ + refine Tri.bind (Q := fun _ => Stage env u o1 [index] (cfgsOf u none) (rcsOf u []) []) ?_ fun r => ?_ + · unfold startTickingIfNecessary + refine Tri.setV fun w o ⟨hw, rcw, added, eo⟩ => ?_ + split + · exact ⟨hw.tick, rcw, added, eo⟩ + · exact ⟨hw, rcw, added, eo⟩ + · cases r + exact Tri.conseq hP (fun _ _ p => p) fun _ _ _ q => q + refine Tri.getV_bind fun x => ?_ + refine Tri.ite (fun _ => ?_) (fun _ => Tri.conseq h6 (fun _ _ p => p.1) fun _ _ _ q => q) + refine tri_pin fun X O ⟨st, _⟩ => ?_ + refine Tri.bind becomeSigned_tri fun r => ?_ + cases r + refine Tri.conseq h6 (fun w o ⟨e1, e2⟩ => ?_) fun _ _ _ q => q + subst e1 e2 + obtain ⟨hw, rcw, added, eo⟩ := st + exact ⟨hw.signed _, rfl, added, eo⟩ + · simp only [Bool.not_eq_true] at hs + subst hs + exact Tri.conseq hP (fun _ _ p => p) fun _ _ _ q => q + have h1 : (retired ≠ [] -> env.names.set retired + ⊆ (abs env.names u).retirementCompletedNodes \ retiredCommittedNodes (abs env.names u).log) + -> Tri env (fun w o => w = { u with rcEntries := u.rcEntries ++ rcsOf u retired } /\ o = o1) + (jp1 ()) + fun _ => FlushGhost env node v0 cl0 := by + intro hrc + refine Tri.bind (Tri.keeps Spec.lookFn) fun l => ?_ + refine Tri.ite (fun _ => ?_) (fun _ => ?_) + · refine tri_pin fun X O ⟨eX, eO⟩ => ?_ + subst eX eO + refine Tri.bind (addConfiguration_tri (X := { u with rcEntries := u.rcEntries ++ rcsOf u retired }) (M.leader S) + ⟨vhU.size, vhU.sorted, vhU.positive, vhU.leLast, vhU.terms, vhU.posTerms⟩ rcU ndU) + fun nodes => ?_ + extract_lets ids1 cfg1 jpC jp3 + refine Tri.ite (fun hd => ?_) (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + refine tri_names_bind ?_ + extract_lets + refine Tri.ite (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) (fun hne => ?_) + refine Tri.ite (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) (fun hlat => ?_) + refine Tri.ite (fun hb => ?_) (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + have hset : env.names.set ids1 = env.names.set (nodes.map Prod.fst) := + names_set_congr (sortDedup_spec (nodes.map Prod.fst)).2 + have hcfg : forall ns, some nodes = some ns -> (ns.map Prod.fst).Nodup /\ ns ≠ [] + /\ env.names.set (ns.map Prod.fst) + ≠ latestConfigurationMembers (configurationHistory (abs env.names u).log) + /\ forall a, a ∈ ns -> env.names.id a.1 ∉ removedNodes (abs env.names u).log := by + rintro _ ⟨⟩ + refine ⟨ReplUpdateCommit.nodup_of_eraseDups_eq (beq_iff_eq.mp hd), ?_, + fun h => hlat (decide_eq_true (hset.trans h)), fun a ma hr => ?_⟩ + · rintro rfl + exact hne (by simp [ids1]) + · exact List.filter_eq_nil_iff.mp (List.isEmpty_iff.mp hb) a.1 + (((sortDedup_spec _).2 _).mpr (List.mem_map_of_mem ma)) (decide_eq_true hr) + refine Tri.conseq (h2 hrc (some nodes) hcfg) (fun w o ⟨Y, hY, post⟩ => ?_) fun _ _ _ q => q + rcases post with ⟨hl, -, -⟩ | ⟨ps, rfl, added, rfl⟩ + · exact (hlat (decide_eq_true (hset.trans (M.latest_of_last hl)))).elim + · rcases hY with rfl | rfl + · exact ⟨⟨u.ticking, u.retired, u.retirementPhase, u.retirementIdx, + u.retirementCommittableIdx, ps, by simp [cfgsOf, index]⟩, rcU, added, rfl⟩ + · exact ⟨⟨u.ticking, true, some Phase.ordered, some index, + u.retirementCommittableIdx, ps, by simp [cfgsOf, index]⟩, rfl, added, rfl⟩ + · exact Tri.conseq (h2 hrc none fun _ h => by cases h) + (fun w o ⟨eW, eO⟩ => ⟨⟨u.ticking, u.retired, u.retirementPhase, u.retirementIdx, + u.retirementCommittableIdx, u.allOtherNodes, by rw [eW]; simp [cfgsOf]⟩, + by rw [eW]; exact rcU, by rw [M.newE_none S, eW]; exact added_nil ndU, + by rw [M.newE_none S, eO]; simp⟩) fun _ _ _ q => q + refine Tri.ite (fun hne0 => ?_) (fun he => ?_) + · refine tri_names_bind ?_ + extract_lets a + refine Tri.ite (fun hrcd => ?_) (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + have ne : retired.isEmpty = false := by simpa using hne0 + refine Tri.bind (Q := fun _ w o => w = { u with rcEntries := u.rcEntries ++ rcsOf u retired } + /\ o = o1) + (Tri.setV fun w o p => ⟨by rw [p.1]; simp [rcsOf, ne, index], p.2⟩) fun r => ?_ + cases r + exact h1 fun _ => of_decide_eq_true hrcd + · have hr : retired = [] := by simpa using he + exact Tri.conseq (h1 fun h => absurd hr h) (fun w o p => ⟨by rw [p.1, hr]; simp [rcsOf], p.2⟩) + fun _ _ _ q => q + +/-- Before the batch, or after some of its entries. -/ +def Loop (env : Env) (node : NodeID) (v0 : State) (cl0 : NodeState) (v : State) + (o : Outbox) + : Prop := + (v = v0 /\ o = []) \/ FlushGhost env node v0 cl0 v o + +theorem batch_start (S : Start env.names node v0 cl0) : Batch env node v0 cl0 v0 [] := + ⟨[], cl0, emits_pure _, Mid.start S, by simp⟩ + +theorem Loop.batch (S : Start env.names node v0 cl0) {v : State} {o : Outbox} + (h : Loop env node v0 cl0 v o) + : Batch env node v0 cl0 v o := by + rcases h with ⟨rfl, rfl⟩ | ⟨es, c, fl, g⟩ + · exact batch_start S + · exact ⟨_, g⟩ + +theorem entries_tri (S : Start env.names node v0 cl0) + : forall n, Pres env (Loop env node v0 cl0) (replicateEntries n) + | 0 => by + unfold replicateEntries + exact Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail _ + | n + 1 => by + unfold replicateEntries + refine Tri.bind (Tri.keeps Spec.lookFn) fun _ => Tri.ite (fun _ => ?_) fun _ => Pres.pure _ + exact Tri.bind (Tri.conseq (entry_tri S) (fun _ _ p => p.batch S) fun _ _ _ q => Or.inr q) + fun _ => entries_tri S n + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplFlush.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplFlush.lean new file mode 100644 index 000000000000..28b1bc1d3e9f --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplFlush.lean @@ -0,0 +1,326 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplMid +public import Consensus.TraceValidation.Proofs.Handlers.ReplEmits + +@[expose] public section + +/-! +# One `send_append_entries_range` in a batch (not reviewed; `Replicate` obligation) + +A range sent during a batch (a flush, or a new peer's heartbeat) is the clean `sendEntries` +to that peer and range from the batch's clean state, keeps `Mid`, and sends an envelope +satisfying `msgInv` (after the `Tick` proof's `hb_step` and `msgInv_hb`, with `Mid`'s facts +in place of `inv`). +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees trackedPeers inv msgInv UnnamedUnmatched) +open Consensus.TraceValidation.Proofs.Ae +open ReplUpdateCommit (Named named_inj Hyps) + +variable {names : Names} {node : NodeID} {v0 : State} {cl0 : NodeState} + +theorem viewAt_zero_vh {v : State} (vh : ViewHyps v) : v.viewAt 0 = 0 := by + simp only [State.viewAt, List.length_eq_zero_iff, List.filter_eq_nil_iff] + intro x hx + have := vh.positive x hx + simp only [Nat.le_zero, decide_eq_true_eq] + omega + +theorem getTerm_vh {v : State} (vh : ViewHyps v) (i : Nat) + : v.getTerm i = termAt (abs names v).log i := by + rw [termAt_abs vh.size] + unfold State.getTerm + by_cases hi : i = 0 + · subst hi; simp [viewAt_zero_vh vh] + · by_cases hl : i > v.lastIdx + · have : v.ledger[i - 1]? = none := by simp [vh.size]; omega + simp [hl, hi, this] + · simp only [hl, hi, ite_false] + rw [vh.terms i (by omega) (by omega)]; rfl + +theorem messageEntries_abs {v : State} (size : v.ledger.size = v.lastIdx) + (prev endIdx : Nat) (eL : endIdx <= v.lastIdx) + : messageEntries (abs names v).log prev endIdx + = (List.range' (prev + 1) (endIdx - prev)).map + fun i => absEntry names v.ledger[i - 1]! := by + unfold messageEntries + apply List.ext_getElem + · simp [abs, size] + omega + · intro j h1 h2 + simp only [List.length_map, List.length_range'] at h2 + simp only [abs, List.getElem_take, List.getElem_drop, List.getElem_map, + List.getElem_range', Array.getElem_toList] + congr 1 + have lt : prev + 1 + j - 1 < v.ledger.size := by rw [size]; omega + rw [Nat.one_mul, getElem!_pos v.ledger _ lt] + congr 1 + omega + +theorem names_set_round_trip {l : List NodeId} (named : forall x, x ∈ l -> Named names x) + : forall i, i ∈ names.set l -> names.id (names.name i) = i := by + intro i mem + simp only [Names.set, CCF.Finset.mem_ofList, List.mem_map] at mem + obtain ⟨x, mem, rfl⟩ := mem + rw [named x mem] + +/-- The entries of a range in one view. -/ +theorem range_entry {v : State} (vh : ViewHyps v) {prev endIdx : Nat} + (eL : endIdx <= v.lastIdx) + (same : forall i, prev < i -> i <= endIdx -> v.viewAt i = v.viewAt endIdx) + : forall i, + prev + 1 <= i + -> i <= endIdx + -> v.ledger[i - 1]! ∈ v.ledger.toList + /\ v.ledger[i - 1]!.term = v.viewAt endIdx := by + intro i i1 iE + have lt : i - 1 < v.ledger.size := by rw [vh.size]; omega + rw [getElem!_pos v.ledger _ lt] + refine ⟨by simp, ?_⟩ + have t := vh.terms i (by omega) (by omega) + rw [Array.getElem?_eq_getElem lt] at t + simp only [Option.map_some, Option.some.injEq] at t + rw [t] + exact same i (by omega) iE + +theorem Mid.self (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : names.id v.nodeId = node := by + rw [M.frame.nodeId, S.self] + +theorem Mid.leader (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : v.leadership = .leader := + M.frame.leadership.trans S.leader + +theorem msgInv_range (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) {to : NodeId} (ne : node ≠ names.id to) + {prev endIdx : Nat} (pL : prev <= v.lastIdx) (e1 : prev <= endIdx) + (eL : endIdx <= v.lastIdx) + (same : forall i, prev < i -> i <= endIdx -> v.viewAt i = v.viewAt endIdx) + : msgInv names + ⟨ + node, + names.id to, + .appendEntriesRequest (rangeRequest names v (prev + 1) endIdx) + ⟩ + = true := by + have hy := M.hy + have vh := M.vh + have entry := range_entry vh eL same + unfold msgInv rangeRequest + simp only [Bool.and_eq_true, beq_iff_eq, bne_iff_ne, ne_eq, List.all_eq_true, List.mem_map, + List.mem_range'_1, forall_exists_index, and_imp, decide_eq_true_eq, Bool.or_eq_true] + refine ⟨⟨⟨⟨?_, ?_⟩, ?_⟩, ?_, ?_⟩, ?_⟩ + · rw [← M.self S, hy.selfNamed] + · exact ne + · intro x i i1 iE xe y mem + subst xe + obtain ⟨inLedger, -⟩ := entry i i1 (by omega) + have all := M.ledgerNamed _ inLedger + simp only [absEntry] at mem + split at mem + · simp [EntryContent.metadata, CCF.Finset.notMem_empty] at mem + · simp only [EntryContent.metadata, List.mem_append, CCF.Finset.mem_sort] at mem + rcases mem with mem | mem + · cases hc : v.ledger[i - 1]!.config with + | none => simp [hc] at mem + | some ns => + simp only [hc, Option.map_some, Option.getD_some, CCF.Finset.mem_sort] at mem + exact names_set_round_trip + (fun x m => all x (List.mem_append_left _ (by simpa [hc] using m))) y mem + · exact names_set_round_trip (fun x m => all x (List.mem_append_right _ m)) y mem + · intro x i i1 iE xe + subst xe + obtain ⟨inLedger, term⟩ := entry i i1 (by omega) + have pos := vh.posTerms _ inLedger + have last : endIdx + 1 - (prev + 1) = (endIdx - prev - 1) + 1 := by omega + refine ⟨⟨?_, ?_⟩, ?_⟩ + · rw [last, List.range'_1_concat, List.map_append, List.getLast?_append] + simp only [List.map_cons, List.map_nil, List.getLast?_singleton, Option.some_or, + Option.map_some, absEntry, Option.some.injEq] + rw [term, (entry _ (by omega) (by omega)).2] + · simpa [absEntry] using pos + · simp only [absEntry] + rw [term] + exact Nat.le_trans (ReplUpdateCommit.viewAt_le_size _ _) hy.viewsBounded + · rcases Nat.eq_zero_or_pos prev with z | z + · exact Or.inl (by simp [z]) + · refine Or.inr ?_ + simp only [Nat.add_sub_cancel, State.getTerm] + split + · omega + · exact viewAt_pos vh z pL + · intro x i _ _ xe + subst xe + simp only [absEntry] + split + · rename_i h + split at h <;> simp_all + · rfl + +/-- `Hyps` does not read the peers but for their names. -/ +theorem hyps_withPeers {v : State} (h : Hyps names v) {L : List (NodeId × Peer)} + (named : forall p, p ∈ L -> Named names p.1) + : Hyps names { v with allOtherNodes := L } := + ⟨ + h.size, + h.commitLe, + h.committable, + h.terms, + h.viewsBounded, + h.configs, + h.selfNamed, + named, + h.membersNamed, + h.distinct + ⟩ + +theorem viewHyps_withPeers {v : State} (h : ViewHyps v) (L : List (NodeId × Peer)) + : ViewHyps { v with allOtherNodes := L } := + ⟨h.size, h.sorted, h.positive, h.leLast, h.terms, h.posTerms⟩ + +theorem setPeer_eq (v : State) (id : NodeId) (p : Peer) + : v.setPeer id p = { v with allOtherNodes := (v.setPeer id p).allOtherNodes } := + rfl + +/-- +One range to the peer `to` during the batch is the clean `sendEntries` to it, keeps `Mid`, +and sends an envelope satisfying `msgInv`. +-/ +theorem range_step (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) {to : NodeId} {p : Peer} + (found : v.peer? to = some p) {endIdx : Nat} (e1 : p.sentIdx <= endIdx) + (eL : endIdx <= v.lastIdx) + (same : forall i, p.sentIdx < i -> i <= endIdx -> v.viewAt i = v.viewAt endIdx) + : Emits (sendEntries (CCF.Capabilities.record node) node cl (names.id to) endIdx) + { cl with sentIndex := CCF.Function.update cl.sentIndex (names.id to) endIdx } + [⟨ + node, + names.id to, + .appendEntriesRequest (rangeRequest names v (p.sentIdx + 1) endIdx) + ⟩] + /\ Mid names node v0 cl0 + { cl with sentIndex := CCF.Function.update cl.sentIndex (names.id to) endIdx } + (v.setPeer to { p with sentIdx := endIdx }) + /\ msgInv names + ⟨ + node, + names.id to, + .appendEntriesRequest (rangeRequest names v (p.sentIdx + 1) endIdx) + ⟩ + = true := by + obtain ⟨f, rfl, P⟩ := M.clean + have hy := M.hy + have vh := M.vh + obtain ⟨fto, pL, -⟩ := P.rel to p found + have key : to ∈ v.allOtherNodes.map Prod.fst := + mem_keys.mpr ⟨p, (lookup_iff_mem P.nodup).mp found⟩ + have elig : names.id to ∈ eligiblePeers { cl0 with log := (abs names v).log, sentIndex := f } + node := (M.eligible _).mpr ⟨to, key, rfl⟩ + have ne : node ≠ names.id to := by + intro e + unfold eligiblePeers at elig + rw [← e, CCF.Finset.mem_erase] at elig + exact elig.1 rfl + have hrole : cl0.role = .primary := S.role + have hterm : cl0.currentTerm = v.currentView := by + rw [M.frame.view, S.cleanEq]; rfl + have hcommit : cl0.commitIndex = v.commitIdx := by rw [M.frame.commit, S.commit] + have hrc : Not (({ cl0 with log := (abs names v).log, sentIndex := f } : NodeState).isRetiredCommitted + node) := not_rc_of_rci (c := { cl0 with log := (abs names v).log, sentIndex := f }) S.cleanRci node + have entry := range_entry vh eL same + have endTerm : termAt (abs names v).log endIdx = v.viewAt endIdx := by + rw [← getTerm_vh vh] + unfold State.getTerm + split + · omega + · rfl + have entries : messageEntries (abs names v).log p.sentIdx endIdx + = (List.range' (p.sentIdx + 1) (endIdx + 1 - (p.sentIdx + 1))).map + fun i => absEntry names v.ledger[i - 1]! := by + rw [messageEntries_abs vh.size _ _ eL] + congr 2 + omega + refine ⟨?_, ?_, msgInv_range S M ne pL e1 eL same⟩ + · have msg : makeAppendEntriesRequest { cl0 with log := (abs names v).log, sentIndex := f } + (names.id to) endIdx = rangeRequest names v (p.sentIdx + 1) endIdx := by + simp only [makeAppendEntriesRequest, rangeRequest, fto, hterm, hcommit, entries, + Nat.add_sub_cancel, getTerm_vh (names := names) vh] + unfold sendEntries + refine emits_congr + (emits_bind (emits_guard ?_) (emits_bind (emits_send _ _) (emits_pure _))) rfl ?_ + · refine ⟨hrole, elig, by simp [fto, e1], ?_, ?_, Or.inl hrc⟩ + · show endIdx <= (abs names v).log.length + rw [ReplUpdateCommit.abs_log_length vh.size] + exact eL + · show ((messageEntries (abs names v).log (f (names.id to)) endIdx).all + fun entry => entry.term == termAt (abs names v).log endIdx) = true + rw [fto, entries, endTerm] + simp only [List.all_eq_true, List.mem_map, List.mem_range'_1, beq_iff_eq, + forall_exists_index, and_imp] + intro x i i1 iE xe + subst xe + simp only [absEntry] + exact (entry i i1 (by omega)).2 + · simp only [List.nil_append, List.append_nil] + rw [msg] + · have nd' := setPeer_nodup P.nodup to { p with sentIdx := endIdx } + have keys : forall k, k ∈ (v.setPeer to { p with sentIdx := endIdx }).allOtherNodes.map Prod.fst + <-> k ∈ v.allOtherNodes.map Prod.fst := by + intro k + rw [setPeer_keys] + constructor + · rintro (rfl | h) + · exact key + · exact h + · exact Or.inr + have named : forall q, q ∈ (v.setPeer to { p with sentIdx := endIdx }).allOtherNodes + -> Named names q.1 := by + intro q mem + obtain ⟨q', mem'⟩ := mem_keys.mp ((keys q.1).mp (List.mem_map_of_mem mem)) + exact hy.peersNamed (q.1, q') mem' + rw [setPeer_eq] + refine ⟨by frame_step M.frame, M.notRC, hyps_withPeers hy named, viewHyps_withPeers vh _, M.unconf, + M.ledgerNamed, + ⟨CCF.Function.update f (names.id to) endIdx, rfl, nd', fun k q lk => ?_⟩, ?_, M.isPrefix, + M.rcRemoved, M.confRemoved, M.removedMono, M.cfgNew⟩ + · rw [← setPeer_eq, setPeer_lookup P.nodup] at lk + split at lk + · rename_i e + subst e + simp only [Option.some.injEq] at lk + subst lk + obtain ⟨-, -, m⟩ := P.rel k p found + exact ⟨by simp [CCF.Function.update], eL, m⟩ + · rename_i e + obtain ⟨fk, qL, m⟩ := P.rel k q lk + have keyk : k ∈ v.allOtherNodes.map Prod.fst := + mem_keys.mpr ⟨q, (lookup_iff_mem P.nodup).mp lk⟩ + obtain ⟨qk, memk⟩ := mem_keys.mp keyk + obtain ⟨qt, memt⟩ := mem_keys.mp key + have ne : names.id k ≠ names.id to := fun eq => + e (named_inj (hy.peersNamed _ memk) (hy.peersNamed _ memt) eq) + refine ⟨?_, qL, m⟩ + simp only [CCF.Function.update, ne, ↓reduceIte] + exact fk + · intro n + refine (iff_of_eq (congrArg (n ∈ ·) (Ae.eligiblePeers_congr + (b := { cl0 with log := (abs names v).log, sentIndex := f }) (by rfl) (by rfl) node))).trans + ?_ + rw [M.eligible n, ← setPeer_eq] + constructor + · rintro ⟨k, mem, rfl⟩ + exact ⟨k, (keys k).mpr mem, rfl⟩ + · rintro ⟨k, mem, rfl⟩ + exact ⟨k, (keys k).mp mem, rfl⟩ + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplMid.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplMid.lean new file mode 100644 index 000000000000..f78363d84361 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplMid.lean @@ -0,0 +1,382 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplPeers + +@[expose] public section + +/-! +# The batch relation (not reviewed; `Replicate` obligation) + +During a `replicate` hold the declared state `v` and the clean state `cl` reached by the +entries seen so far are related by `Mid`: `v` keeps every field `abs` reads but the ledger +and the peers, `cl` is the starting clean state with the declared log and new send +indexes, the declared peers are the clean eligible peers, each with its clean send index +and the starting clean match index, and `v` satisfies the facts `update_commit` and +`send_append_entries` need (`Hyps`, `ViewHyps`). +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees trackedPeers inv UnnamedUnmatched) +open Consensus.TraceValidation.Proofs.Ae +open ReplUpdateCommit (Named named_inj Hyps) + +/-- The declared fields `abs` reads, other than the ledger and the peers, are `v0`'s. -/ +structure Frame (v0 v : State) : Prop where + nodeId : v.nodeId = v0.nodeId + view : v.currentView = v0.currentView + commit : v.commitIdx = v0.commitIdx + leadership : v.leadership = v0.leadership + newFollower : v.isNewFollower = v0.isNewFollower + votedFor : v.votedFor = v0.votedFor + leaderId : v.leaderId = v0.leaderId + votes : v.votesForMe = v0.votesForMe + rci : v.retiredCommittedIdx = v0.retiredCommittedIdx + +/-- Re-establishes `Frame` across an update that keeps its fields definitionally. -/ +macro "frame_step " h:term:max : tactic => + `(tactic| exact ⟨($h).nodeId, ($h).view, ($h).commit, ($h).leadership, ($h).newFollower, + ($h).votedFor, ($h).leaderId, ($h).votes, ($h).rci⟩) + +/-- What the batch keeps of the starting declared and clean states. -/ +structure Start (names : Names) (node : NodeID) (v0 : State) (cl0 : NodeState) + : Prop where + inv : inv names v0 = true + agrees : agrees names cl0 v0 = true + um : UnnamedUnmatched node cl0 + self : names.id v0.nodeId = node + leader : v0.leadership = .leader + notRC : v0.isRetiredCommitted = false + rci : v0.retiredCommittedIdx = none + +/-- The declared peers against the clean send indexes `f` and starting match indexes. -/ +structure PeerRel (names : Names) (cl0 : NodeState) (f : NodeID -> Nat) (v : State) + : Prop where + nodup : (v.allOtherNodes.map Prod.fst).Nodup + rel + : forall k p, + v.peer? k = some p + -> f (names.id k) = p.sentIdx + /\ p.sentIdx <= v.lastIdx + /\ cl0.matchIndex (names.id k) = p.matchIdx + +/-- The batch relation. -/ +structure Mid (names : Names) (node : NodeID) (v0 : State) (cl0 : NodeState) + (cl : NodeState) (v : State) + : Prop where + frame : Frame v0 v + notRC : v.isRetiredCommitted = false + hy : Hyps names v + vh : ViewHyps v + unconf : v.lastIdx = 0 -> v.configurations = [] + ledgerNamed + : forall e, + e ∈ v.ledger.toList + -> forall id, id ∈ (e.config.getD []).map Prod.fst ++ e.retired -> Named names id + clean + : exists f, + cl = { cl0 with log := (abs names v).log, sentIndex := f } + /\ PeerRel names cl0 f v + eligible + : forall n, + n ∈ eligiblePeers cl node + <-> exists k, k ∈ v.allOtherNodes.map Prod.fst /\ names.id k = n + isPrefix : cl0.log <+: (abs names v).log + rcRemoved + : forall e, + e ∈ v.rcEntries + -> forall id, id ∈ e.2 -> names.id id ∈ removedNodes (abs names v0).log + confRemoved + : forall j x, + v0.commitIdx <= j + -> (abs names v).log[j]? = some x + -> forall n, + n ∈ x.content.metadata.retirementConfirmations + -> n ∈ removedNodes (abs names v0).log + removedMono + : forall n, n ∈ removedNodes (abs names v0).log -> n ∈ removedNodes (abs names v).log + cfgNew + : exists new, + v.configurations = v0.configurations ++ new + /\ forall c, + c ∈ new + -> forall a, a ∈ c.nodes -> names.id a.1 ∉ removedNodes (abs names v0).log + +variable {names : Names} {node : NodeID} {v0 : State} {cl0 : NodeState} + +theorem Start.cleanEq (S : Start names node v0 cl0) + : cl0 + = { + abs names v0 with + sentIndex := cl0.sentIndex, + matchIndex := cl0.matchIndex, + votesGranted := cl0.votesGranted, + preVotesGranted := cl0.preVotesGranted + } := + agrees_eq S.agrees + +theorem Start.log (S : Start names node v0 cl0) : cl0.log = (abs names v0).log := by + rw [S.cleanEq] + +theorem Start.commit (S : Start names node v0 cl0) : cl0.commitIndex = v0.commitIdx := by + rw [S.cleanEq]; rfl + +theorem Start.role (S : Start names node v0 cl0) : cl0.role = .primary := by + rw [S.cleanEq]; simp [abs, S.leader, Consensus.TraceValidation.absRole] + +theorem Start.cleanRci (S : Start names node v0 cl0) + : cl0.retiredCommittedIndex = none := by + rw [S.cleanEq]; simp [abs, S.rci] + +/-- A clean state without a latched confirmation is not retired-committed. -/ +theorem not_rc_of_rci {c : NodeState} (h : c.retiredCommittedIndex = none) (n : NodeID) + : Not (c.isRetiredCommitted n) := by + unfold NodeState.isRetiredCommitted NodeState.retirement + simp only [h, Option.isSome_none, Bool.false_eq_true, ite_false] + split + · simp + · repeat' split + all_goals simp + +/-- The tracked peers of a declared leader are its peers' clean ids. -/ +theorem tracked_iff {v : State} (leader : v.leadership = .leader) {n : NodeID} + : n ∈ trackedPeers names v + <-> exists k p, (k, p) ∈ v.allOtherNodes /\ names.id k = n := by + simp only [trackedPeers, leader, beq_self_eq_true, ite_true, List.mem_map] + constructor + · rintro ⟨⟨k, p⟩, mem, rfl⟩ + exact ⟨k, p, mem, rfl⟩ + · rintro ⟨k, p, mem, rfl⟩ + exact ⟨(k, p), mem, rfl⟩ + +theorem eligible_of_log_nil {c : NodeState} (h : c.log = []) (self n : NodeID) + : n ∉ eligiblePeers c self := by + intro mem + unfold eligiblePeers NodeState.activeMembers NodeState.retirementCompletedNodes + NodeState.activeConfigurations NodeState.committedLog at mem + rw [h] at mem + simp [CCF.Finset.mem_erase, CCF.Finset.mem_union, CCF.Finset.mem_sdiff, configurationHistory, + activeConfigurations, configurationMembers, CCF.Finset.notMem_empty] at mem + +theorem mem_members_iff {cs : List Configuration} {n : NodeID} + : n ∈ configurationMembers cs <-> exists x, x ∈ cs /\ n ∈ x.nodes := by + refine ⟨ + fun h => ?_, + fun ⟨x, mem, member⟩ => ReplUpdateCommit.mem_configurationMembers mem member + ⟩ + unfold configurationMembers at h + have general : forall (cs : List Configuration) (acc : CCF.Finset NodeID), + n ∈ cs.foldl (fun nodes configuration => nodes ∪ configuration.nodes) acc + -> n ∈ acc \/ exists x, x ∈ cs /\ n ∈ x.nodes := by + intro cs + induction cs with + | nil => exact fun _ h => Or.inl h + | cons y ys ih => + intro acc h + rcases ih _ h with h | ⟨x, mem, member⟩ + · rcases CCF.Finset.mem_union.mp h with h | h + · exact Or.inl h + · exact Or.inr ⟨y, List.mem_cons_self, h⟩ + · exact Or.inr ⟨x, List.mem_cons_of_mem _ mem, member⟩ + rcases general cs ∅ h with h | h + · exact absurd h (CCF.Finset.notMem_empty _) + · exact h + +theorem history_prefix (l1 l2 : List Consensus.Model.Node.Entry) + : configurationHistory l1 <+: configurationHistory (l1 ++ l2) := by + unfold configurationHistory + rw [List.zipIdx_append, List.filterMap_append] + exact List.prefix_append _ _ + +theorem members_prefix {l1 l2 : List Consensus.Model.Node.Entry} (h : l1 <+: l2) + {n : NodeID} (mem : n ∈ configurationMembers (configurationHistory l1)) + : n ∈ configurationMembers (configurationHistory l2) := by + obtain ⟨t, rfl⟩ := h + obtain ⟨x, mem, member⟩ := mem_members_iff.mp mem + exact mem_members_iff.mpr ⟨x, (history_prefix l1 t).subset mem, member⟩ + +theorem Mid.start (S : Start names node v0 cl0) : Mid names node v0 cl0 cl0 v0 := by + have invS := S.inv + have hy := Hyps.ofInv invS + have unconf : (v0.lastIdx != 0 || v0.leadership != .leader || v0.configurations.isEmpty) + = true := by + inv_conj invS "empty_leader_unconfigured" + have ledgerNamed : (v0.ledger.all fun e => + ((e.config.getD []).map Prod.fst ++ e.retired).all + fun id => names.name (names.id id) == id) = true := by + inv_conj invS "ledger_names_round_trip" + have bounds : (v0.leadership != .leader + || v0.allOtherNodes.all fun (_, p) => p.sentIdx <= v0.lastIdx && p.matchIdx <= v0.lastIdx) + = true := by + inv_conj invS "peer_bounds" + simp only [S.leader, bne_self_eq_false, Bool.false_or, Bool.or_false, List.all_eq_true, + Bool.and_eq_true, decide_eq_true_eq] at bounds unconf + have peers : forall k, k ∈ v0.allOtherNodes.map Prod.fst + -> (v0.allOtherNodes.map Prod.fst).Nodup := by + intro k mem + by_cases z : v0.lastIdx = 0 + · have alone : (v0.lastIdx != 0 || v0.leadership != .leader || v0.allOtherNodes.isEmpty) + = true := by + inv_conj invS "empty_leader_alone" + simp only [z, S.leader, bne_self_eq_false, Bool.false_or, List.isEmpty_iff] at alone + simp [alone] at mem + · have hp : (v0.lastIdx == 0 || v0.leadership == .none + || v0.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names v0) (names.id v0.nodeId)).sort) = true := by + inv_conj invS "peers" + simp only [z, S.leader, beq_iff_eq, Bool.or_eq_true, reduceCtorEq, false_or] at hp + have mapEq : (v0.allOtherNodes.map Prod.fst).map names.id + = (eligiblePeers (abs names v0) (names.id v0.nodeId)).sort := by + rw [← hp, List.map_map] + rfl + refine List.Pairwise.of_map (S := fun x y : NodeID => x ≠ y) names.id + (fun a b h e => h (e ▸ rfl)) ?_ + rw [mapEq] + exact CCF.Finset.nodup_of_sorted (eligiblePeers _ _).sorted + have nodup : (v0.allOtherNodes.map Prod.fst).Nodup := by + cases h : v0.allOtherNodes with + | nil => simp + | cons q l => exact h ▸ peers q.1 (by simp [h]) + have rcRemoved : forall e, e ∈ v0.rcEntries -> forall id, id ∈ e.2 + -> names.id id ∈ removedNodes (abs names v0).log := by + have e : (v0.leadership != .leader + || v0.rcEntries.all fun (x : Nat × List NodeId) => x.2.all fun id => + decide (names.id id ∈ removedNodes (abs names v0).log)) = true := by + inv_conj invS "rc_entries_removed" + simp only [S.leader, bne_self_eq_false, Bool.false_or, List.all_eq_true, + decide_eq_true_eq] at e + exact e + have rcs : (v0.rcEntries + == (List.range' (v0.commitIdx + 1) (v0.lastIdx - v0.commitIdx)).filterMap + fun i => v0.ledger[i - 1]?.bind + fun e => if e.retired.isEmpty then none else some (i, e.retired)) = true := by + inv_conj invS "rc_entries" + rw [beq_iff_eq] at rcs + refine ⟨ + ⟨rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl, rfl⟩, + S.notRC, + hy, + ViewHyps.ofInv invS, + fun z => by simpa [z] using unconf, + ?_, + ?_, + ?_, + by rw [S.log]; exact List.prefix_refl _, + rcRemoved, + ?_, + fun _ h => h, + ⟨[], by simp, by simp⟩ + ⟩ + · intro e mem id idMem + have := (List.all_eq_true.mp (Array.all_eq_true_iff_forall_mem.mp ledgerNamed e + (Array.mem_def.mpr mem))) id idMem + simpa using this + · refine ⟨cl0.sentIndex, ?_, nodup, fun k p found => ?_⟩ + · rw [← S.log] + have mem := (lookup_iff_mem nodup).mp found + refine ⟨?_, (bounds _ mem).1, ?_⟩ + · have named := hy.peersNamed _ mem + rw [← abs_sentIndex hy.peersNamed named found] + have ag := S.agrees + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at ag + exact (ag.1.1.1.1.1.1.2 _ ((tracked_iff S.leader).mpr ⟨k, p, mem, rfl⟩)).1 + · have named := hy.peersNamed _ mem + rw [← ReplUpdateCommit.abs_matchIndex hy.peersNamed named found] + have ag := S.agrees + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at ag + exact (ag.1.1.1.1.1.1.2 _ ((tracked_iff S.leader).mpr ⟨k, p, mem, rfl⟩)).2 + · intro n + by_cases z : v0.lastIdx = 0 + · have alone : (v0.lastIdx != 0 || v0.leadership != .leader || v0.allOtherNodes.isEmpty) + = true := by + inv_conj invS "empty_leader_alone" + simp only [z, S.leader, bne_self_eq_false, Bool.false_or, List.isEmpty_iff] at alone + have logNil : cl0.log = [] := by + rw [S.log] + simp [abs, z] + simp only [alone, List.map_nil, List.not_mem_nil, false_and, exists_false, iff_false] + exact eligible_of_log_nil logNil _ _ + · have hp : (v0.lastIdx == 0 || v0.leadership == .none + || v0.allOtherNodes.map (fun (id, _) => names.id id) + == (eligiblePeers (abs names v0) (names.id v0.nodeId)).sort) = true := by + inv_conj invS "peers" + simp only [z, S.leader, beq_iff_eq, Bool.or_eq_true, reduceCtorEq, false_or] at hp + have congr : eligiblePeers cl0 node = eligiblePeers (abs names v0) (names.id v0.nodeId) := by + rw [S.self] + exact Ae.eligiblePeers_congr S.log S.commit node + have mapEq : (v0.allOtherNodes.map Prod.fst).map names.id + = (eligiblePeers (abs names v0) (names.id v0.nodeId)).sort := by + rw [← hp, List.map_map] + rfl + rw [congr, ← CCF.Finset.mem_sort, ← mapEq, List.mem_map] + · intro j x cj hx n mem + simp only [abs, List.getElem?_map, List.getElem?_take, Option.map_eq_some_iff] at hx + split at hx + · rename_i jL + obtain ⟨e, he, rfl⟩ := hx + have he' : v0.ledger[j]? = some e := by simpa using he + cases hs : e.sig with + | true => simp [absEntry, hs, EntryContent.metadata, CCF.Finset.notMem_empty] at mem + | false => + simp only [absEntry, hs, Bool.false_eq_true, ite_false, EntryContent.metadata, + Names.set, CCF.Finset.mem_ofList, List.mem_map] at mem + obtain ⟨id, mid, rfl⟩ := mem + have ne : e.retired.isEmpty = false := by + cases h : e.retired with + | nil => rw [h] at mid; cases mid + | cons _ _ => rfl + refine rcRemoved (j + 1, e.retired) ?_ id mid + rw [rcs, List.mem_filterMap] + refine ⟨j + 1, List.mem_range'_1.mpr ⟨by omega, by omega⟩, ?_⟩ + have ne' : ¬e.retired = [] := fun z => by rw [z] at ne; cases ne + simp [he', ne'] + · obtain ⟨_, h, _⟩ := hx + cases h + +/-- At the end of the batch the clean state agrees with the declared one. -/ +theorem Mid.finish (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : agrees names cl v = true /\ UnnamedUnmatched node cl := by + obtain ⟨f, rfl, P⟩ := M.clean + have F := M.frame + refine ⟨?_, ?_⟩ + · have ag := S.agrees + have leader : v.leadership = .leader := F.leadership.trans S.leader + simp only [agrees, Bool.and_eq_true, beq_iff_eq, List.all_eq_true] at ag ⊢ + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨a1, a2⟩, a3⟩, a4⟩, -⟩, a6⟩, a7⟩, a8⟩, -⟩, -⟩, a11⟩ := ag + have r1 : (abs names v).role = (abs names v0).role := by simp [abs, F.leadership] + refine ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨?_, ?_⟩, trivial⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩, ?_⟩ + · rw [r1]; exact a1 + · show cl0.currentTerm = v.currentView + rw [F.view]; exact a2 + · show cl0.commitIndex = v.commitIdx + rw [F.commit]; exact a4 + · intro n mem + obtain ⟨k, p, memK, rfl⟩ := (tracked_iff leader).mp mem + have found := (lookup_iff_mem P.nodup).mpr memK + obtain ⟨fk, -, mk⟩ := P.rel k p found + have named := M.hy.peersNamed _ memK + refine ⟨?_, ?_⟩ + · show f (names.id k) = _ + rw [abs_sentIndex M.hy.peersNamed named found, fk] + · show cl0.matchIndex (names.id k) = _ + rw [ReplUpdateCommit.abs_matchIndex M.hy.peersNamed named found, mk] + · show cl0.isNewFollower = v.isNewFollower + rw [F.newFollower]; exact a6 + · show cl0.votedFor = v.votedFor.map names.id + rw [F.votedFor]; exact a7 + · show cl0.primaryKnown = v.leaderId.isSome + rw [F.leaderId]; exact a8 + · simp [abs, leader, Consensus.TraceValidation.absRole] + · simp [abs, leader, Consensus.TraceValidation.absRole] + · show cl0.retiredCommittedIndex = v.retiredCommittedIdx + rw [F.rci]; exact a11 + · intro role n ne notMem + exact S.um S.role n ne fun mem => notMem (members_prefix M.isPrefix mem) + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeerSend.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeerSend.lean new file mode 100644 index 000000000000..13b871bdb74d --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeerSend.lean @@ -0,0 +1,99 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplSend +public import Consensus.TraceValidation.Proofs.Handlers.ReplPeers + +@[expose] public section + +/-! +# `send_append_entries` to one peer from its send frontier (not reviewed; `Replicate`) + +From one past a peer's send index, `send_append_entries` sends ranges that each start at the +peer's send index and end within the ledger in one view. Any ghost predicate that each such +range keeps is kept by the whole call. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Life + +variable {env : Env} + +theorem tri_pin {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} + (h : forall v0 o0, P v0 o0 -> Tri env (fun v o => v = v0 /\ o = o0) x Q) + : Tri env P x Q := + fun c a c' e p r => h c.vars c.outbox p c a c' e ⟨rfl, rfl⟩ r + +/-- What a range from the send frontier `p.sentIdx` to `e` requires of `e`. -/ +def RangeOk (v : State) (p : Peer) (e : Nat) : Prop := + p.sentIdx <= e + /\ e <= v.lastIdx + /\ forall i, p.sentIdx < i -> i <= e -> v.viewAt i = v.viewAt e + +/-- The range a peer's send leaves in its send index and outbox. -/ +def rangeEnv (env : Env) (v : State) (to : NodeId) (p : Peer) (e : Nat) + : CCF.Envelope NodeID Message := + ⟨ + env.names.id v.nodeId, + env.names.id to, + .appendEntriesRequest (rangeRequest env.names v (p.sentIdx + 1) e) + ⟩ + +theorem peerSend_tri {to : NodeId} {ext : Bool} {G : State -> Outbox -> Prop} + (base + : forall v o, + G v o + -> ViewHyps v + /\ v.isRetiredCommitted = false + /\ (v.allOtherNodes.map Prod.fst).Nodup) + (step + : forall v o p e, + G v o + -> v.peer? to = some p + -> RangeOk v p e + -> G (v.setPeer to { p with sentIdx := e }) (o ++ [rangeEnv env v to p e])) + {start : Nat} + : Tri env + (fun v o => + G v o + /\ exists p, + v.peer? to = some p /\ start = p.sentIdx + 1 /\ p.sentIdx <= v.lastIdx) + (sendAppendEntries to start ext) fun _ => G := by + refine send_tri (I := fun s v o => G v o /\ exists p, v.peer? to = some p + /\ s = p.sentIdx + 1 /\ p.sentIdx <= v.lastIdx) (fun _ v o h => (base v o h.1).2.1) + (fun s e => ?_) + refine tri_pin fun v0 o0 pre => ?_ + obtain ⟨⟨g, p, found, rfl, pL⟩, ok⟩ := pre + obtain ⟨vh, -, nd⟩ := base _ _ g + have facts : RangeOk v0 p e := by + unfold OkEnd at ok + by_cases hL : p.sentIdx = v0.lastIdx + · rw [hL, maxIdx_past vh] at ok + simp only [gt_iff_lt, Nat.lt_add_one, ite_true] at ok + subst ok + exact ⟨Nat.le_of_eq hL, Nat.le_refl _, fun i h1 h2 => by omega⟩ + · obtain ⟨m1, m2, same⟩ := maxIdx_range vh (start := p.sentIdx + 1) (by omega) (by omega) + have : Not (p.sentIdx + 1 > maxEnd v0 (p.sentIdx + 1)) := by omega + simp only [this, ite_false] at ok + exact ⟨by omega, by omega, fun i h1 h2 => + (same i (by omega) (by omega)).trans (same e (by omega) (by omega)).symm⟩ + refine Tri.conseq (tri_of_hoare (sendRange_spec (o0 := o0) found)) (fun _ _ h => h) + (fun _ v o h => ?_) + obtain ⟨rfl, rfl⟩ := h + have g' := step _ _ _ _ g found facts + refine ⟨fun _ => g', fun ne => ⟨g', { p with sentIdx := e }, ?_, ?_, ?_⟩⟩ + · rw [setPeer_lookup nd] + simp + · simp only [setPeer_lastIdx] at ne ⊢ + have := facts.2.1 + show min (e + 1) v0.lastIdx = e + 1 + omega + · exact facts.2.1 + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeers.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeers.lean new file mode 100644 index 000000000000..049759c2f8c0 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPeers.lean @@ -0,0 +1,275 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplSend + +@[expose] public section + +/-! +# Peer lists and the name table (not reviewed; `Replicate` obligation) + +Peer lookups after `setPeer` (as in the `Tick` proof's `TickPeers`), and the name table's +order: when the table is strictly sorted, `names.id` is strictly monotone on the ids in it, +so a sorted list of node ids maps to the sorted list of their clean ids. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation (Names abs agrees) +open ReplUpdateCommit (Named named_inj) + +/-! ## Peer lists -/ + +theorem lookup_iff_mem {l : List (NodeId × Peer)} (nd : (l.map Prod.fst).Nodup) + {k : NodeId} {p : Peer} + : l.lookup k = some p <-> (k, p) ∈ l := by + induction l with + | nil => simp + | cons q l ih => + obtain ⟨k', p'⟩ := q + simp only [List.map_cons, List.nodup_cons] at nd + by_cases e : k = k' + · subst e + simp only [List.lookup_cons_self, Option.some.injEq, List.mem_cons, Prod.mk.injEq, + true_and] + constructor + · intro h + exact Or.inl h.symm + · rintro (h | h) + · exact h.symm + · exact absurd (List.mem_map_of_mem (f := Prod.fst) h) nd.1 + · have ne : (k == k') = false := by simpa using e + simp only [List.lookup_cons, ne, List.mem_cons, Prod.mk.injEq, e, false_and, false_or] + exact ih nd.2 + +theorem mem_setPeer {v : State} {id k : NodeId} {p q : Peer} + : (k, q) ∈ (v.setPeer id p).allOtherNodes + <-> (k = id /\ q = p) \/ (k ≠ id /\ (k, q) ∈ v.allOtherNodes) := by + simp only [State.setPeer, List.mem_mergeSort, List.mem_append, List.mem_filter, + List.mem_singleton, Prod.mk.injEq, bne_iff_ne, ne_eq] + constructor + · rintro (⟨m, n⟩ | h) + · exact Or.inr ⟨n, m⟩ + · exact Or.inl h + · rintro (h | ⟨n, m⟩) + · exact Or.inr h + · exact Or.inl ⟨m, n⟩ + +theorem setPeer_nodup {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) + (id : NodeId) (p : Peer) + : ((v.setPeer id p).allOtherNodes.map Prod.fst).Nodup := by + simp only [State.setPeer] + refine (((List.mergeSort_perm _ _).map Prod.fst).nodup_iff).mpr ?_ + rw [List.map_append, List.nodup_append] + refine ⟨((List.filter_sublist).map Prod.fst).nodup nd, by simp, ?_⟩ + intro a ha b hb + simp only [List.map_cons, List.map_nil, List.mem_singleton] at hb + subst hb + obtain ⟨x, mem, rfl⟩ := List.mem_map.mp ha + have := (List.mem_filter.mp mem).2 + simpa using this + +theorem setPeer_lookup {v : State} (nd : (v.allOtherNodes.map Prod.fst).Nodup) + (id k : NodeId) (p : Peer) + : (v.setPeer id p).peer? k = if k = id then some p else v.peer? k := by + have nd' := setPeer_nodup nd id p + unfold State.peer? + split + · rename_i e + rw [lookup_iff_mem nd', mem_setPeer] + exact Or.inl ⟨e, rfl⟩ + · rename_i e + apply Option.ext + intro q + rw [lookup_iff_mem nd', lookup_iff_mem nd, mem_setPeer] + constructor + · rintro (⟨h, -⟩ | ⟨-, h⟩) + · exact absurd h e + · exact h + · intro h + exact Or.inr ⟨e, h⟩ + +theorem mem_keys {l : List (NodeId × Peer)} {k : NodeId} + : k ∈ l.map Prod.fst <-> exists q, (k, q) ∈ l := by + simp + +theorem peer_isSome_iff {v : State} {k : NodeId} + : (v.peer? k).isSome <-> k ∈ v.allOtherNodes.map Prod.fst := by + unfold State.peer? + rw [List.lookup_isSome_iff] + simp only [beq_iff_eq, List.mem_map] + constructor + · rintro ⟨q, mem, rfl⟩ + exact ⟨q, mem, rfl⟩ + · rintro ⟨q, mem, rfl⟩ + exact ⟨q, mem, rfl⟩ + +theorem setPeer_keys {v : State} {id k : NodeId} {p : Peer} + : k ∈ (v.setPeer id p).allOtherNodes.map Prod.fst + <-> k = id \/ k ∈ v.allOtherNodes.map Prod.fst := by + rw [mem_keys, mem_keys] + constructor + · rintro ⟨q, mem⟩ + rcases mem_setPeer.mp mem with ⟨rfl, -⟩ | ⟨-, mem⟩ + · exact Or.inl rfl + · exact Or.inr ⟨q, mem⟩ + · rintro (rfl | ⟨q, mem⟩) + · exact ⟨p, mem_setPeer.mpr (Or.inl ⟨rfl, rfl⟩)⟩ + · by_cases e : k = id + · exact ⟨p, mem_setPeer.mpr (Or.inl ⟨e, rfl⟩)⟩ + · exact ⟨q, mem_setPeer.mpr (Or.inr ⟨e, mem⟩)⟩ + +/-! ## Clean and abstract peer indexes -/ + +/-- The clean send index of a peer is its declared one. -/ +theorem abs_sentIndex {names : Names} {v : State} + (peersNamed : forall p, p ∈ v.allOtherNodes -> Named names p.1) {id : NodeId} + (named : Named names id) {p : Peer} (found : v.peer? id = some p) + : (abs names v).sentIndex (names.id id) = p.sentIdx := by + simp only [abs] + unfold State.peer? at found + generalize v.allOtherNodes = l at peersNamed found + induction l with + | nil => simp at found + | cons q l ih => + obtain ⟨k, pk⟩ := q + by_cases same : id = k + · subst same + simp only [List.lookup_cons, beq_self_eq_true, Option.some.injEq] at found + subst found + simp + · have ne : (names.id k == names.id id) = false := by + simp only [beq_eq_false_iff_ne] + intro eq + exact same (named_inj named (peersNamed (k, pk) (by simp)) eq.symm) + have ne' : (id == k) = false := by simpa using same + simp only [List.lookup_cons, ne'] at found + simp only [List.find?_cons, ne] + exact ih (fun p mem => peersNamed p (List.mem_cons_of_mem _ mem)) found + +/-- A clean state that agrees with `d` is `abs d` but for the peer indexes and votes. -/ +theorem agrees_eq {names : Names} {c : NodeState} {d : State} + (h : agrees names c d = true) + : c + = { + abs names d with + sentIndex := c.sentIndex, + matchIndex := c.matchIndex, + votesGranted := c.votesGranted, + preVotesGranted := c.preVotesGranted + } := by + simp only [agrees, Bool.and_eq_true, beq_iff_eq] at h + obtain ⟨⟨⟨⟨⟨⟨⟨⟨⟨⟨h1, h2⟩, h3⟩, h4⟩, -⟩, h6⟩, h7⟩, h8⟩, -⟩, -⟩, h11⟩ := h + cases c + simp only at h1 h2 h3 h4 h6 h7 h8 h11 ⊢ + rw [h1, h2, h3, h4, h6, h7, h8, h11] + +/-! ## The name table's order -/ + +/-- The name table is strictly sorted. -/ +abbrev SortedNames (names : Names) : Prop := + (names.known.toList.zip names.known.toList.tail).all (fun (x, y) => decide (x < y)) + = true + +theorem string_pairwise_of_adjacent + : forall {l : List String}, + (l.zip l.tail).all (fun (x, y) => decide (x < y)) = true -> l.Pairwise (· < ·) + | [], _ => .nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: t, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true, + decide_eq_true_eq] at h + have rest : (b :: t).Pairwise (· < ·) := string_pairwise_of_adjacent (by simpa using h.2) + refine List.Pairwise.cons ?_ rest + intro x mem + rcases List.mem_cons.mp mem with rfl | mem + · exact h.1 + · exact String.lt_trans h.1 (List.rel_of_pairwise_cons rest mem) + +theorem known_index {names : Names} {x : NodeId} (h : names.known.contains x = true) + : exists (lt : names.id x < names.known.size), names.known[names.id x] = x := by + have mem : x ∈ names.known := by simpa using h + obtain ⟨i, hi⟩ : exists i, names.known.findIdx? (· == x) = some i := by + cases e : names.known.findIdx? (· == x) with + | some i => exact ⟨i, rfl⟩ + | none => + rw [Array.findIdx?_eq_none_iff] at e + exact absurd (e x mem) (by simp) + obtain ⟨lt, eq, -⟩ := Array.findIdx?_eq_some_iff_getElem.mp hi + have idx : names.id x = i := by simp [Names.id, hi] + subst idx + exact ⟨lt, by simpa using eq⟩ + +theorem named_of_known {names : Names} {x : NodeId} (h : names.known.contains x = true) + : Named names x := by + obtain ⟨lt, eq⟩ := known_index h + show names.name (names.id x) = x + simp [Names.name, lt, eq] + +theorem id_lt_id {names : Names} (sorted : SortedNames names) {x y : NodeId} + (hx : names.known.contains x = true) (hy : names.known.contains y = true) (xy : x < y) + : names.id x < names.id y := by + obtain ⟨ltx, ex⟩ := known_index hx + obtain ⟨lty, ey⟩ := known_index hy + have pw := string_pairwise_of_adjacent sorted + rcases Nat.lt_trichotomy (names.id x) (names.id y) with h | h | h + · exact h + · have : x = y := by + rw [← ex, ← ey] + simp only [h] + subst this + exact absurd xy (String.lt_irrefl _) + · have := List.pairwise_iff_getElem.mp pw (names.id y) (names.id x) + (by simpa using lty) (by simpa using ltx) h + simp only [Array.getElem_toList, ex, ey] at this + exact absurd xy (String.lt_asymm this) + +/-- A strictly sorted list of ids in the table maps to a strictly sorted list of clean ids. -/ +theorem map_id_sorted {names : Names} (sorted : SortedNames names) {l : List NodeId} + (hl : l.Pairwise (· < ·)) (known : forall x, x ∈ l -> names.known.contains x = true) + : (l.map names.id).Pairwise (· < ·) := by + rw [List.pairwise_map] + exact hl.imp_of_mem fun ha hb lt => id_lt_id sorted (known _ ha) (known _ hb) lt + +/-! ## Sorted, duplicate-free node id lists -/ + +theorem eraseDups_sublist {α : Type} [BEq α] [LawfulBEq α] + : forall (n : Nat) (l : List α), l.length <= n -> l.eraseDups.Sublist l + | _, [], _ => by simp + | 0, _ :: _, h => by simp at h + | n + 1, a :: as, h => by + rw [List.eraseDups_cons] + refine List.Sublist.cons_cons _ ?_ + refine List.Sublist.trans (eraseDups_sublist n _ ?_) List.filter_sublist + have := List.length_filter_le (fun b => !b == a) as + simp only [List.length_cons] at h + omega + +theorem pairwise_lt_of_le {l : List String} (sorted : l.Pairwise (· <= ·)) (nd : l.Nodup) + : l.Pairwise (· < ·) := by + refine (sorted.and nd).imp fun ⟨le, ne⟩ => ?_ + refine Classical.byContradiction fun h => ne ?_ + exact String.le_antisymm le (String.not_lt.mp h) + +/-- `mergeSort` then `eraseDups`: strictly sorted, with the same members. -/ +theorem sortDedup_spec (l : List NodeId) + : ((l.mergeSort (· <= ·)).eraseDups).Pairwise (· < ·) + /\ forall x, x ∈ (l.mergeSort (· <= ·)).eraseDups <-> x ∈ l := by + refine ⟨?_, fun x => by rw [List.mem_eraseDups, List.mem_mergeSort]⟩ + have sorted : (l.mergeSort (· <= ·)).Pairwise (fun a b => decide (a <= b) = true) := + List.pairwise_mergeSort + (fun a b c hab hbc => by + simp only [decide_eq_true_eq] at hab hbc ⊢ + exact String.le_trans hab hbc) + (fun a b => by + rcases String.le_total a b with h | h <;> simp [h]) + l + have sub := eraseDups_sublist _ (l.mergeSort (· <= ·)) (Nat.le_refl _) + refine pairwise_lt_of_le ?_ (ReplUpdateCommit.nodup_eraseDups _ _ (Nat.le_refl _)) + exact (sorted.sublist sub).imp fun h => by simpa using h + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPush.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPush.lean new file mode 100644 index 000000000000..60cc3df2995c --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplPush.lean @@ -0,0 +1,173 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplBatch +public import Consensus.TraceValidation.Proofs.Handlers.ReplCreate +public import Consensus.TraceValidation.Proofs.Handlers.ReplClean + +@[expose] public section + +/-! +# Appending one entry: the clean log + +How the clean configurations and eligible peers change when an entry is appended above the +commit index. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open CCF (Finset) + +/-- The configuration an entry at `index` carries, as a list. -/ +def entryConfig (x : Entry) (index : Nat) : List Configuration := + (x.content.metadata.configuration.map + fun nodes => ({ index, nodes } : Configuration)).toList + +theorem history_snoc (log : List Entry) (x : Entry) + : configurationHistory (log ++ [x]) + = configurationHistory log ++ entryConfig x (log.length + 1) := by + unfold configurationHistory entryConfig + rw [List.zipIdx_append, List.filterMap_append] + cases h : x.content.metadata.configuration <;> simp [h, Nat.add_comm] + +theorem history_index_le (log : List Entry) + : forall c, c ∈ configurationHistory log -> c.index <= log.length := by + intro c mem + unfold configurationHistory at mem + obtain ⟨⟨e, i⟩, memZ, found⟩ := List.mem_filterMap.mp mem + have := List.mem_zipIdx memZ + cases h : e.content.metadata.configuration with + | none => simp [h] at found + | some nodes => + simp only [h, Option.map_some, Option.some.injEq] at found + subst found + simp only + omega + +theorem active_snoc (log : List Entry) (x : Entry) {ci : Nat} (h : ci <= log.length) + : activeConfigurations (log ++ [x]) ci + = activeConfigurations log ci ++ entryConfig x (log.length + 1) := by + unfold activeConfigurations + dsimp only + rw [history_snoc, List.filter_append] + have none : (entryConfig x (log.length + 1)).filter (fun c => decide (c.index <= ci)) = [] := by + unfold entryConfig + cases x.content.metadata.configuration <;> simp; omega + rw [none, List.append_nil, List.drop_append_of_le_length] + have := List.length_filter_le (fun c : Configuration => decide (c.index <= ci)) + (configurationHistory log) + omega + +theorem committedLog_snoc {cl : NodeState} (x : Entry) + (h : cl.commitIndex <= cl.log.length) + : ({ cl with log := cl.log ++ [x] } : NodeState).committedLog = cl.committedLog := by + unfold NodeState.committedLog + exact List.take_append_of_le_length h + +theorem members_append (a b : List Configuration) {n : NodeID} + : n ∈ configurationMembers (a ++ b) + <-> n ∈ configurationMembers a \/ n ∈ configurationMembers b := by + simp only [Repl.mem_members_iff, List.mem_append] + constructor + · rintro ⟨x, mem | mem, h⟩ + · exact Or.inl ⟨x, mem, h⟩ + · exact Or.inr ⟨x, mem, h⟩ + · rintro (⟨x, mem, h⟩ | ⟨x, mem, h⟩) + · exact ⟨x, Or.inl mem, h⟩ + · exact ⟨x, Or.inr mem, h⟩ + +/-- The eligible peers after appending an entry above the commit index. -/ +theorem eligible_snoc {cl : NodeState} (x : Entry) (h : cl.commitIndex <= cl.log.length) + (self n : NodeID) + : n ∈ eligiblePeers { cl with log := cl.log ++ [x] } self + <-> n ∈ eligiblePeers cl self + \/ (n ≠ self + /\ exists nodes, + x.content.metadata.configuration = some nodes /\ n ∈ nodes) := by + have rcn : ({ cl with log := cl.log ++ [x] } : NodeState).retirementCompletedNodes + = cl.retirementCompletedNodes := by + unfold NodeState.retirementCompletedNodes + rw [committedLog_snoc x h] + unfold eligiblePeers + rw [rcn] + simp only [CCF.Finset.mem_erase, CCF.Finset.mem_union, NodeState.activeMembers, + NodeState.activeConfigurations] + rw [show cl.log ++ [x] = (cl.log ++ [x]) from rfl, active_snoc cl.log x h, members_append] + unfold entryConfig + cases hc : x.content.metadata.configuration with + | none => simp [configurationMembers] + | some nodes => + simp only [Option.map_some, Option.toList_some, Repl.mem_members_iff, List.mem_singleton, + exists_eq_left, Option.some.injEq] + constructor + · rintro ⟨ne, (a | b) | c⟩ + · exact Or.inl ⟨ne, Or.inl a⟩ + · exact Or.inr ⟨ne, nodes, rfl, b⟩ + · exact Or.inl ⟨ne, Or.inr c⟩ + · rintro (⟨ne, a | c⟩ | ⟨ne, _, rfl, b⟩) + · exact ⟨ne, Or.inl (Or.inl a)⟩ + · exact ⟨ne, Or.inr c⟩ + · exact ⟨ne, Or.inl (Or.inr b)⟩ + +/-! ## The batch relation's clean state -/ + +section Declared + +open Consensus.TraceValidation (Names abs) +open Consensus.TraceValidation.Exec +open ReplUpdateCommit (Named named_inj Hyps shifted_mem absConfig) + +variable {names : Names} {node : NodeID} {v0 : State} {cl0 : NodeState} + +theorem Mid.cleanLog {cl : NodeState} {v : State} (M : Mid names node v0 cl0 cl v) + : cl.log = (abs names v).log := by + obtain ⟨f, rfl, -⟩ := M.clean + rfl + +theorem Mid.cleanCommit (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : cl.commitIndex = v.commitIdx := by + obtain ⟨f, rfl, -⟩ := M.clean + exact S.commit.trans M.frame.commit.symm + +theorem Mid.cleanTerm (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) + : cl.currentTerm = v.currentView := by + obtain ⟨f, rfl, -⟩ := M.clean + rw [M.frame.view, S.cleanEq] + rfl + +theorem Mid.pos {cl : NodeState} {v : State} (M : Mid names node v0 cl0 cl v) + (ne : v.configurations ≠ []) + : 0 < v.lastIdx := by + refine Nat.pos_of_ne_zero fun z => ne (M.unconf z) + +/-- A member of a declared configuration is the node itself or one of its peers. -/ +theorem Mid.member (S : Start names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid names node v0 cl0 cl v) {x : Config} (mem : x ∈ v.configurations) + {a : NodeId × String} (ma : a ∈ x.nodes) + : a.1 = v.nodeId \/ a.1 ∈ v.allOtherNodes.map Prod.fst := by + have L0 := M.pos (List.ne_nil_of_mem mem) + obtain ⟨D, hD, sh⟩ := M.hy.configs L0 + obtain ⟨x', memD, nodes⟩ := shifted_mem sh mem + have named : Named names a.1 := M.hy.membersNamed x mem a ma + have act : names.id a.1 ∈ cl.activeMembers := by + unfold NodeState.activeMembers NodeState.activeConfigurations + rw [M.cleanLog, M.cleanCommit S, hD] + refine ReplUpdateCommit.mem_configurationMembers (List.mem_map_of_mem memD) ?_ + simp only [absConfig, nodes, Names.set, CCF.Finset.mem_ofList, List.mem_map] + exact ⟨a.1, ⟨a, ma, rfl⟩, rfl⟩ + by_cases eq : names.id a.1 = node + · exact Or.inl (named_inj named M.hy.selfNamed (eq.trans (M.self S).symm)) + · obtain ⟨k, memK, idk⟩ := (M.eligible _).mp + (CCF.Finset.mem_erase.mpr ⟨eq, CCF.Finset.mem_union.mpr (Or.inl act)⟩) + obtain ⟨q, memQ⟩ := mem_keys.mp memK + have := named_inj (M.hy.peersNamed _ memQ) named idk + exact Or.inr (this ▸ memK) + +end Declared + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplSend.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplSend.lean new file mode 100644 index 000000000000..550cee1e97b6 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplSend.lean @@ -0,0 +1,383 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AeHoare +public import Consensus.TraceValidation.Proofs.Obligation +public import Consensus.TraceValidation.Proofs.Handlers.LifeHoare +public import Consensus.TraceValidation.Proofs.Handlers.AeLemmas +public import Consensus.TraceValidation.Proofs.Handlers.ReplUpdateCommit + +@[expose] public section + +/-! +# `send_append_entries` as a sequence of sub-range sends (not reviewed) + +The loop of `send_append_entries` reads each sub-range end from the trace. Whatever the +ends, every successful run is a sequence of `send_append_entries_range` calls whose ends +lie within the view of their start (`maxEnd`), the first starting at the given index, each +next one just after the previous end, and the last ending at the last index. +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Ae + +/-- The highest sub-range end `send_append_entries` allows from `start`. -/ +def maxEnd (v : State) (start : Nat) : Nat := + match v.endOfView (v.viewAt start) with + | 0 => v.lastIdx + | e => e + +/-- The sub-range ends `send_append_entries` accepts from `start`. -/ +def OkEnd (v : State) (start e : Nat) : Prop := + if start > maxEnd v start then e = maxEnd v start else start <= e /\ e <= maxEnd v start + +/-- The request `send_append_entries_range` sends for the sub-range `[start, e]`. -/ +def rangeRequest (names : Names) (v : State) (start e : Nat) : AppendEntriesRequest := + { + term := v.currentView, + prevLogIndex := start - 1, + prevLogTerm := v.getTerm (start - 1), + entries := + (List.range' start (e + 1 - start)).map fun i => absEntry names v.ledger[i - 1]!, + primaryCommit := v.commitIdx + } + +/-! ## The sub-range ends (after the `Tick` proof's view lemmas) -/ + +/-- A list whose adjacent elements are ordered is sorted. -/ +theorem pairwise_of_adjacent + : forall {l : List Nat}, + (l.zip l.tail).all (fun (x, y) => decide (x <= y)) = true -> l.Pairwise (· <= ·) + | [], _ => .nil + | [_], _ => List.pairwise_singleton _ _ + | a :: b :: t, h => by + simp only [List.tail_cons, List.zip_cons_cons, List.all_cons, Bool.and_eq_true, + decide_eq_true_eq] at h + have rest : (b :: t).Pairwise (· <= ·) := pairwise_of_adjacent (by simpa using h.2) + refine List.Pairwise.cons ?_ rest + intro x mem + rcases List.mem_cons.mp mem with rfl | mem + · exact h.1 + · exact Nat.le_trans h.1 (List.rel_of_pairwise_cons rest mem) + +/-- In a sorted list, the `k`-th element is at most `i` iff more than `k` elements are. -/ +theorem lt_length_filter_iff + : forall {l : List Nat}, + l.Pairwise (· <= ·) + -> forall {k : Nat} (hk : k < l.length) (i : Nat), + k < (l.filter fun x => decide (x <= i)).length <-> l[k] <= i + | [], _, k, hk, _ => by simp at hk + | a :: t, sorted, k, hk, i => by + have rest := List.Pairwise.of_cons sorted + by_cases ai : a <= i + · rw [List.filter_cons_of_pos (by simpa using ai), List.length_cons] + cases k with + | zero => simp [ai] + | succ k => + simp only [List.getElem_cons_succ] + have := lt_length_filter_iff rest (k := k) (by simpa using hk) i + omega + · rw [List.filter_cons_of_neg (by simpa using ai)] + have none_ : (t.filter fun x => decide (x <= i)) = [] := + List.filter_eq_nil_iff.mpr fun y mem => by + have := List.rel_of_pairwise_cons sorted mem + simp only [decide_eq_true_eq] + omega + rw [none_] + cases k with + | zero => simp [ai] + | succ k => + simp only [List.length_nil, Nat.not_lt_zero, false_iff, List.getElem_cons_succ] + have := List.rel_of_pairwise_cons sorted (List.getElem_mem (l := t) + (show k < t.length by simpa using hk)) + omega + +/-- What the batch range needs of the view history, from `inv`. -/ +structure ViewHyps (v : State) : Prop where + size : v.ledger.size = v.lastIdx + sorted : v.views.toList.Pairwise (· <= ·) + positive : forall x, x ∈ v.views.toList -> 0 < x + leLast : forall x, x ∈ v.views.toList -> x <= v.lastIdx + 1 + terms + : forall i, + 1 <= i -> i <= v.lastIdx -> v.ledger[i - 1]?.map (·.term) = some (v.viewAt i) + posTerms : forall e, e ∈ v.ledger.toList -> 0 < e.term + +open Consensus.TraceValidation (Names) in +theorem ViewHyps.ofInv {names : Names} {v : State} (h : inv names v = true) + : ViewHyps v := by + obtain ⟨size, _, _, _, terms, _, positive⟩ := Ae.inv_parts h + have sorted : (v.views.toList.zip v.views.toList.tail).all + (fun (x, y) => decide (x <= y)) = true := by + inv_conj h "views_sorted" + have leLast : v.views.all (· <= v.lastIdx + 1) = true := by inv_conj h "views_le_last" + have posTerms : v.ledger.all (0 < ·.term) = true := by inv_conj h "positive_terms" + refine ⟨size, pairwise_of_adjacent sorted, ?_, ?_, terms, ?_⟩ + · intro x mem + have := Array.all_eq_true_iff_forall_mem.mp positive x (by simpa using mem) + simpa using this + · intro x mem + have := Array.all_eq_true_iff_forall_mem.mp leLast x (by simpa using mem) + simpa using this + · intro e mem + have := Array.all_eq_true_iff_forall_mem.mp posTerms e (by simpa using mem) + simpa using this + +variable {v : State} + +theorem viewAt_ge_iff (h : ViewHyps v) {k : Nat} (hk : k < v.views.size) (i : Nat) + : k < v.viewAt i <-> v.views[k] <= i := by + unfold State.viewAt + have := lt_length_filter_iff h.sorted (k := k) (by simpa using hk) i + simpa using this + +theorem viewAt_pos (h : ViewHyps v) {i : Nat} (i1 : 1 <= i) (iL : i <= v.lastIdx) + : 0 < v.viewAt i := by + have t := h.terms i i1 iL + have lt : i - 1 < v.ledger.size := by rw [h.size]; omega + rw [Array.getElem?_eq_getElem lt] at t + simp only [Option.map_some, Option.some.injEq] at t + rw [← t] + exact h.posTerms _ (by simp) + +theorem viewAt_past (h : ViewHyps v) : v.viewAt (v.lastIdx + 1) = v.views.size := by + unfold State.viewAt + rw [List.filter_eq_self.mpr (fun x mem => by simpa using h.leLast x mem)] + simp + +/-- The range from `start` within the ledger: it ends in the ledger, in the view of `start`. -/ +theorem maxIdx_range (h : ViewHyps v) {start : Nat} (s1 : 1 <= start) + (sL : start <= v.lastIdx) + : start <= maxEnd v start + /\ maxEnd v start <= v.lastIdx + /\ forall i, start <= i -> i <= maxEnd v start -> v.viewAt i = v.viewAt start := by + have w1 := viewAt_pos h s1 sL + have wS := ReplUpdateCommit.viewAt_le_size v start + generalize hw : v.viewAt start = w at w1 wS + have prevLe : v.views[w - 1] <= start := + (viewAt_ge_iff h (k := w - 1) (by omega) start).mp (by omega) + have prevPos : 0 < v.views[w - 1] := h.positive _ (by simp) + by_cases last : w < v.views.size + · have nextGt : start < v.views[w] := by + have := viewAt_ge_iff h (k := w) last start + omega + have nextLe : v.views[w] <= v.lastIdx + 1 := h.leLast _ (by simp) + have eov : v.endOfView w = v.views[w] - 1 := by + have ne : Not (v.views[w] = v.views[w - 1]) := by omega + simp [State.endOfView, State.startOfView, last, Nat.not_lt.mpr (Nat.le_of_lt last), + Nat.ne_of_gt w1, ne, Nat.succ_le_of_lt last, + getElem!_pos v.views (w - 1) (by omega), Nat.ne_of_gt prevPos, Nat.not_le.mpr last] + have mx : maxEnd v start = v.views[w] - 1 := by + unfold maxEnd + rw [hw, eov] + split + · omega + · rfl + rw [mx] + refine ⟨by omega, by omega, fun i si im => ?_⟩ + have lo := ReplUpdateCommit.viewAt_mono v si + have hi : Not (w < v.viewAt i) := fun lt => by + have := (viewAt_ge_iff h last i).mp lt + omega + omega + · have eq : w = v.views.size := by omega + have eov : v.endOfView w = 0 := by + simp [State.endOfView, eq] + have mx : maxEnd v start = v.lastIdx := by + unfold maxEnd + rw [hw, eov] + rfl + rw [mx] + refine ⟨sL, Nat.le_refl _, fun i si _ => ?_⟩ + have lo := ReplUpdateCommit.viewAt_mono v si + have hi := ReplUpdateCommit.viewAt_le_size v i + omega + +/-- From one past the ledger, the range is empty: it ends at the last index. -/ +theorem maxIdx_past (h : ViewHyps v) : maxEnd v (v.lastIdx + 1) = v.lastIdx := by + unfold maxEnd + rw [viewAt_past h] + have eov : v.endOfView v.views.size = 0 := by simp [State.endOfView] + rw [eov] + rfl + +variable {env : Env} + +theorem tri_of_hoare {α : Type} {P : State -> Outbox -> Prop} {x : M α} + {Q : α -> State -> Outbox -> Prop} (h : Hoare env P x Q) + : Life.Tri env P x Q := + h + +theorem sendRange_spec {to : NodeId} {start e : Nat} {ext : Bool} {v0 : State} + {o0 : Outbox} {p : Peer} (found : v0.peer? to = some p) + : Hoare env (fun v o => v = v0 /\ o = o0) (sendAppendEntriesRange to start e ext) + fun _ v o => + v = v0.setPeer to { p with sentIdx := e } + /\ o + = o0 + ++ [⟨ + env.names.id v0.nodeId, + env.names.id to, + .appendEntriesRequest (rangeRequest env.names v0 start e) + ⟩] := by + unfold sendAppendEntriesRange + refine Hoare.getV_bind fun s => ?_ + refine Hoare.pin fun v o pre => ?_ + obtain ⟨⟨hv, ho⟩, hs⟩ := pre + subst s; subst v; subst o + simp only [found] + refine Hoare.bind (Hoare.keeps (Spec.emit _ _) fun _ _ _ h => h) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.emitStr _ _) fun _ _ _ h => h) fun _ => ?_ + refine Hoare.bind (Hoare.of_spec Spec.names + (Q := fun a w o => a = env.names /\ w = v0 /\ o = o0) fun _ _ _ _ _ p h => by + obtain ⟨rfl, rfl⟩ := p + exact ⟨h.1, h.2.1, h.2.2⟩) fun names => ?_ + refine Hoare.pin fun w o pre => ?_ + obtain ⟨hn, hw, ho⟩ := pre + subst names; subst w; subst o + refine Hoare.bind (Hoare.send _ _ (Q := fun _ w o' => w = v0 /\ o' = o0 ++ [⟨env.names.id v0.nodeId, env.names.id to, + .appendEntriesRequest (rangeRequest env.names v0 start e)⟩]) fun _ _ h => by + obtain ⟨rfl, rfl⟩ := h + exact ⟨rfl, rfl⟩) fun _ => ?_ + refine Hoare.bind (Hoare.keeps (Spec.note _) fun _ _ _ h => h) fun _ => ?_ + exact Hoare.setV _ fun _ _ h => by obtain ⟨rfl, rfl⟩ := h; exact ⟨rfl, rfl⟩ + +open Consensus.TraceValidation.Proofs.Life in +theorem tri_fact {α : Type} {x : M α} {P : State -> Outbox -> Prop} + {Q : α -> State -> Outbox -> Prop} {φ : Prop} (get : forall v o, P v o -> φ) + (h : φ -> Tri env P x Q) + : Tri env P x Q := + fun c a c' e p r => h (get _ _ p) c a c' e p r + +theorem okEnd_of {v : State} {start e : Nat} + (h + : (if start > maxEnd v start then + e == maxEnd v start + else + decide (start <= e) && decide (e <= maxEnd v start)) + = true) + : OkEnd v start e := by + unfold OkEnd + split at h + · simp_all + · rename_i hs + simp only [Bool.and_eq_true, decide_eq_true_eq] at h + simp only [gt_iff_lt, hs, ite_false] + exact h + +open Consensus.TraceValidation.Proofs.Life in +theorem loop_tri {to : NodeId} {ext : Bool} {I : Nat -> State -> Outbox -> Prop} + {Fin : State -> Outbox -> Prop} + (notRC : forall s v o, I s v o -> v.isRetiredCommitted = false) + (step + : forall s e, + Tri env (fun v o => I s v o /\ OkEnd v s e) + (sendAppendEntriesRange to s e ext) + fun _ v o => + (e = v.lastIdx -> Fin v o) + /\ (e ≠ v.lastIdx -> I (min (e + 1) v.lastIdx) v o)) + : forall fuel start batch, + Tri env (I start) (sendAppendEntries.loop to ext fuel start batch) + fun _ => Fin := by + intro fuel + induction fuel with + | zero => + intro start batch + unfold sendAppendEntries.loop + exact Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail _ + | succ fuel ih => + intro start batch + unfold sendAppendEntries.loop + refine Tri.getV_bind fun v => ?_ + refine tri_fact (fun w o p => p.2 ▸ notRC _ _ _ p.1) fun hrc => ?_ + simp only [hrc, Bool.false_and, Bool.false_eq_true, ite_false, pure_bind] + have hK : forall e b, Tri env (fun w o => (I start w o /\ w = v) /\ OkEnd v start e) + (do + sendAppendEntriesRange to start e ext + let v ← getV + if (e == v.lastIdx) = true then pure () + else sendAppendEntries.loop to ext fuel (min (e + 1) v.lastIdx) b) fun _ => Fin := by + intro e b + refine Tri.bind (Tri.conseq (step start e) (fun w o h => ⟨h.1.1, h.1.2 ▸ h.2⟩) + (fun _ _ _ h => h)) fun _ => ?_ + refine Tri.getV_bind fun w => ?_ + refine Tri.ite (fun he => ?_) (fun he => ?_) + · exact Tri.conseq (Tri.pure' (Q := fun _ => Fin) ()) (fun _ _ h => by + obtain ⟨h, rfl⟩ := h + exact h.1 (by simpa using he)) (fun _ _ _ h => h) + · exact Tri.conseq (ih _ _) (fun _ _ h => by + obtain ⟨h, rfl⟩ := h + exact h.2 (by simpa using he)) (fun _ _ _ h => h) + refine Tri.bind (Q := fun _ w o => I start w o /\ w = v) (Tri.keeps Spec.look) + fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.use _)) fun _ => ?_ + refine Tri.bind (Tri.keeps (Spec.liftE _)) fun e => ?_ + refine Tri.ite (fun hok => ?_) + (fun _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _) + have ok : OkEnd v start e := okEnd_of hok + refine Tri.conseq (P' := fun w o => (I start w o /\ w = v) /\ OkEnd v start e) ?_ + (fun _ _ h => ⟨h, ok⟩) (fun _ _ _ h => h) + have hF : forall {β : Type} (m : String -> String) (k : Unit -> M β) {Q : β -> State -> Outbox -> Prop}, + Tri env (fun w o => (I start w o /\ w = v) /\ OkEnd v start e) + (curLoc >>= fun l => fail (m l) >>= k) Q := + fun _ _ => Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _ + refine Tri.ite (fun _ => Tri.ite (fun _ => hF _ _) fun _ => hK _ _) + fun _ => Tri.ite (fun _ => hF _ _) fun _ => hK _ _ + +open Consensus.TraceValidation.Proofs.Life in +theorem send_tri {to : NodeId} {start : Nat} {ext : Bool} + {I : Nat -> State -> Outbox -> Prop} {Fin : State -> Outbox -> Prop} + (notRC : forall s v o, I s v o -> v.isRetiredCommitted = false) + (step + : forall s e, + Tri env (fun v o => I s v o /\ OkEnd v s e) + (sendAppendEntriesRange to s e ext) + fun _ v o => + (e = v.lastIdx -> Fin v o) + /\ (e ≠ v.lastIdx -> I (min (e + 1) v.lastIdx) v o)) + : Tri env (I start) (sendAppendEntries to start ext) fun _ => Fin := by + unfold sendAppendEntries + refine Tri.getV_bind fun v => ?_ + exact Tri.conseq (loop_tri notRC step _ _ _) (fun _ _ h => h.1) (fun _ _ _ h => h) + +theorem setPeer_lastIdx (v : State) (id : NodeId) (p : Peer) + : (v.setPeer id p).lastIdx = v.lastIdx := + rfl + +/-- A heartbeat from one past the ledger: one empty request, the peer's send index at the end. -/ +theorem heartbeat_tri {to : NodeId} {ext : Bool} {v0 : State} {o0 : Outbox} {p : Peer} + (h : ViewHyps v0) (rc : v0.isRetiredCommitted = false) (found : v0.peer? to = some p) + : Life.Tri env (fun v o => v = v0 /\ o = o0) + (sendAppendEntries to (v0.lastIdx + 1) ext) + fun _ v o => + v = v0.setPeer to { p with sentIdx := v0.lastIdx } + /\ o + = o0 + ++ [⟨ + env.names.id v0.nodeId, + env.names.id to, + .appendEntriesRequest + (rangeRequest env.names v0 (v0.lastIdx + 1) v0.lastIdx) + ⟩] := by + refine Life.Tri.conseq (send_tri (start := v0.lastIdx + 1) + (I := fun s v o => s = v0.lastIdx + 1 /\ v = v0 /\ o = o0) (fun _ _ _ h => h.2.1 ▸ rc) + (fun s e => ?_)) (fun _ _ h => ⟨rfl, h⟩) (fun _ _ _ h => h) + refine tri_fact (φ := s = v0.lastIdx + 1 /\ e = v0.lastIdx) (fun v o h => by + obtain ⟨⟨rfl, rfl, _⟩, ok⟩ := h + refine ⟨rfl, ?_⟩ + unfold OkEnd at ok + rw [maxIdx_past h] at ok + simpa using ok) fun ⟨hs, he⟩ => ?_ + subst hs he + refine Life.Tri.conseq (tri_of_hoare <| sendRange_spec (env := env) (start := v0.lastIdx + 1) (e := v0.lastIdx) (ext := ext) (o0 := o0) found) + (fun _ _ h => ⟨h.1.2.1, h.1.2.2⟩) (fun _ _ _ h => ?_) + obtain ⟨rfl, rfl⟩ := h + exact ⟨fun _ => ⟨rfl, rfl⟩, fun ne => absurd rfl ne⟩ + +end Consensus.TraceValidation.Proofs.Repl diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Replicate.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Replicate.lean new file mode 100644 index 000000000000..171bddf0d06f --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/Replicate.lean @@ -0,0 +1,380 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.ReplCommit + +@[expose] public section + +/-! +# Obligation: `replicate` (not reviewed) + +A leader replicates a batch of entries (`replicate_entry`, with its hooks, `put_entry` and +flushes), then runs `update_commit` only if no other node was in its active configurations +before the batch. The clean counterpart is one `append` input with the batch's entries, or +none for an empty batch. With other nodes, the clean `advanceCommit` cannot move +(`Mid.stuck`); without them, `update_commit` chooses the clean `highestCommittableIndex`, and +the node cannot step down, as it is not removed (`alone_not_removed`). +-/ + +namespace Consensus.TraceValidation.Proofs.Repl + +open Consensus.Model.Node +open Consensus.TraceValidation (Names Env abs agrees inv msgInv UnnamedUnmatched) +open Consensus.TraceValidation.Exec +open Consensus.TraceValidation.Proofs.Life + +theorem firstLogIndexAfter_isSome {l : List Model.Node.Entry} {p : EntryContent -> Bool} + : (firstLogIndexAfter l 0 p).isSome + <-> exists (j : Nat) (x : Model.Node.Entry), + l[j]? = some x /\ p x.content = true := by + unfold firstLogIndexAfter + rw [Option.isSome_map, List.find?_isSome] + constructor + · rintro ⟨⟨x, k⟩, mem, hp⟩ + rw [List.mem_zipIdx_iff_le_and_getElem?_sub] at mem + simp only [Bool.and_eq_true, decide_eq_true_eq] at hp + exact ⟨k - 1, x, mem.2, hp.2⟩ + · rintro ⟨j, x, hj, hp⟩ + refine ⟨(x, j + 1), ?_, ?_⟩ + · rw [List.mem_zipIdx_iff_le_and_getElem?_sub] + simpa using hj + · simp [hp] + +variable {env : Env} {node : NodeID} {v0 : State} {cl0 : NodeState} + +/-- What `replicate` leaves, from a leader `v0` and a clean state `cl0`. -/ +def Out (env : Env) (node : NodeID) (v0 : State) (cl0 : NodeState) (v : State) + (o : Outbox) + : Prop := + exists v1 o1, + Batch env node v0 cl0 v1 o1 + /\ ((v0.otherNodesInActiveConfigs.isEmpty = false /\ v = v1 /\ o = o1) + \/ (v0.otherNodesInActiveConfigs.isEmpty = true /\ UcOut env v1 o1 v o)) + +theorem replicate_tri (S : Start env.names node v0 cl0) + : Tri env (fun v o => v = v0 /\ o = []) Exec.replicate + fun _ => Out env node v0 cl0 := by + unfold Exec.replicate + refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.getV_bind fun v => ?_ + refine tri_fact (φ := v = v0) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst v + refine Tri.conseq (P' := fun w o => w = v0 /\ o = []) ?_ (fun _ _ p => p.1) + fun _ _ _ q => q + have g : (v0.leadership == .leader && !v0.isRetiredCommitted) = true := by + simp [S.leader, S.notRC] + simp only [g, ↓reduceIte] + refine Tri.bind (Tri.keeps Spec.Keeps.get) fun ctx => ?_ + refine Tri.bind (Tri.conseq (entries_tri S _) (fun v o p => Or.inl p) fun _ _ _ q => q) + fun _ => ?_ + refine Tri.ite (fun alone => ?_) fun others => ?_ + · refine tri_pin fun v1 o1 L => ?_ + obtain ⟨es, cl, -, M, -⟩ := L.batch S + have uc := updateCommit_hoare env (v1 := v1) (o1 := o1) + (M.frame.leadership.trans S.leader) (M.cover S) (M.rcRetired alone) + exact fun c a c' e p r => by + obtain ⟨e', q⟩ := uc c a c' e p r + exact ⟨e', v1, o1, L.batch S, Or.inr ⟨alone, q⟩⟩ + · exact Tri.conseq (Tri.pure' ()) (fun v o L => ⟨v, o, L.batch S, + Or.inl ⟨Bool.eq_false_iff.mpr others, rfl, rfl⟩⟩) fun _ _ _ q => q + +theorem replicate_fails + (no : Not (v0.leadership = .leader /\ v0.isRetiredCommitted = false)) + : Tri env (fun v o => v = v0 /\ o = []) Exec.replicate fun _ _ _ => False := by + unfold Exec.replicate + refine Tri.bind (Tri.keeps (Spec.trace _)) fun _ => ?_ + refine Tri.getV_bind fun v => ?_ + refine tri_fact (φ := v = v0) (fun _ _ p => p.2.symm.trans p.1.1) fun e => ?_ + subst v + have g : (v0.leadership == .leader && !v0.isRetiredCommitted) = false := by + cases h1 : v0.leadership <;> cases h2 : v0.isRetiredCommitted <;> simp_all + simp only [g, Bool.false_eq_true, ↓reduceIte] + exact Tri.bind (Tri.keeps Spec.curLoc) fun _ => Tri.fail_bind _ + +theorem Out.nodeId {v : State} {o : Outbox} (h : Out env node v0 cl0 v o) + : v.nodeId = v0.nodeId := by + obtain ⟨v1, o1, ⟨es, cl, -, M, -⟩, br⟩ := h + rcases br with ⟨-, rfl, -⟩ | ⟨-, res, -, ⟨-, rfl, -⟩ | ⟨i, -, -, -, K, -⟩⟩ + · exact M.frame.nodeId + · exact M.frame.nodeId + · exact K.1.trans M.frame.nodeId + +theorem Mid.role (S : Start env.names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid env.names node v0 cl0 cl v) + : cl.role = .primary := by + obtain ⟨f, rfl, -⟩ := M.clean + exact S.role + +theorem Mid.rci (S : Start env.names node v0 cl0) {cl : NodeState} {v : State} + (M : Mid env.names node v0 cl0 cl v) + : cl.retiredCommittedIndex = none := by + obtain ⟨f, rfl, -⟩ := M.clean + exact S.cleanRci + +theorem emits_nil {cl : NodeState} {o : Outbox} + (em : Emits (([] : List AppendEntryInput).foldlM (entryStep node) cl0) cl o) + : cl = cl0 /\ o = [] := by + have h := emits_run em + rw [List.foldlM_nil, emits_run (emits_pure cl0)] at h + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, h⟩ := h + exact ⟨rfl, (congrArg CCF.Outputs.outgoing h).symm⟩ + +theorem emits_advance_le {st : NodeState} (primary : st.role = .primary) + (le : highestCommittableIndex st node <= st.commitIndex) + : Emits (advanceCommit (CCF.Capabilities.record node) st node) st [] := by + have h := emits_advance (node := node) st primary + rwa [ite_eq_left le, ite_eq_right fun c => c.1 le] at h + +theorem emits_advance_keep {st : NodeState} {i : Nat} (primary : st.role = .primary) + (hi : highestCommittableIndex st node = i) (gt : Not (i <= st.commitIndex)) + (rci : st.retiredCommittedIndex = none) + (nrc : Not ((AeResp.latch node st i).isRetiredCommitted node)) + : Emits (advanceCommit (CCF.Capabilities.record node) st node) + (AeResp.latch node st i) [] := by + have h := emits_advance (node := node) st primary + rwa [hi, ite_eq_right gt, AeResp.recordCommit_keep rci nrc, ite_eq_right fun c => nrc c.2] at h + +open CCF.Sections (LocalRun) in +/-- The clean side, from the batch's clean run and the clean commit after it. -/ +theorem conclude (S : Start env.names node v0 cl0) + {cleanOthers : List (NodeID × NodeState)} {es : List AppendEntryInput} + {cl cl' : NodeState} {o1 o2 o : Outbox} {v : State} + (em : Emits (es.foldlM (entryStep node) cl0) cl o1) + (ha : Emits (advanceCommit (CCF.Capabilities.record node) cl node) cl' o2) + (still : es = [] -> cl' = cl /\ o2 = []) (out : o = o1 ++ o2) + (agreed : agrees env.names cl' v = true) (U : UnnamedUnmatched node cl') + (msgs : forall e, e ∈ o -> msgInv env.names e = true) + : exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node cl0 (cleanActions env none inputs) clean' o + /\ agrees env.names clean' v = true + /\ UnnamedUnmatched node clean' + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall e, e ∈ o -> msgInv env.names e = true := by + subst out + by_cases ne : es = [] + · subst ne + obtain ⟨rfl, rfl⟩ := emits_nil em + obtain ⟨rfl, rfl⟩ := still rfl + refine ⟨[], _, ?_, agreed, U, by simp, msgs⟩ + simpa [cleanActions] using LocalRun.nil (protocol := protocol env) (node := node) _ + · exact ⟨[.append es], cl', localRun_append env + (emits_appendBatch S.role (not_rc_of_rci S.cleanRci node) ne em ha), agreed, U, + by simp [admit], msgs⟩ + +open CCF.Sections (LocalRun) in +open AeResp (Agrees hc_of_agrees) in +/-- The obligation's clean side, from what `replicate` leaves. -/ +theorem out_sound (S : Start env.names node v0 cl0) + {cleanOthers : List (NodeID × NodeState)} {v : State} {o : Outbox} + (h : Out env node v0 cl0 v o) (invV : inv env.names v = true) + : exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node cl0 (cleanActions env none inputs) clean' o + /\ agrees env.names clean' v = true + /\ UnnamedUnmatched node clean' + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall e, e ∈ o -> msgInv env.names e = true := by + obtain ⟨v1, o1, ⟨es, cl, em, M, msgs⟩, br⟩ := h + have prim := M.role S + have rci := M.rci S + have cc := M.cleanCommit S + obtain ⟨A1b, U⟩ := M.finish S + have A1 := Agrees.of A1b + have idle : highestCommittableIndex cl node <= cl.commitIndex + -> exists (inputs : List Input) (clean' : NodeState), + LocalRun (protocol env) node cl0 (cleanActions env none inputs) clean' o1 + /\ agrees env.names clean' v1 = true /\ UnnamedUnmatched node clean' + /\ (forall input, input ∈ inputs -> admit cleanOthers node input = true) + /\ forall e, e ∈ o1 -> msgInv env.names e = true := + fun le => conclude S em (emits_advance_le prim le) (fun _ => ⟨rfl, rfl⟩) + (List.append_nil _).symm A1b U msgs + have hcEq : forall r, ReplUpdateCommit.updateCommitOf v1 0 none (v1.lastIdx + 2) = .ok r + -> highestCommittableIndex cl node = r.getD v1.commitIdx := by + intro r run + rw [hc_of_agrees A1 fun n el => ?_, ← M.self S] + · exact ReplUpdateCommit.updateCommit_eq M.hy run + · obtain ⟨k, memK, rfl⟩ := (M.eligible n).mp el + obtain ⟨p, memP⟩ := mem_keys.mp memK + exact (tracked_iff (M.leader S)).mpr ⟨k, p, memP, rfl⟩ + rcases br with ⟨others, rfl, rfl⟩ | ⟨alone, res, run, ⟨le, rfl, rfl⟩ | ⟨i, rfl, lt, ile, R⟩⟩ + · exact idle (M.stuck S others) + · exact idle (by rw [hcEq _ run, cc]; exact le) + -- A commit. + obtain ⟨⟨kId, kView, kLedger, kLast, kNF, kVoted, kCommit⟩, -, R⟩ := R + have hc := hcEq _ run + simp only [Option.getD_some] at hc + have nmax : es ≠ [] := by + rintro rfl + obtain ⟨rfl, -⟩ := emits_nil em + have := S.maximal + omega + have absLog : (abs env.names v).log = (abs env.names v1).log := by + show (v.ledger.toList.take v.lastIdx).map _ = (v1.ledger.toList.take v1.lastIdx).map _ + rw [kLedger, kLast] + have hIdV : env.names.id v.nodeId = node := by rw [kId]; exact M.self S + have rciEq : v.retiredCommittedIdx = Ae.firstConf node cl.log i := by + have e : (v.retiredCommittedIdx + == firstLogIndexAfter ((abs env.names v).log.take v.commitIdx) 0 + fun x => decide (env.names.id v.nodeId ∈ x.metadata.retirementConfirmations)) + = true := by + inv_conj invV "rci_first" + rw [absLog, kCommit, hIdV, beq_iff_eq, ← A1.log] at e + exact e + have rcIff : (AeResp.latch node cl i).isRetiredCommitted node + <-> v.isRetiredCommitted = true := by + have e : (v.isRetiredCommitted + == decide ((abs env.names v).isRetiredCommitted (env.names.id v.nodeId))) = true := by + inv_conj invV "retired_committed" + rw [hIdV, beq_iff_eq] at e + rw [e, decide_eq_true_iff, Ae.isRetiredCommitted_iff, Ae.isRetiredCommitted_iff, absLog, + ← A1.log] + show _ <-> _ /\ v.retiredCommittedIdx.isSome = true + rw [rciEq] + rcases R with ⟨vl, vlid, ho, sub, -⟩ | ⟨vl, vlid, vrc, ho⟩ + -- Still leader. + · have notRC : (v.leadership != .leader || !v.isRetiredCommitted) = true := by + inv_conj invV "leader_not_retired_committed" + simp only [vl, bne_self_eq_false, Bool.false_or, Bool.not_eq_true'] at notRC + have nrc : Not ((AeResp.latch node cl i).isRetiredCommitted node) := + fun h => by rw [rcIff.mp h] at notRC; cases notRC + have ha := emits_advance_keep prim hc (by omega) rci nrc + obtain ⟨f, -, P⟩ := M.clean + have sortedV := (AeResp.peerCtx invV vl (by rw [kLast]; omega)).sortedId + have trackedV : forall n, n ∈ trackedPeers env.names v + -> exists p, p ∈ v.allOtherNodes /\ env.names.id p.1 = n := by + intro n m + simp only [trackedPeers, vl, beq_self_eq_true, ↓reduceIte, List.mem_map] at m + exact m + have peerV1 : forall p, p ∈ v1.allOtherNodes + -> cl.sentIndex (env.names.id p.1) = p.2.sentIdx + /\ cl.matchIndex (env.names.id p.1) = p.2.matchIdx := by + intro p mp + have tr : env.names.id p.1 ∈ trackedPeers env.names v1 := + (tracked_iff (M.leader S)).mpr ⟨p.1, p.2, mp, rfl⟩ + have found := (lookup_iff_mem P.nodup).mpr mp + have named := M.hy.peersNamed _ mp + exact ⟨(A1.sent _ tr).trans (abs_sentIndex M.hy.peersNamed named found), + (A1.match_ _ tr).trans (ReplUpdateCommit.abs_matchIndex M.hy.peersNamed named found)⟩ + have agreedV : Agrees env.names (AeResp.latch node cl i) v := by + refine ⟨?_, ?_, ?_, kCommit.symm, ?_, ?_, ?_, ?_, ?_, ?_⟩ + · show cl.role = _ + rw [prim, vl] + rfl + · show cl.currentTerm = v.currentView + rw [A1.term, kView] + · show cl.log = _ + rw [absLog] + exact A1.log + · intro n m + obtain ⟨p, mp, rfl⟩ := trackedV n m + exact (peerV1 p (sub p mp)).1.trans (AeResp.abs_sentIndex_of_sorted sortedV mp).symm + · intro n m + obtain ⟨p, mp, rfl⟩ := trackedV n m + exact (peerV1 p (sub p mp)).2.trans (AeResp.abs_matchIndex_of_sorted sortedV mp).symm + · show cl.isNewFollower = _ + rw [A1.newFollower, kNF] + · show cl.votedFor = _ + rw [A1.voted, kVoted] + · show cl.primaryKnown = _ + rw [A1.known, vlid] + · show Ae.firstConf node cl.log i = _ + rw [rciEq] + exact conclude S em ha (fun e => absurd e nmax) (by rw [ho, List.append_nil]) + (Agrees.to agreedV ⟨by rw [vl]; simp, by rw [vl]; simp⟩) U (by rw [ho]; exact msgs) + -- Stepped down: impossible, as the node was not removed. + · exfalso + have some1 := ((Ae.isRetiredCommitted_iff _ _).mp (rcIff.mpr vrc)).2 + change (Ae.firstConf node cl.log i).isSome = true at some1 + rw [Ae.firstConf, firstLogIndexAfter_isSome] at some1 + obtain ⟨j, x, hj, hx⟩ := some1 + rw [List.getElem?_take] at hj + split at hj + rotate_left + · cases hj + have M0 := Mid.start S + have ge : v0.commitIdx <= j := by + refine Nat.le_of_not_lt fun jl => ?_ + have e0 : (v0.retiredCommittedIdx + == firstLogIndexAfter ((abs env.names v0).log.take v0.commitIdx) 0 + fun x => decide (env.names.id v0.nodeId ∈ x.metadata.retirementConfirmations)) + = true := by + inv_conj S.inv "rci_first" + rw [S.rci, S.self, beq_iff_eq] at e0 + have len : j < cl0.log.length := by + rw [S.log, ReplUpdateCommit.abs_log_length M0.hy.size] + have := M0.hy.commitLe + omega + obtain ⟨T, hT⟩ := M.isPrefix + have some0 := (firstLogIndexAfter_isSome (l := (abs env.names v0).log.take v0.commitIdx) + (p := fun x => decide (node ∈ x.metadata.retirementConfirmations))).mpr ⟨j, x, ?_, hx⟩ + · rw [← e0] at some0 + cases some0 + · rw [List.getElem?_take, ite_eq_left jl, ← S.log, ← List.getElem?_append_left len (l₂ := T), + hT, ← A1.log] + exact hj + have mem := M.confRemoved j x ge (by rw [← A1.log]; exact hj) node (of_decide_eq_true hx) + have e2 : (v0.leadership != .leader + || !v0.configurations.all (·.nodes.all (·.1 == v0.nodeId)) + || decide (env.names.id v0.nodeId ∉ removedNodes (abs env.names v0).log)) = true := by + inv_conj S.inv "alone_not_removed" + have all : v0.configurations.all (·.nodes.all (·.1 == v0.nodeId)) = true := by + simp only [List.all_eq_true, beq_iff_eq] + exact (others_empty_iff v0).mp alone + rw [S.leader, all, S.self] at e2 + simp only [bne_self_eq_false, Bool.not_true, Bool.or_false, Bool.false_or, + decide_eq_true_eq] at e2 + exact e2 mem + +section Witness + +variable {names : Names} + +theorem agrees_abs (v : State) : agrees names (abs names v) v = true := by + simp [agrees] + +theorem unmatched_abs {v : State} (h : inv names v = true) (lead : v.leadership = .leader) + : UnnamedUnmatched (names.id v.nodeId) (abs names v) := by + intro _ n _ nm + simp only [abs] + split + · rename_i k p hf + exfalso + have mem := List.mem_of_find?_eq_some hf + have e := List.find?_some hf + simp only [beq_iff_eq] at e + exact nm (AeResp.eligible_mem_history + ((AeResp.peerCtx h lead (AeResp.leader_nonempty h lead mem)).eligible_iff.mpr ⟨_, mem, e⟩)) + · rfl + +end Witness + +end Consensus.TraceValidation.Proofs.Repl + +namespace Consensus.TraceValidation.Proofs +open Consensus.Model.Node +open Consensus.TraceValidation (abs agrees) +open Repl Life + +theorem replicateSound (env : Env) : ReplicateSound env := by + intro node saved actions c vars others cleanOthers savedName savedId invSaved _ _ ran _ + finished invVars + simp only [plainFinish, Except.ok.injEq] at finished + subst finished + by_cases able : saved.leadership = .leader /\ saved.isRetiredCommitted = false + rotate_left + · exact (Tri.run (replicate_fails able) ⟨rfl, rfl⟩ ran).elim + obtain ⟨lead, notRC⟩ := able + have start : forall cl0, agrees env.names cl0 saved = true -> UnnamedUnmatched node cl0 + -> Start env.names node saved cl0 := + fun _ a u => ⟨invSaved, a, u, savedId, lead, notRC, AeResp.leader_rci_none invSaved lead⟩ + have out : forall cl0, Start env.names node saved cl0 + -> Out env node saved cl0 c.vars c.outbox := + fun _ S => Tri.run (replicate_tri S) ⟨rfl, rfl⟩ ran + refine ⟨(out _ (start _ (agrees_abs saved) + (savedId ▸ unmatched_abs invSaved lead))).nodeId, fun clean _ agreed unmatched => ?_⟩ + have S := start clean agreed unmatched + exact out_sound S (out clean S) invVars + +end Consensus.TraceValidation.Proofs From cbe522744dc17ae5703e54caad90555f5132b05a Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:09:38 +0000 Subject: [PATCH 15/25] State and prove that accepted traces refine the clean model TraceValidation.lean states the one reviewed theorem, `accepted_refines`: an accepted trace is a behaviour of `Consensus.Model.transitionSystem` under the reviewed state mapping `related`, at every lock-taking event. Its proof assembles the fourteen handler obligations and the section framework, and uses only the standard axioms. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 15 +--- lean/consensus/Consensus/TraceValidation.lean | 54 +++++++++++++ .../TraceValidation/Proofs/Handlers.lean | 50 ++++++++++++ .../TraceValidation/Proofs/Refinement.lean | 80 +++++++++++++++++++ 4 files changed, 185 insertions(+), 14 deletions(-) create mode 100644 lean/consensus/Consensus/TraceValidation.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Handlers.lean create mode 100644 lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 777f34303701..1f6b9d4bae94 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -1,21 +1,8 @@ module public import Consensus.Properties +public import Consensus.TraceValidation public import Consensus.TraceValidation.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks -import Consensus.TraceValidation.Proofs.Handlers.AppendEntries -import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo -import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary -import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup -import Consensus.TraceValidation.Proofs.Handlers.OutOfLockHook -import Consensus.TraceValidation.Proofs.Handlers.ProposeRequestVote -import Consensus.TraceValidation.Proofs.Handlers.Replicate -import Consensus.TraceValidation.Proofs.Handlers.RequestPreVote -import Consensus.TraceValidation.Proofs.Handlers.RequestPreVoteResponse -import Consensus.TraceValidation.Proofs.Handlers.RequestVote -import Consensus.TraceValidation.Proofs.Handlers.RequestVoteResponse -import Consensus.TraceValidation.Proofs.Handlers.Tick -import Consensus.TraceValidation.Proofs.Section -import Consensus.TraceValidation.Proofs.Validator diff --git a/lean/consensus/Consensus/TraceValidation.lean b/lean/consensus/Consensus/TraceValidation.lean new file mode 100644 index 000000000000..a0f6cead5aae --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation.lean @@ -0,0 +1,54 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Refinement + +@[expose] public section + +/-! +# Trace validation (reviewed statement) + +The validator `validate` (in `Consensus.TraceValidation.Validator`) checks a trace of +`cft.h` trace points, split into one stream per node. The theorem below is what +acceptance means: the accepted trace is a behaviour of the clean model +`Consensus.Model.transitionSystem` under a state refinement mapping. Properties are +stated and proved of the clean model only (`Consensus.Properties`); nothing here is +claimed of the implementation beyond this refinement. + +To review, the state refinement mapping and the observations it is checked at: +`State` (the declared state: the `cft.h` variables of a node, with the ledger it +holds), `Abs` (the relation `related` of a clean node state to a declared state), +`Event` (decoded trace points), `Action` and `Observe` (what each trace point is +compared with), `CCF.Observation` (the refinement statement, in `lean/common`), and this +file. The behaviour refinement, that is the proof of the theorem, is in +`Consensus.TraceValidation.Proofs` and is not reviewed. +-/ + +namespace Consensus.TraceValidation + +open CCF.MultiNodeTransitionSystem (nodeState) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Ev) + +/-- +If the validator accepts the per-node streams, its observations are exactly the streams' +events, in order per node; each is consistent (`Exec.consistent`) with the declared state +and the model's label at its trace point; and they refine the clean specification +`Consensus.Model.transitionSystem` at every lock-taking event (`opens`): there is one +specification trace in which, at each such event, the node's clean state is `related` to +the declared state the event was compared with. +-/ +theorem accepted_refines {env : Env} + {streams : List (NodeID × List Ev)} {v : Verdict} (h : validate env streams = .ok v) + : streamsMatch streams v.observations = true + /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) + /\ CCF.ObservationRefinement.Refines + (Consensus.Model.transitionSystem env.genesis v.keys) nodeState + (fun node clean declared => + related env.names node clean declared.1 = true) + opens v.observations := + Proofs.validate_refines h + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers.lean new file mode 100644 index 000000000000..aeebea83543f --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers.lean @@ -0,0 +1,50 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Handlers.AppendEntries +public import Consensus.TraceValidation.Proofs.Handlers.AppendEntriesResponse +public import Consensus.TraceValidation.Proofs.Handlers.DropPendingTo +public import Consensus.TraceValidation.Proofs.Handlers.ForceBecomePrimary +public import Consensus.TraceValidation.Proofs.Handlers.InitAsBackup +public import Consensus.TraceValidation.Proofs.Handlers.Nomination +public import Consensus.TraceValidation.Proofs.Handlers.OutOfLockHook +public import Consensus.TraceValidation.Proofs.Handlers.ProposeRequestVote +public import Consensus.TraceValidation.Proofs.Handlers.Replicate +public import Consensus.TraceValidation.Proofs.Handlers.RequestPreVote +public import Consensus.TraceValidation.Proofs.Handlers.RequestPreVoteResponse +public import Consensus.TraceValidation.Proofs.Handlers.RequestVote +public import Consensus.TraceValidation.Proofs.Handlers.RequestVoteResponse +public import Consensus.TraceValidation.Proofs.Handlers.Tick + +@[expose] public section + +/-! +# Per-handler obligations: assembly (not reviewed) + +Each obligation of `Obligations` is proved in its own file +`Consensus.TraceValidation.Proofs.Handlers.`, as +`theorem Sound (env : Env) : Sound env`. +-/ + +namespace Consensus.TraceValidation.Proofs + +/-- Every handler's obligation. -/ +theorem obligations (env : Env) : Obligations env where + appendEntries := appendEntriesSound env + appendEntriesResponse := appendEntriesResponseSound env + requestVote := requestVoteSound env + requestPreVote := requestPreVoteSound env + requestVoteResponse := requestVoteResponseSound env + requestPreVoteResponse := requestPreVoteResponseSound env + proposeRequestVote := proposeRequestVoteSound env + tick := tickSound env + replicate := replicateSound env + nomination := nominationSound env + initAsBackup := initAsBackupSound env + outOfLockHook := outOfLockHookSound env + forceBecomePrimary := forceBecomePrimarySound env + dropPendingTo := dropPendingToSound env + +end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean new file mode 100644 index 000000000000..670d4804db6e --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean @@ -0,0 +1,80 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Proofs.Validator +public import Consensus.TraceValidation.Proofs.Section +public import Consensus.TraceValidation.Proofs.Handlers +public import CCF.Proofs.SectionsObservation + +@[expose] public section + +/-! +# An accepted trace refines the clean model (proof, not reviewed) + +If the validator accepts the per-node streams, then there is one trace of +`Consensus.Model.transitionSystem env.genesis keys` (the frozen specification, with its +nonempty-genesis and committed-prefix-join conditions), and a nondecreasing map from +observations into it, such that at every lock-taking event (`opens`) the observed node's +clean state is `related` (reviewed, `Consensus.TraceValidation.Abs`) to the declared state the event +was compared with. The proof instantiates `CCF.Sections.observation_refines` with M_tv's +`Refinement` (`Consensus.TraceValidation.Proofs.refinement`), which reduces every section to +the obligation of the `cft.h` handler it runs, each proved in +`Consensus.TraceValidation.Proofs.Handlers`. +-/ + +namespace Consensus.TraceValidation.Proofs + +open CCF.Sections +open CCF.MultiNodeTransitionSystem (nodeState) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Ev) + +/-- Every action of the guarded clean network is a step of the specification. -/ +theorem guarded_embeds {g : CCF.Finset NodeID} {clean clean' : Consensus.Model.State} + {action : Consensus.Model.Action} + (h : guardedNext (Consensus.Model.protocol g) admit clean action = some clean') + : Consensus.Model.networkStep g clean action = some clean' := by + cases action with + | deliver envelope => exact h + | «local» node input => + have h' : (if admit (without clean.nodes node) node input = true then + CCF.MultiNodeTransitionSystem.next (Consensus.Model.protocol g) clean (.local node input) + else none) = some clean' := h + by_cases admitted : admit (without clean.nodes node) node input = true + · simp only [admitted, ite_true] at h' + cases input with + | initAsBackup entries => + have prefix_ : Consensus.Model.committedPrefixOf clean entries = true := by + simp only [admit, List.any_eq_true] at admitted + obtain ⟨⟨other, c⟩, member, holds⟩ := admitted + simp only [Consensus.Model.committedPrefixOf, List.any_eq_true] + exact ⟨(other, c), (List.mem_filter.mp member).1, holds⟩ + simp only [Consensus.Model.networkStep, prefix_, ite_true] + exact h' + | _ => exact h' + · simp [admitted] at h' + +/-- +If the validator accepts the per-node streams, its observations are exactly the +streams' events, in order per node; each is consistent (by the reviewed `Exec.observe`) +with the declared state and the model's label at its trace point; and they refine the +clean specification at every lock-taking event. +-/ +theorem validate_refines {env : Env} + {streams : List (NodeID × List Ev)} {v : Verdict} (h : validate env streams = .ok v) + : streamsMatch streams v.observations = true + /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) + /\ CCF.ObservationRefinement.Refines + (Consensus.Model.transitionSystem env.genesis v.keys) nodeState + (fun node clean declared => + related env.names node clean declared.1 = true) + opens v.observations := by + obtain ⟨accepts, _, matches_, nonempty, consistent⟩ := validate_sound h + exact ⟨matches_, consistent, observation_refines (refinement env (obligations env)) declare + (fun node clean declared => related env.names node clean declared.1 = true) + (fun node c l h idle => factors env node c l h idle) (frame env) v.keys _ _ (fun _ init keys => ⟨nonempty, keys, init⟩) + (fun _ _ _ step => guarded_embeds step) v.observations accepts⟩ + +end Consensus.TraceValidation.Proofs From 62722a340de716e34574dcb704115e2c1635f651 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:10:35 +0000 Subject: [PATCH 16/25] Document trace validation and its known differences from the specification The consensus README, the replay README and the architecture docs now describe the M_tv validator and what acceptance means. The replay README lists the behaviours of cft.h that validation rejects because the clean model cannot express them, with a reachable scenario for each, and what validation tolerates, so a rejected real capture can be triaged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- doc/architecture/verification.rst | 2 +- lean/AGENT.md | 23 +++--- lean/consensus/README.md | 12 +-- lean/consensus/replay/README.md | 118 +++++++++++++++++++++--------- 4 files changed, 105 insertions(+), 50 deletions(-) diff --git a/doc/architecture/verification.rst b/doc/architecture/verification.rst index 300e17fa852e..ef561b04b14b 100644 --- a/doc/architecture/verification.rst +++ b/doc/architecture/verification.rst @@ -37,7 +37,7 @@ Lean packages - The :doc:`CCF consensus protocol `, as implemented in :ccf_repo:`src/consensus/aft/cft.h`. Proved properties include election safety (no two primaries in the same term), prefix-comparability of committed logs, and that every positive commit index points to a signature entry. A joining node may initialize from another node's committed ledger prefix, as when installing a snapshot; the join protocol is not modelled. - - :ccf_repo:`consensus-replay ` replays traces of the consensus scenarios run by the native ``cft_driver``. + - :ccf_repo:`consensus-replay ` validates traces of the consensus scenarios run by the native ``cft_driver``, and of real nodes, against a model of ``cft.h`` with one step per trace point, and relates each accepted trace to the protocol model by a refinement theorem. * - :ccf_repo:`consistency ` - CCF's externally visible consistency semantics, including :ref:`transaction status `, for a simple append-and-read application with forwarded reads, elections and invalidation. The primary guarantee is that committed writes serialize in transaction ID order, and that this order respects the real-time order of requests and their initial responses. diff --git a/lean/AGENT.md b/lean/AGENT.md index 4d68e4aec1eb..1b9ff7f270a6 100644 --- a/lean/AGENT.md +++ b/lean/AGENT.md @@ -13,17 +13,17 @@ To be clear being able to save 1 line of human readable code at the cost of 1000 Within a model's library directory, use this layout: -| Location | Responsibility | -| ---------------------- | ---------------------------------------------------------------------------------------------------- | -| `Model.lean` | Assemble the executable model, including configuration and network composition. | -| `Model/` | Model-specific definitions and transitions. For disaster recovery, this includes `Model/Local.lean`. | -| `../common/CCF/` | Reusable transition systems, network composition, and execution definitions in the `CCF` namespace. | -| `Properties.lean` | State safety theorems and witness lemmas explicitly, linked to checked implementations. | -| `Properties/` | Definitions needed to state and understand those claims, such as state and trace predicates. | -| `Proofs/` | Supporting derivations, ghost state, strengthening invariants, and correspondence proofs. | -| `Tests/` | Executable model checks and regression cases. | -| `TraceValidation.lean` | Replay recorded implementation traces through the executable model. | -| `TraceValidation/` | Parsing and ordering of those traces, for `TraceValidation.lean`. | +| Location | Responsibility | +| ---------------------- | ----------------------------------------------------------------------------------------------------- | +| `Model.lean` | Assemble the executable model, including configuration and network composition. | +| `Model/` | Model-specific definitions and transitions. For disaster recovery, this includes `Model/Local.lean`. | +| `../common/CCF/` | Reusable transition systems, network composition, and execution definitions in the `CCF` namespace. | +| `Properties.lean` | State safety theorems and witness lemmas explicitly, linked to checked implementations. | +| `Properties/` | Definitions needed to state and understand those claims, such as state and trace predicates. | +| `Proofs/` | Supporting derivations, ghost state, strengthening invariants, and correspondence proofs. | +| `Tests/` | Executable model checks and regression cases. | +| `TraceValidation.lean` | State that accepted implementation traces refine the model. | +| `TraceValidation/` | Declared state, trace events, observation, state mapping, implementation model, validator and proofs. | ## Dependency direction @@ -78,6 +78,7 @@ Moving ghost definitions into `Properties/` merely to remove an import does not Review the model, full statements and proof links in `Properties.lean`, and the property helpers used by those statements. Keep the detailed proof implementations machine-checked and within the axiom allowlist. +For trace validation, review the files that `consensus/replay/README.md` lists; its proofs under `TraceValidation/Proofs/` follow the same rule. Retain the package-level import root, whole-package import coverage with `lake exe check-imports`, and kernel and axiom-dependency checks with `lake check`. The proof entrypoint does not replace either check. diff --git a/lean/consensus/README.md b/lean/consensus/README.md index 66fdae65fa8d..7bfdcdecfd2e 100644 --- a/lean/consensus/README.md +++ b/lean/consensus/README.md @@ -15,6 +15,8 @@ It assumes familiarity with the [CCF consensus protocol documentation](../../doc | Safety theorems and witness lemmas | [`Properties.lean`](Consensus/Properties.lean) | | Valid initial memberships | [`Properties/Config.lean`](Consensus/Properties/Config.lean) | | Supporting proofs and executions | [`Proofs/`](Consensus/Proofs) | +| Trace validation: statement | [`TraceValidation.lean`](Consensus/TraceValidation.lean) (`accepted_refines`) | +| Trace validation: model and validator | [`TraceValidation/`](Consensus/TraceValidation) (declared state, observation, `abs`, M_tv, validator, proofs) | | Action-trace tests | [`Tests/CanonicalTraces.lean`](Consensus/Tests/CanonicalTraces.lean) | Transition systems, traces, effects and network composition come from the local [`ccf_common` package](../common/README.md). @@ -53,7 +55,7 @@ Append regressions check configuration heartbeats followed by flushing, pre-comm These are regression examples, not exhaustive checking. `lake check` checks both default targets, `Consensus` and `consensus-replay`, in one invocation. It runs without sandboxing here, so build-time code must be trusted. -`Consensus.lean` reexports `Properties.lean` and the replay API transitively, while importing tests privately. +`Consensus.lean` reexports `Properties.lean`, `TraceValidation.lean` and the diagnostic `TraceValidation/Lockstep.lean`, while importing tests privately. The shared `check-imports` command rejects modules missing from that import closure. ## Proofs @@ -68,8 +70,8 @@ The safety-invariant proof remains independent of the witness construction, allo To list the safety-invariant declarations used by the exported theorems, run `lake env lean scripts/invariant-dependencies.lean`. -## Trace replay +## Trace validation -The [trace replayer](replay/README.md) checks finite driver observations against direct model transitions, independently of proofs. -It checks each native send against the model, delivers any matching queued packet, treats undelivered packets as lost, and never repairs model state. -The current native Fluentd capture path and replay's assurance limits are documented there. +The [trace validator](replay/README.md) checks traces of `cft.h`, from the native driver or from real nodes, against M_tv, a model of `cft.h` with one step per trace point, and checks every lock hold against the clean model's `Node.step`. +[`TraceValidation.lean`](Consensus/TraceValidation.lean) states what acceptance means: the trace refines `Consensus.Model.transitionSystem` at every lock-taking event, through the reviewed abstraction of the declared `cft.h` state. +The capture path, the validation contract and the files to review are documented there. diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 3a6c9bf28184..75b4c2249891 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -1,7 +1,7 @@ -# CCF consensus protocol trace replay +# CCF consensus protocol trace validation -Replay native `cft_driver` captures against the Lean model of the CCF consensus protocol. -The existing `cft_scenario_test` collects native traces; `consensus-replay` validates one trace per invocation. +Validate traces of [`cft.h`](../../../src/consensus/aft/cft.h) against M_tv, a Lean model of `cft.h` that takes one step per trace point, and check that every accepted trace refines the [clean consensus model](../README.md). +The `consensus-replay` executable validates captures from the native `cft_driver` and from real nodes. ## Run replay @@ -11,9 +11,13 @@ From `lean/consensus`, build the validator and validate a saved trace: ```sh lake build --wfail consensus-replay -./.lake/build/bin/consensus-replay path/to/trace.ndjson +./.lake/build/bin/consensus-replay path/to/trace.ndjson... ``` +Each accepted trace prints `PASS` with its node, event and lock-hold counts; each rejected trace prints `FAIL` and the reason, usually the first event that the model cannot explain. +With `--refine`, an accepted trace is also checked hold by hold against the clean model (see below), and each finding prints `REFINE` and rejects the trace. +The exit status is 0 when every trace is accepted, 1 when any is rejected, and 2 on a usage error. + To generate captures, build the native driver and run the existing scenario test. The driver links the [scenarios](../../../tests/cft_scenarios/README.md), which are Lean programs, so CMake must find `lake`. Use a fresh build directory to avoid replaying stale captures from earlier runs. @@ -25,7 +29,7 @@ cmake -S ../.. -B /tmp/cft-build -GNinja cmake --build /tmp/cft-build --target cft_driver ctest --test-dir /tmp/cft-build -VV -R '^cft_scenario_test$' --no-tests=error for trace in /tmp/cft-build/consensus/raw/*.ndjson; do - ./.lake/build/bin/consensus-replay "$trace" + ./.lake/build/bin/consensus-replay --refine "$trace" done ``` @@ -34,31 +38,79 @@ The Fluentd tag is `ccf.cft`; packet message names are unprefixed, for example ` Each event's `state` field is a snapshot of `aft::State`. Events whose code reads or writes the `aft::Aft` variables `voted_for`, `votes_for_me`, `leader_id`, `is_new_follower` or `ticking` also carry those variables as top-level fields next to `state`, with their values when the event is traced; [`cft_trace_msgpack.h`](../../../src/consensus/aft/cft_trace_msgpack.h) lists the fields of each event. `voted_for` and `leader_id` are a node ID or nil, and `votes_for_me` is an array, ordered by configuration index, of `{"idx", "quorum", "votes"}` maps whose `votes` lists the sorted IDs of the nodes that voted for this node in that configuration. -Replay currently ignores these fields. - -## Replay contract - -Every protocol event must match a named rule; bootstrap selects the initial singleton membership. -Bootstrap accepts bare ticks before genesis, which native code runs asynchronously after the first node becomes leader, and a flush of the genesis entry. -Rules group related protocol events and read action inputs from those events; only top-level alternatives backtrack. -Actions must be enabled by the model. -After bootstrap, each rule emits one read-only observation before its model actions, comparing the native group's entry snapshot with the current model state. -A native `replicate` event and the entries that follow it, each starting with its `replicate_entry` event, form one group and one model append, so the model checks commit once per batch, as CCF does. -A `replicate` call rejected at its first entry traces no entries and appends nothing. - -A receive delivers any queued model envelope from its sender whose rendered packet has exactly the native packet's fields, with equal values. -It delivers the queued **model payload**, not reconstructing unrecorded native bytes; if matching envelopes differ in payload, for example in AppendEntries entries, which packets omit, replay fails with an ambiguous delivery. -An envelope that is never delivered stays queued, which models loss, so `drop_pending_to` emits no observation or action. -After each rule's actions, the envelopes they queued must equal the rule's native sends, as a multiset of target and rendered packet. -Native code does not trace the `propose_request_vote` send that follows `step_down_and_nominate_successor`, so replay counts each `step_down_and_nominate_successor` as that send. - -## Source and checks - -- [`Input.lean`](../Consensus/Replay/Input.lean): decode events, carry optional command provenance and collect identities. -- [`Reduction.lean`](../Consensus/Replay/Reduction.lean): named rules, explicit boundaries and rule-tagged snapshot checks. -- [`Interpreter.lean`](../Consensus/Replay/Interpreter.lean): boundary-state field comparisons, packet selection, send checks and model execution. -- [`ReplayMain.lean`](ReplayMain.lean): single-trace validation CLI. -- [`ReplayDelivery.lean`](../Consensus/Tests/ReplayDelivery.lean): delivery selection among equal rendered packets. -- [`cft_scenarios_runner.py`](../../../tests/cft_scenarios_runner.py): existing native scenario runner and capture generation. - -See [failure fixtures](fixtures/README.md) for examples and expected diagnostics. + +## Validation contract + +A trace is a file of records `{process_id, h_ts, msg}`. +Records whose `msg` has a `cmd` are driver provenance and are ignored; every other record is one trace point of the node named by `msg.state.node_id` (`msg.node_id` for `retired_committed_tx`, which has no snapshot). +Records are split into one stream per node, ordered by `h_ts`; all of a node's records must come from one process. +`h_ts` is never compared across nodes, so captures with one process per node, or with shuffled lines, validate the same way. + +Each node's state is the declared state ([`State`](../Consensus/TraceValidation/State.lean)), one field per `cft.h` member, extended by the position inside the current lock hold. +[`Aft`](../Consensus/TraceValidation/Aft.lean) mirrors the `cft.h` functions statement by statement; it takes one step per trace point, running the code from the previous trace point up to this one. +The first trace point of a lock hold opens a section; a silent release, inserted when the node's next event opens another section or its stream ends, runs the code after the last trace point and publishes the hold's sends. +Where `cft.h` depends on something no trace point records, such as a timer or a batch size, the handler follows the branch that the node's next event requires. + +At every trace point, [`Observe`](../Consensus/TraceValidation/Observe.lean) compares the event with the declared state there: the `state` snapshot, the per-event state fields such as `match_idx`, `sent_idx`, `configurations` and `commit.idx`, and the values the model computed, such as packets. +Every field is either compared or consumed as the step's input, as `Observe.inputFields` lists; an event with a missing or unexpected field is rejected. +This includes the `aft::Aft` variables above, which are compared on exactly the events that carry them. +A receive delivers a message that its sender has already published with an identical packet; a dropped message stays in the network. + +A node that joined from a snapshot holds only the ledger after it: its declared state has the snapshot's index and view (`base`, `baseView`) and the entries after the index. +Each release checks that the base is a committed signature in that view, and that the hold's outcome does not depend on the entries up to the base, which the node does not hold. +For the proof only, the model takes those entries, which no trace point records, from another node's committed ledger. + +With `--refine`, [`Lockstep`](../Consensus/TraceValidation/Lockstep.lean) also checks every release against the [clean model](../Consensus/Model/Node.lean): the clean inputs of the hold are rebuilt, the clean `Node.step`s run from the node's clean state, and the result must agree ([`Abs`](../Consensus/TraceValidation/Abs.lean)) with the declared state, with the same sends in the same order, and satisfy the invariants the proofs use. +This check is a diagnostic and a regression oracle for the proofs, not part of what acceptance means. + +## What acceptance means + +An accepted trace is a behaviour of the clean model under a state refinement mapping. +The mapping is reviewed: the declared state ([`State`](../Consensus/TraceValidation/State.lean)) and the relation `related` of a clean node state to it ([`Abs`](../Consensus/TraceValidation/Abs.lean)). +The behaviour refinement is the one theorem [`TraceValidation.lean`](../Consensus/TraceValidation.lean) states, using the refinement statement of [`CCF.Observation`](../../common/CCF/Observation.lean). +`accepted_refines`: the validator observed exactly the streams' events, each consistent with the declared state at its trace point, and there is one trace of `Consensus.Model.transitionSystem` in which, at every lock-taking event, the node's clean state is `related` to its declared state. +Its proof, in [`TraceValidation/Proofs`](../Consensus/TraceValidation/Proofs), is not reviewed and uses only the standard axioms. +Properties are stated and proved of the clean model only ([`Properties.lean`](../Consensus/Properties.lean)); trace validation claims nothing more of the implementation than this refinement. +The proof reduces it to one obligation per `cft.h` handler, each stated in [`Obligation.lean`](../Consensus/TraceValidation/Proofs/Obligation.lean) and proved in its own file under [`Proofs/Handlers/`](../Consensus/TraceValidation/Proofs/Handlers) ([`Handlers.lean`](../Consensus/TraceValidation/Proofs/Handlers.lean) assembles them). + +To review: `TraceValidation.lean`, `CCF.Observation`, and `State`, `Event`, `Action`, `Observe` and `Abs` in [`TraceValidation/`](../Consensus/TraceValidation). +`Handler`, `Aft`, `Machine` and `Validator` are the executable model and its scheduler, and `Invariant` and `Lockstep` the invariants and the diagnostic check; the proofs cover them. +The decoder (`Event`) and the per-node split are trusted. + +## Known implementation and specification differences + +Validation rejects some behaviours that `cft.h` can show but the clean model cannot express. +Each such diagnostic says "accepted by the implementation, rejected by validation" and "known implementation and specification difference". +A trace that shows one of them is rejected, even though the implementation behaved as designed. + +| # | Where | `cft.h` | Clean model | Reachable scenario | +| --- | ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| S1 | `Invariant` `peers`, and `Aft` `rollback` ("peers kept across rollback") | Keeps a peer in `all_other_nodes` across a rollback. | Drops it: a node's peers are its eligible peers. | n0 appends a configuration adding n3, does not replicate it, and is partitioned. n1 wins the next view. When n0 rolls the configuration back, it keeps n3. | +| S2 | `Invariant` `empty_ledger_alone` | Keeps peers across a rollback to an empty ledger. | A node without a log has no eligible peers. | As S1, when the rolled-back configuration was the node's only one. | +| S3 | `Aft` `electionGuard` ("election guard") | Starts an election when it is ticking and not retired-committed. | Also needs a role and membership of a signed configuration. | `ticking` is sticky. Leader n0 appends a configuration adding n3, then a signature, which reach only n3. n0 is partitioned, and n1, which lacks them, wins. n3 rolls them back, still ticks, times out and stands for election. The native driver also ticks nodes that have no role. | +| S4 | `Aft` `setRetiredCommitted` ("successor nomination") | Nominates after erasing the peers whose retirement commits in the same commit. | Nominates from the peers as they were before the commit. | One `remove_node` proposal retires primary n0 and n1, and one `set_retired_committed` transaction marks both. When it commits, `cft.h` erases n1 before it nominates; the clean model may pick n1, for example when n1 has the highest match index. | +| S5 | `Aft` `retiredHooks` ("retirement confirmation") | `hooks.h` confirms a retired node again whenever its record is rewritten with `retired_committed`. | Confirms only completed, unconfirmed retirements. | A second `remove_node` proposal for a retired-committed node, before `retired_nodes_cleanup` deletes its row, rewrites the record. | +| S6 | `Aft` `retiredHooks` ("empty configuration") | `hooks.h` adds an empty configuration when the last node removes itself. | Requires a non-empty configuration. | `remove_node` of the only node of a one-node service, which the default constitution does not forbid. | +| S7 | `Aft` `recvRequestVoteResponse` (pre-votes) | Ignores a granted pre-vote from a node that is in no active configuration. | Counts the pre-vote of any eligible peer. | Pre-vote candidate n1 asks n3 in view 2. n1 learns a committed configuration without n3 and steps down. It starts a new pre-vote in view 2, and n3's late grant arrives. | +| S8 | `Aft` `recvProposeRequestVote` | Ignores the proposal on a node that is not ticking. | Starts an election. | A joiner is named by a configuration that a configuration without it supersedes before the next signature. It never ticks, but it is a member of a signed active configuration, so the primary can nominate it. | +| S9 | `Machine` `ghostFree` ("depends on the ledger up to the snapshot base") | A primary that joined from a snapshot sends AppendEntries below its snapshot base; the host ([`node_connections.h`](../../../src/host/node_connections.h)) cannot read those entries and drops the message. | Sends the entries. | n3 joins from a snapshot at seqno s and later becomes primary while n1 lags below s, for example after a long partition. n1 never catches up from n3, which is a liveness issue. | + +Every other rejection is of something `cft.h` cannot do: a mirror of one of its assertions or throws, a fact about the trace format, a step that would need two leaders in one view or a faulty peer, or an entry that CCF never writes. + +Validation also tolerates the following without checking them exactly. + +- **T1:** a node that joined from a snapshot may declare its first configuration at a later index than the ledger has it, at or below its commit index, because the snapshot hook reports the version of the last write to the nodes table. + `cft.h` compares that index only with later configurations and with indexes above the commit index, so the behaviour is the same. +- **T2:** inputs that no trace point records are read from the node's next events: the batch size, `request_timeout`, the CheckQuorum acknowledgement timers, the flush threshold, the out-of-lock hook's snapshot version and `force_become_primary`. + Every consequence of each one is still checked. +- **T3:** the view history of a node that joined from a snapshot is not traced, so M_tv assumes that every index up to the snapshot base is in the snapshot's view. + Only the base itself is read, and it is a committed signature in that view; any read below the base is rejected (S9). +- **T4:** on an election timeout with no configurations, `cft.h` returns early; the proof matches it with no clean step. + +## Source + +- [`TraceValidation/`](../Consensus/TraceValidation): declared state, events, observation, abstraction, M_tv, the validator and proofs. +- [`ReplayMain.lean`](ReplayMain.lean): validation CLI. +- [`cft_scenarios_runner.py`](../../../tests/cft_scenarios_runner.py): native scenario runner and capture generation. + +See [fixtures](fixtures/README.md) for examples and expected diagnostics. From 1b8dcbe54b03aab32d1179522aafb210cb6e9cff Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:26:51 +0000 Subject: [PATCH 17/25] State that the observations are the streams' events, not just their lines `streamsMatch` compared only trace line numbers, so `accepted_refines` did not say that the observed events are the input: observations with the right lines but other events, or for nodes without a stream, satisfied it. It now says that every observation is of a stream's node and that each node's observed events are its stream's events, in order. The validator takes each scheduled action's event from the streams (`restream`) before certifying, so this holds by construction; the proof does not need a lawful equality on JSON. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus/TraceValidation.lean | 2 +- .../Consensus/TraceValidation/Abs.lean | 12 +- .../TraceValidation/Proofs/Refinement.lean | 2 +- .../TraceValidation/Proofs/Validator.lean | 227 +++++++++++++++++- .../Consensus/TraceValidation/Validator.lean | 65 +++-- 5 files changed, 280 insertions(+), 28 deletions(-) diff --git a/lean/consensus/Consensus/TraceValidation.lean b/lean/consensus/Consensus/TraceValidation.lean index a0f6cead5aae..b17d4575095c 100644 --- a/lean/consensus/Consensus/TraceValidation.lean +++ b/lean/consensus/Consensus/TraceValidation.lean @@ -42,7 +42,7 @@ the declared state the event was compared with. -/ theorem accepted_refines {env : Env} {streams : List (NodeID × List Ev)} {v : Verdict} (h : validate env streams = .ok v) - : streamsMatch streams v.observations = true + : streamsMatch streams v.observations /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) /\ CCF.ObservationRefinement.Refines (Consensus.Model.transitionSystem env.genesis v.keys) nodeState diff --git a/lean/consensus/Consensus/TraceValidation/Abs.lean b/lean/consensus/Consensus/TraceValidation/Abs.lean index 2e0c1d405ab5..0d7cee8e4b00 100644 --- a/lean/consensus/Consensus/TraceValidation/Abs.lean +++ b/lean/consensus/Consensus/TraceValidation/Abs.lean @@ -171,10 +171,12 @@ def opens (e : Ev) : Bool := Exec.heads.contains e.function /-- One observation: the node, its event, and its declared state and label at the event. -/ abbrev Obs := CCF.ObservationRefinement.Observation NodeID Ev (Declared × Exec.Label) -/-- Every node's observed events are its stream, in order (by trace line). -/ -def streamsMatch (streams : List (NodeID × List Ev)) (obs : List Obs) : Bool := - streams.all - fun (k, evs) => - ((obs.filter (·.node == k)).map (·.event.line)) == evs.map (·.line) +/-- +The observations are exactly the streams' events: every observation is of a node that has a +stream, and every node's observed events are its stream's events, in order. +-/ +def streamsMatch (streams : List (NodeID × List Ev)) (obs : List Obs) : Prop := + (forall o, o ∈ obs -> o.node ∈ streams.map Prod.fst) + /\ forall k evs, (k, evs) ∈ streams -> (obs.filter (·.node == k)).map (·.event) = evs end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean index 670d4804db6e..a46060f9f2eb 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean @@ -64,7 +64,7 @@ clean specification at every lock-taking event. -/ theorem validate_refines {env : Env} {streams : List (NodeID × List Ev)} {v : Verdict} (h : validate env streams = .ok v) - : streamsMatch streams v.observations = true + : streamsMatch streams v.observations /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) /\ CCF.ObservationRefinement.Refines (Consensus.Model.transitionSystem env.genesis v.keys) nodeState diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean index 3fa76bcfb6b6..69e60439b811 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean @@ -110,6 +110,223 @@ theorem certify_sound {env : Env} {keys : List NodeID} {ticking : NodeID -> Bool · cases h · cases h +/-! ## The observations are the streams' events -/ + +/-- The node and event of each action that emits an observation. -/ +def actionEvents : List GAction -> List (NodeID × Ev) + | [] => [] + | .event k e :: as => (k, e) :: actionEvents as + | .deliver x e :: as => (x.target, e) :: actionEvents as + | .release _ :: as => actionEvents as + +theorem emitsCheck_events {env : Env} + : forall {s : GState} {actions : List GAction} {f : GState} {obs : List Obs}, + emitsCheck env s actions = some (f, obs) + -> obs.map (fun o => (o.node, o.event)) = actionEvents actions + | s, [], f, obs, h => by + simp only [emitsCheck, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + rfl + | s, .event node e :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · split at h + · cases h + · split at h + · cases h + · rename_i f' os tail + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp [actionEvents, emitsCheck_events tail] + | s, .deliver x e :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · split at h + · cases h + · split at h + · cases h + · rename_i f' os tail + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + simp [actionEvents, emitsCheck_events tail] + | s, .release node :: rest, f, obs, h => by + simp only [emitsCheck] at h + split at h + · cases h + · rw [actionEvents] + exact emitsCheck_events h + +theorem certify_events {env : Env} {keys : List NodeID} {ticking : NodeID -> Bool} + {actions : List GAction} {obs : List Obs} + (h : certify env keys ticking actions = some obs) + : keys.Nodup /\ obs.map (fun o => (o.node, o.event)) = actionEvents actions := by + unfold certify at h + split at h + · rename_i guards + split at h + · rename_i f os run + split at h + · simp only [Option.some.injEq] at h + subst h + exact ⟨guards.1, emitsCheck_events run⟩ + · cases h + · cases h + · cases h + +theorem lookup_mem {k : NodeID} {b : List Ev} + : forall {rest : List (NodeID × List Ev)}, + rest.lookup k = some b -> k ∈ rest.map Prod.fst + | [], h => by simp at h + | (j, evs) :: rest, h => by + by_cases eq : k = j + · simp [eq] + · have ne : (k == j) = false := by simpa using eq + simp only [List.lookup_cons, ne] at h + exact List.mem_cons_of_mem _ (lookup_mem h) + +theorem lookup_of_mem {k : NodeID} {evs : List Ev} + : forall {rest : List (NodeID × List Ev)}, + (rest.map Prod.fst).Nodup -> (k, evs) ∈ rest -> rest.lookup k = some evs + | [], _, h => by simp at h + | (j, b) :: rest, nodup, h => by + simp only [List.map_cons, List.nodup_cons] at nodup + rcases List.mem_cons.mp h with eq | mem + · simp only [Prod.mk.injEq] at eq + obtain ⟨rfl, rfl⟩ := eq + simp + · have ne : k ≠ j := by + rintro rfl + exact nodup.1 (List.mem_map.mpr ⟨_, mem, rfl⟩) + have ne : (k == j) = false := by simpa using ne + simp only [List.lookup_cons, ne] + exact lookup_of_mem nodup.2 mem + +theorem lookup_empty {k : NodeID} + : forall {rest : List (NodeID × List Ev)}, + rest.all (·.2.isEmpty) = true -> (rest.lookup k).getD [] = [] + | [], _ => rfl + | (j, evs) :: rest, h => by + simp only [List.all_cons, Bool.and_eq_true, List.isEmpty_iff] at h + by_cases eq : k = j + · simp [eq, h.1] + · have ne : (k == j) = false := by simpa using eq + simp only [List.lookup_cons, ne] + exact lookup_empty h.2 + +theorem popEvent_spec {k : NodeID} {e : Ev} + : forall {rest rest' : List (NodeID × List Ev)}, + popEvent k rest = some (e, rest') + -> rest'.map Prod.fst = rest.map Prod.fst + /\ (rest.lookup k).getD [] = e :: (rest'.lookup k).getD [] + /\ forall j, j ≠ k -> rest'.lookup j = rest.lookup j + | [], _, h => by simp [popEvent] at h + | (j, evs) :: rest, rest', h => by + unfold popEvent at h + by_cases eq : j = k + · subst eq + simp only [beq_self_eq_true, ↓reduceIte] at h + cases evs with + | nil => cases h + | cons e' es => + simp only [Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + refine ⟨rfl, by simp, fun i ne => ?_⟩ + have ne : (i == j) = false := by simpa using ne + simp [List.lookup_cons, ne] + · simp only [beq_iff_eq, eq, ↓reduceIte, Option.map_eq_some_iff, Prod.exists] at h + obtain ⟨e', r, popped, he⟩ := h + simp only [Prod.mk.injEq] at he + obtain ⟨rfl, rfl⟩ := he + obtain ⟨keys, here, others⟩ := popEvent_spec popped + have ne : (k == j) = false := by simpa using fun h => eq h.symm + refine ⟨by simp [keys], by simpa [List.lookup_cons, ne] using here, fun i ne' => ?_⟩ + by_cases ij : i = j + · simp [ij] + · have ij : (i == j) = false := by simpa using ij + simp [List.lookup_cons, ij, others i ne'] + +theorem restream_spec + : forall {rest : List (NodeID × List Ev)} {actions actions' : List GAction}, + restream rest actions = some actions' + -> (forall p, p ∈ actionEvents actions' -> p.1 ∈ rest.map Prod.fst) + /\ forall k, + ((actionEvents actions').filter (·.1 == k)).map Prod.snd + = (rest.lookup k).getD [] + | rest, [], actions', h => by + unfold restream at h + split at h + · rename_i empty + simp only [Option.some.injEq] at h + subst h + exact ⟨by simp [actionEvents], fun k => by simp [actionEvents, lookup_empty empty]⟩ + · cases h + | rest, .release k :: as, actions', h => by + simp only [restream, Option.map_eq_some_iff] at h + obtain ⟨as', tail, rfl⟩ := h + rw [actionEvents] + exact restream_spec tail + | rest, .event k e :: as, actions', h => by + simp only [restream] at h + split at h + · rename_i e' rest' popped + split at h + · simp only [Option.map_eq_some_iff] at h + obtain ⟨as', tail, rfl⟩ := h + exact step popped (restream_spec tail) + · cases h + · cases h + | rest, .deliver x e :: as, actions', h => by + simp only [restream] at h + split at h + · rename_i e' rest' popped + split at h + · simp only [Option.map_eq_some_iff] at h + obtain ⟨as', tail, rfl⟩ := h + exact step popped (restream_spec tail) + · cases h + · cases h +where + step {rest rest' : List (NodeID × List Ev)} {k : NodeID} {e : Ev} + {evs : List (NodeID × Ev)} (popped : popEvent k rest = some (e, rest')) + (tail + : (forall p, p ∈ evs -> p.1 ∈ rest'.map Prod.fst) + /\ forall k, (evs.filter (·.1 == k)).map Prod.snd = (rest'.lookup k).getD []) + : (forall p, p ∈ (k, e) :: evs -> p.1 ∈ rest.map Prod.fst) + /\ forall j, + (((k, e) :: evs).filter (·.1 == j)).map Prod.snd + = (rest.lookup j).getD [] := by + obtain ⟨keys, here, others⟩ := popEvent_spec popped + refine ⟨fun p mem => ?_, fun j => ?_⟩ + · rcases List.mem_cons.mp mem with eq | mem + · subst eq + cases found : rest.lookup k with + | none => simp [found] at here + | some b => exact lookup_mem found + · rw [← keys] + exact tail.1 p mem + · by_cases eq : j = k + · subst eq + simp [here, tail.2] + · have ne : (k == j) = false := by simpa using fun h => eq h.symm + simp [ne, tail.2, others j eq] + +theorem conclude_streams {env : Env} {ticking : NodeID -> Bool} + {streams : List (NodeID × List Ev)} {actions : List GAction} {obs : List Obs} + {scheduled : List GAction} (restreamed : restream streams scheduled = some actions) + (certified : certify env (streams.map Prod.fst) ticking actions = some obs) + : streamsMatch streams obs := by + obtain ⟨nodup, events⟩ := certify_events certified + obtain ⟨members, perNode⟩ := restream_spec restreamed + refine ⟨fun o mem => ?_, fun k evs mem => ?_⟩ + · apply members (o.node, o.event) + rw [← events] + exact List.mem_map.mpr ⟨o, mem, rfl⟩ + · have := perNode k + rw [lookup_of_mem nodup mem, ← events, List.filter_map, List.map_map] at this + simpa [Function.comp_def] using this + /-- **T1.** If the validator accepts, the acceptance predicate holds of its observations: a run of M_tv's event-granular network over exactly the stream nodes, from an initial state, @@ -120,7 +337,7 @@ theorem validate_sound {env : Env} {streams : List (NodeID × List Ev)} {v : Ver (h : validate env streams = .ok v) : Accepts (machine env) declare v.keys v.observations /\ v.keys = streams.map Prod.fst - /\ streamsMatch streams v.observations = true + /\ streamsMatch streams v.observations /\ env.genesis.Nonempty /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) := by unfold validate at h @@ -132,13 +349,13 @@ theorem validate_sound {env : Env} {streams : List (NodeID × List Ev)} {v : Ver dsimp only at h split at h · cases h - · rename_i obs certified + · rename_i actions restreamed split at h - · rename_i matches_ + · cases h + · rename_i obs certified simp only [Except.ok.injEq] at h subst h obtain ⟨accepts, nonempty, consistent⟩ := certify_sound certified - exact ⟨accepts, rfl, matches_, nonempty, consistent⟩ - · cases h + exact ⟨accepts, rfl, conclude_streams restreamed certified, nonempty, consistent⟩ end Consensus.TraceValidation.Proofs diff --git a/lean/consensus/Consensus/TraceValidation/Validator.lean b/lean/consensus/Consensus/TraceValidation/Validator.lean index b01dea15bb84..c86ca93e5d77 100644 --- a/lean/consensus/Consensus/TraceValidation/Validator.lean +++ b/lean/consensus/Consensus/TraceValidation/Validator.lean @@ -15,6 +15,8 @@ node, ordered by `h_ts` within the node's process; any node whose next event is steps (receives and joiner releases may wait); a node releases when its next event is a section head or its stream has ended. It never compares `h_ts` across nodes. +`restream` takes every action's event from the streams, in order per node, and requires +every stream to be used up, so the observations are the streams' events by construction. `certify` then replays the action list with the framework's own `next` (`emitsCheck`), which yields the observation list, and checks that the run started in an initial state and ended with every lock released. `validate_sound` (in `Consensus.TraceValidation.Proofs.Validator`) turns @@ -96,6 +98,37 @@ def certify (env : Env) (keys : List NodeID) (ticking : NodeID -> Bool) else none +/-- Take node `k`'s next stream event, from the first stream of `k`. -/ +def popEvent (k : NodeID) + : List (NodeID × List Ev) -> Option (Ev × List (NodeID × List Ev)) + | [] => none + | (j, evs) :: rest => + if j == k then + match evs with + | e :: es => some (e, (j, es) :: rest) + | [] => none + else + (popEvent k rest).map fun (e, rest') => (e, (j, evs) :: rest') + +/-- +Take the events of the actions from the streams, in order per node (checking the trace +line), and require every stream to be used up: the observations are then the streams' +events by construction. +-/ +def restream : List (NodeID × List Ev) -> List GAction -> Option (List GAction) + | rest, [] => if rest.all (·.2.isEmpty) then some [] else none + | rest, .release k :: as => (restream rest as).map (.release k :: ·) + | rest, .event k e :: as => + match popEvent k rest with + | some (e', rest') => + if e'.line == e.line then (restream rest' as).map (.event k e' :: ·) else none + | none => none + | rest, .deliver x e :: as => + match popEvent x.target rest with + | some (e', rest') => + if e'.line == e.line then (restream rest' as).map (.deliver x e' :: ·) else none + | none => none + /-! ## Scheduling (untrusted search for an action list) -/ /-- A release, for the diagnostic lock-step check. -/ @@ -279,22 +312,22 @@ def conclude (env : Env) (ticking : NodeID -> Bool) (streams : List (NodeID × L (w : World) : Except String Verdict := let keys := streams.map Prod.fst - match certify env keys ticking w.actions.toList with - | none => .error "internal: the scheduled run does not certify" - | some observations => - if streamsMatch streams observations then - .ok - { - keys, - releases := w.releases.toList, - actions := w.actions.toList, - observations, - sections := w.sections - waits := w.waits, - inFlight := w.st.network.length - } - else - .error "internal: observations differ from the streams" + match restream streams w.actions.toList with + | none => .error "internal: the scheduled events differ from the streams" + | some actions => + match certify env keys ticking actions with + | none => .error "internal: the scheduled run does not certify" + | some observations => + .ok + { + keys, + releases := w.releases.toList, + actions, + observations, + sections := w.sections + waits := w.waits, + inFlight := w.st.network.length + } /-- The initial `ticking` of a node: the value carried by its first event that carries one From 5b1c3c74d30da106b8e651c7c2dbbe8cb457b628 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:29:45 +0000 Subject: [PATCH 18/25] Require every trace point's declared fields, uniformly Only the label and the `aft::Aft` variables were required to be present, so an event could omit a field that is a projection of the declared state, such as `replicate_entry.seqno` or a peer's `match_idx`, or even `state`, and still be accepted. `Observe.traceFields` now lists the fields of each trace point as `cft_trace_msgpack.h` declares them, with `recv_request_vote` split by message type; an event must carry exactly those. The `aft::Aft` variable projections no longer need their own per-point table. Add invalid fixtures for a missing `seqno` and a missing `match_idx`. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Consensus/TraceValidation/Observe.lean | 96 +++++++++++++------ lean/consensus/replay/README.md | 3 +- lean/consensus/replay/fixtures/README.md | 2 + .../fixtures/invalid/missing-match-idx.ndjson | 64 +++++++++++++ .../fixtures/invalid/missing-seqno.ndjson | 64 +++++++++++++ 5 files changed, 198 insertions(+), 31 deletions(-) create mode 100644 lean/consensus/replay/fixtures/invalid/missing-match-idx.ndjson create mode 100644 lean/consensus/replay/fixtures/invalid/missing-seqno.ndjson diff --git a/lean/consensus/Consensus/TraceValidation/Observe.lean b/lean/consensus/Consensus/TraceValidation/Observe.lean index 99f8b856e6bd..604a222f1676 100644 --- a/lean/consensus/Consensus/TraceValidation/Observe.lean +++ b/lean/consensus/Consensus/TraceValidation/Observe.lean @@ -15,7 +15,8 @@ public import Consensus.TraceValidation.Action Each trace event maps to exactly one M_tv action (`actionOf`). After the model steps that action, the event is observed against the declared state (`Declared`) at the trace point and the model's label (`observe`). Every field of every event is in -exactly one of these classes, or both of the last two: +exactly one of these classes, or both of the last two, and every event carries exactly +the fields its trace point declares (`traceFields`): * `state`, and the per-point fields in `stateFields`: projections of `Declared`; * `inputFields`: consumed by the action (message identity, untraced choices, @@ -29,6 +30,54 @@ namespace Consensus.TraceValidation.Exec open Lean +/-- +The fields of each trace point besides `function`, as `cft_trace_msgpack.h` declares them. +An event must carry exactly these. +-/ +def traceFields (e : Ev) : List String := + match e.function with + | "send_append_entries" => ["state", "packet", "to_node_id", "match_idx", "sent_idx"] + | "recv_append_entries_response" => + ["state", "packet", "from_node_id", "match_idx", "sent_idx"] + | "recv_append_entries" => + ["state", "packet", "from_node_id", "leader_id", "is_new_follower"] + | "execute_append_entries_sync" => ["state", "from_node_id", "ticking"] + | "send_append_entries_response" + | "send_request_vote" + | "send_request_vote_response" => ["state", "packet", "to_node_id"] + -- Only a regular vote request reads `voted_for` and `leader_id`. + | "recv_request_vote" => + match e.msg.getObjValD "packet" |>.getObjValD "msg" |>.getStr? with + | .ok "request_vote" => + ["state", "packet", "from_node_id", "voted_for", "leader_id"] + | _ => ["state", "packet", "from_node_id"] + | "recv_request_vote_response" => ["state", "packet", "from_node_id", "votes_for_me"] + | "recv_propose_request_vote" => ["state", "packet", "from_node_id", "ticking"] + | "tick" => ["state", "ticking"] + | "become_pre_vote_candidate" + | "become_leader" => ["state", "configurations", "votes_for_me", "leader_id"] + | "become_candidate" => + ["state", "configurations", "voted_for", "votes_for_me", "leader_id"] + | "become_follower" => + [ + "state", + "configurations", + "voted_for", + "votes_for_me", + "leader_id", + "is_new_follower" + ] + | "nomination" | "batch_flush" | "replicate" => ["state"] + | "step_down_and_nominate_successor" => + ["state", "configurations", "to_node_id", "leader_id"] + | "replicate_entry" => ["state", "view", "seqno", "globally_committable", "ticking"] + | "retired_committed_tx" => ["node_id", "seqno", "retired_node_id"] + | "init_as_backup" => ["state", "seqno", "view"] + | "add_configuration" => ["state", "configurations", "idx", "nodes", "rid"] + | "commit" => ["state", "idx", "configurations", "leader_id"] + | "drop_pending_to" => ["state", "from_node_id", "to_node_id", "packet"] + | _ => [] + /-- Fields an action consumes as input, by trace point. -/ def inputFields : String -> List String -- A receive's `from_node_id` and `packet` are labels: the delivered message's. @@ -104,33 +153,15 @@ def votesJson (vs : List (Nat × List NodeId × Nat)) : Json := ("votes", toJson (votes.mergeSort (· <= ·))) ]) -/-- -The `aft::Aft` protocol variables a trace point carries (`cft_trace_msgpack.h`), as -projections of `Declared`. A regular vote request carries `voted_for` and `leader_id`; a -pre-vote request carries neither. Every event of these points must carry them. --/ -def carried (e : Ev) (s : Declared) : List (String × Json) := - let v := ("voted_for", optId s.votedFor) - let w := ("votes_for_me", votesJson s.votesForMe) - let l := ("leader_id", optId s.leaderId) - let n := ("is_new_follower", toJson s.isNewFollower) - let t := ("ticking", toJson s.ticking) - match e.function with - | "tick" - | "replicate_entry" - | "execute_append_entries_sync" - | "recv_propose_request_vote" => [t] - | "recv_append_entries" => [l, n] - | "recv_request_vote" => - match e.msg.getObjValD "packet" |>.getObjValD "msg" |>.getStr? with - | .ok "request_vote" => [v, l] - | _ => [] - | "recv_request_vote_response" => [w] - | "become_pre_vote_candidate" | "become_leader" => [w, l] - | "become_candidate" => [v, w, l] - | "become_follower" => [v, w, l, n] - | "commit" | "step_down_and_nominate_successor" => [l] - | _ => [] +/-- The `aft::Aft` protocol variables, which some trace points carry, as projections. -/ +def carried (s : Declared) : List (String × Json) := + [ + ("voted_for", optId s.votedFor), + ("votes_for_me", votesJson s.votesForMe), + ("leader_id", optId s.leaderId), + ("is_new_follower", toJson s.isNewFollower), + ("ticking", toJson s.ticking) + ] /-- Non-snapshot fields that are projections of `Declared` at the trace point. -/ def stateFields (e : Ev) (s : Declared) : List (String × Json) := @@ -144,7 +175,7 @@ def stateFields (e : Ev) (s : Declared) : List (String × Json) := | .ok id => s.allOtherNodes.lookup id | .error _ => none [("configurations", configsJson s.configurations)] - ++ carried e s + ++ carried s ++ (match peer with | some p => [("match_idx", toJson p.matchIdx), ("sent_idx", toJson p.sentIdx)] | none => []) @@ -171,8 +202,13 @@ def compareObj (pfx : String) (model : List (String × Json)) (observed : Json) def observe (e : Ev) (s : Declared) (label : Label) : Except String Unit := do let obj ← e.msg.getObj? let proj := stateFields e s + for k in traceFields e do + unless obj.contains k do + throw s!"{k}: absent, a field of every {e.function} event" for (k, o) in obj.toList do if k == "function" then continue + unless (traceFields e).contains k do + throw s!"{k}: observed {o.compress}, not a field of {e.function} events" if k == "state" then compareObj "state." (snapshot s) o; continue match proj.lookup k <|> label.lookup k with | some m => @@ -181,7 +217,7 @@ def observe (e : Ev) (s : Declared) (label : Label) : Except String Unit := do | none => unless (inputFields e.function).contains k do throw s!"{k}: observed {o.compress}, neither observed nor consumed by the model" - for (k, m) in label ++ carried e s do + for (k, m) in label do unless obj.contains k do throw s!"{k}: absent, model {m.compress}" diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 75b4c2249891..141acd92355e 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -52,7 +52,8 @@ The first trace point of a lock hold opens a section; a silent release, inserted Where `cft.h` depends on something no trace point records, such as a timer or a batch size, the handler follows the branch that the node's next event requires. At every trace point, [`Observe`](../Consensus/TraceValidation/Observe.lean) compares the event with the declared state there: the `state` snapshot, the per-event state fields such as `match_idx`, `sent_idx`, `configurations` and `commit.idx`, and the values the model computed, such as packets. -Every field is either compared or consumed as the step's input, as `Observe.inputFields` lists; an event with a missing or unexpected field is rejected. +Every trace point has a fixed set of fields (`Observe.traceFields`, as `cft_trace_msgpack.h` declares them); an event with a missing or unexpected field is rejected. +Every field is either compared or consumed as the step's input, as `Observe.inputFields` lists. This includes the `aft::Aft` variables above, which are compared on exactly the events that carry them. A receive delivers a message that its sender has already published with an identical packet; a dropped message stays in the network. diff --git a/lean/consensus/replay/fixtures/README.md b/lean/consensus/replay/fixtures/README.md index 94ef5a57f35b..52dcef22e869 100644 --- a/lean/consensus/replay/fixtures/README.md +++ b/lean/consensus/replay/fixtures/README.md @@ -16,6 +16,8 @@ Each invalid fixture is the two-node startup capture with one change, and must b | [Reordered events](invalid/reordered-events.ndjson) | Two events of one node are swapped | The model expects a different trace point | | [Configuration mismatch](invalid/configuration-mismatch.ndjson) | An `add_configuration` hook omits a node | A later send is not explained by the open lock hold | | [Missing field](invalid/missing-field.ndjson) | `become_leader` lacks its `votes_for_me` field | `votes_for_me` is absent | +| [Missing sequence number](invalid/missing-seqno.ndjson) | A `replicate_entry` lacks its `seqno` field | `seqno` is absent | +| [Missing match index](invalid/missing-match-idx.ndjson) | A `send_append_entries` lacks its `match_idx` field | `match_idx` is absent | From `lean/consensus`, inspect a failure directly (exit status 1 is expected): diff --git a/lean/consensus/replay/fixtures/invalid/missing-match-idx.ndjson b/lean/consensus/replay/fixtures/invalid/missing-match-idx.ndjson new file mode 100644 index 000000000000..493cacdca7d4 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/missing-match-idx.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 3, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 1, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id":"3276455-1794853960018847360","h_ts":18,"msg":{"function":"send_append_entries","state":{"node_id":"0","current_view":2,"last_idx":2,"commit_idx":2,"leadership_state":"Leader","membership_state":"Active","committable_indices":[]},"packet":{"msg":"append_entries","idx":2,"prev_idx":2,"term":2,"prev_term":2,"leader_commit_idx":2,"term_of_idx":2,"contains_new_view":false},"to_node_id":"1","sent_idx":3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} diff --git a/lean/consensus/replay/fixtures/invalid/missing-seqno.ndjson b/lean/consensus/replay/fixtures/invalid/missing-seqno.ndjson new file mode 100644 index 000000000000..b6d683d692c8 --- /dev/null +++ b/lean/consensus/replay/fixtures/invalid/missing-seqno.ndjson @@ -0,0 +1,64 @@ +{"process_id": "3276455-1794853960018847360", "h_ts": 0, "msg": {"cmd": "start_node,0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 1, "msg": {"function": "become_leader", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "votes_for_me": [], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 2, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id":"3276455-1794853960018847360","h_ts":3,"msg":{"function":"replicate_entry","state":{"node_id":"0","current_view":2,"last_idx":0,"commit_idx":0,"leadership_state":"Leader","membership_state":"Active","committable_indices":[]},"view":2,"globally_committable":false,"ticking":true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 4, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 5, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 6, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 7, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 8, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 2, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 9, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 10, "msg": {"cmd": "assert_detail,0,leadership_state,Leader"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 11, "msg": {"cmd": "assert_commit_idx,0,2"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 12, "msg": {"cmd": "trust_node,2,1"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 13, "msg": {"function": "init_as_backup", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "None", "membership_state": "Active", "committable_indices": []}, "seqno": 0, "view": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 14, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": false}} +{"process_id": "3276455-1794853960018847360", "h_ts": 15, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 16, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 3, "globally_committable": false, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 17, "msg": {"function": "add_configuration", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 18, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 19, "msg": {"cmd": "replicate,2,$"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 20, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 21, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 4, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 22, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 23, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 0, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 2, "prev_idx": 2, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 24, "msg": {"function": "become_follower", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "voted_for": null, "votes_for_me": [], "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 25, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 26, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 0, "success": "FAIL"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 2}} +{"process_id": "3276455-1794853960018847360", "h_ts": 27, "msg": {"cmd": "periodic_all,10"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 28, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 29, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 0}} +{"process_id": "3276455-1794853960018847360", "h_ts": 30, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 0, "sent_idx": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 31, "msg": {"function": "tick", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 32, "msg": {"cmd": "dispatch_all"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 33, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 3, "prev_idx": 0, "term": 2, "prev_term": 0, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": null, "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 34, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 0, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 35, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [], "idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}} +{"process_id": "3276455-1794853960018847360", "h_ts": 36, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 1, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 37, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 0, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [2]}, "idx": 2, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 38, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 2, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 39, "msg": {"function": "add_configuration", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}], "idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}} +{"process_id": "3276455-1794853960018847360", "h_ts": 40, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 41, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 4, "prev_idx": 3, "term": 2, "prev_term": 2, "leader_commit_idx": 2, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 42, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 3, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 43, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 44, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 3, "success": "OK"}, "from_node_id": "1", "match_idx": 0, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 45, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 4, "success": "OK"}, "from_node_id": "1", "match_idx": 3, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 46, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [4]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 47, "msg": {"cmd": "assert_commit_idx,0,4"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 48, "msg": {"function": "replicate", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}}} +{"process_id": "3276455-1794853960018847360", "h_ts": 49, "msg": {"function": "replicate_entry", "state": {"node_id": "0", "current_view": 2, "last_idx": 4, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "view": 2, "seqno": 5, "globally_committable": true, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 50, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 51, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 4, "sent_idx": 4}} +{"process_id": "3276455-1794853960018847360", "h_ts": 52, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 4, "term": 2, "prev_term": 2, "leader_commit_idx": 4, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 53, "msg": {"function": "execute_append_entries_sync", "state": {"node_id": "1", "current_view": 2, "last_idx": 4, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4]}, "from_node_id": "0", "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 54, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 2, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [4, 5]}, "idx": 4, "configurations": [{"idx": 1, "nodes": {"0": {"address": ":"}}, "rid": 1}, {"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 55, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 56, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 4, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 57, "msg": {"function": "commit", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 58, "msg": {"function": "tick", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "ticking": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 59, "msg": {"function": "send_append_entries", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "to_node_id": "1", "match_idx": 5, "sent_idx": 5}} +{"process_id": "3276455-1794853960018847360", "h_ts": 60, "msg": {"function": "recv_append_entries", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "packet": {"msg": "append_entries", "idx": 5, "prev_idx": 5, "term": 2, "prev_term": 2, "leader_commit_idx": 5, "term_of_idx": 2, "contains_new_view": false}, "from_node_id": "0", "leader_id": "0", "is_new_follower": true}} +{"process_id": "3276455-1794853960018847360", "h_ts": 61, "msg": {"function": "commit", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 4, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": [5]}, "idx": 5, "configurations": [{"idx": 3, "nodes": {"0": {"address": ":"}, "1": {"address": ":"}}, "rid": 3}], "leader_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 62, "msg": {"function": "send_append_entries_response", "state": {"node_id": "1", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Follower", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "to_node_id": "0"}} +{"process_id": "3276455-1794853960018847360", "h_ts": 63, "msg": {"function": "recv_append_entries_response", "state": {"node_id": "0", "current_view": 2, "last_idx": 5, "commit_idx": 5, "leadership_state": "Leader", "membership_state": "Active", "committable_indices": []}, "packet": {"msg": "append_entries_response", "term": 2, "last_log_idx": 5, "success": "OK"}, "from_node_id": "1", "match_idx": 5, "sent_idx": 5}} From a58459557c2da61553962a95a0bceae4c7cf67d6 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:35:16 +0000 Subject: [PATCH 19/25] Take a snapshot joiner's view history from the donor A node joining from a snapshot taken after an election receives a term history spanning several views. fillSnapshot rejected such snapshots, assuming every entry up to the base was in the snapshot's view, so real services were rejected. Take the joiner's view history up to the base from the donor, which equals the snapshot's because both assign each committed index its entry's term, and check only that the base is a signature in the snapshot's view. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../Consensus/TraceValidation/Aft.lean | 13 +++--- .../Consensus/TraceValidation/Machine.lean | 23 +++++++---- .../Proofs/Handlers/InitAsBackup.lean | 40 ++++++++----------- lean/consensus/replay/README.md | 5 ++- 4 files changed, 41 insertions(+), 40 deletions(-) diff --git a/lean/consensus/Consensus/TraceValidation/Aft.lean b/lean/consensus/Consensus/TraceValidation/Aft.lean index e8d1c8b78e19..e62062aa7f01 100644 --- a/lean/consensus/Consensus/TraceValidation/Aft.lean +++ b/lean/consensus/Consensus/TraceValidation/Aft.lean @@ -1059,7 +1059,7 @@ def nominateSuccessor : M Unit := do trace "nomination" nominateSuccessorUnsafe -/-- `init_as_backup(index, term, {})`, as the driver calls it for a joiner. -/ +/-- `init_as_backup(index, term, term_history)` for a joiner; `term_history` is untraced. -/ def initAsBackup : M Unit := do trace "init_as_backup" let index ← inNat "seqno" @@ -1073,11 +1073,12 @@ def initAsBackup : M Unit := do fail s!"{← curLoc}: init_as_backup at index {index} in view {term}: index 0 iff view 0" note (.initAsBackup index term) - -- From a snapshot, `term_history` is untraced: assume every entry up to `index` - -- is in view `term`, and the snapshotted entries are opaque (no hooks); a snapshot is - -- taken at a signature, so entry `index` is one. The node does not hold them (the - -- ledger starts after `index`, the base); the machine replaces them at release by a - -- ghost from a node that has committed them. + -- From a snapshot, `term_history` is untraced: until the release, assume every entry + -- up to `index` is in view `term`, and the snapshotted entries are opaque (no hooks); a + -- snapshot is taken at a signature, so entry `index` is one. The node does not hold + -- them (the ledger starts after `index`, the base); the machine replaces them at + -- release by a ghost from a node that has committed them, and the view history up to + -- `index` by that node's. let views := if index == 0 then #[] else Array.replicate term 1 let ledger := (Array.replicate index { term, sig := false }).modify (index - 1) diff --git a/lean/consensus/Consensus/TraceValidation/Machine.lean b/lean/consensus/Consensus/TraceValidation/Machine.lean index 7259041b1cfd..f817e1017ff5 100644 --- a/lean/consensus/Consensus/TraceValidation/Machine.lean +++ b/lean/consensus/Consensus/TraceValidation/Machine.lean @@ -212,8 +212,12 @@ def snapshotOf (c : Ctx) : Option (Nat × Nat) := /-- Fill a joiner's ledger prefix up to its snapshot `index` (its `base`) from a donor: another node whose declared state has committed `index`. The joiner does not hold the prefix -(`State.declared` drops it): it is a ghost, for the proof. `init_as_backup` gets an empty term history from -the driver, so every snapshotted entry is in view `term`; the donor's entries must agree. +(`State.declared` drops it): it is a ghost, for the proof. The joiner does hold the view +history up to `index`, which `init_as_backup` receives with the snapshot +(`get_history_until(index)` of the node that took it) but no trace point records: it is the +donor's, up to `index`. Both nodes' histories give each index up to `index` the term of +its committed entry (`inv`'s `terms_are_views`), and their starts are positive and sorted, +so they are equal. -/ def fillSnapshot (others : List (NodeID × Local)) (index term : Nat) (vars : State) : Except String State := @@ -222,12 +226,10 @@ def fillSnapshot (others : List (NodeID × Local)) (index term : Nat) (vars : St | none => .error s!"wait: no node has committed {index} yet" | some (_, donor) => let prefix_ := donor.vars.ledger.extract 0 index - if !prefix_.all (·.term == term) then + -- A snapshot is taken at a signature, in the snapshot's view. + if index != 0 && !prefix_[index - 1]?.any fun e => e.sig && e.term == term then .error - s!"snapshot at {index} in view {term} spans earlier views {prefix_.toList.map (·.term) |>.eraseDups}, which the driver's empty term history cannot express" - -- A snapshot is taken at a signature. - else if index != 0 && !prefix_[index - 1]?.any (·.sig) then - .error s!"snapshot at {index}: the donor's entry {index} is not a signature" + s!"snapshot at {index} in view {term}: the donor's entry {index} is not a signature in that view" -- The snapshot's hooks installed configurations of the snapshotted prefix. hooks.h -- installs a snapshot's configuration at the version of the snapshot's last write -- to the nodes table, which may follow the entry that set the membership (a node's @@ -244,7 +246,12 @@ def fillSnapshot (others : List (NodeID × Local)) (index term : Nat) (vars : St .error s!"snapshot at {index}: the snapshotted prefix retires the joiner {vars.nodeId}" else - .ok { vars with ledger := prefix_ ++ vars.ledger.extract index vars.ledger.size } + .ok + { + vars with + ledger := prefix_ ++ vars.ledger.extract index vars.ledger.size + views := donor.vars.views.filter (· <= index) + } /-- The declared state at release: a joiner's snapshot prefix is filled from a donor. -/ def closeVars (others : List (NodeID × Local)) (head : Ev) (c : Ctx) diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean index 5a4605d86211..a8e28bb88997 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/InitAsBackup.lean @@ -15,8 +15,8 @@ index and view in a note, sizes the ledger to the index and makes the node a fol the snapshot's view. The release (`joinFinish`) fills the ledger with a donor's committed prefix (`fillSnapshot`), so the clean `initAsBackup` input is the abstraction of that prefix: the donor's clean state has committed it (`admit`), and `fillSnapshot`'s checks give -the clean guard (the prefix ends at a signature) and the clean view (every entry of the -prefix is in the snapshot's view). +the clean guard (the prefix ends at a signature) and the clean view (that signature is in +the snapshot's view). -/ namespace Consensus.TraceValidation.Proofs.Life @@ -110,15 +110,17 @@ theorem fill_ok {others : List (NodeID × Local)} {index term : Nat} {vars vars' (k, donor) ∈ others /\ index <= donor.vars.commitIdx /\ index <= donor.vars.ledger.size - /\ (forall e, e ∈ donor.vars.ledger.extract 0 index -> e.term = term) /\ (index != 0 - -> ((donor.vars.ledger.extract 0 index)[index - 1]?.any (·.sig)) = true) + -> ((donor.vars.ledger.extract 0 index)[index - 1]?.any + fun e => e.sig && e.term == term) + = true) /\ vars' = { vars with ledger := donor.vars.ledger.extract 0 index ++ vars.ledger.extract index vars.ledger.size + views := donor.vars.views.filter (· <= index) } := by unfold fillSnapshot at filled split at filled @@ -130,25 +132,15 @@ theorem fill_ok {others : List (NodeID × Local)} {index term : Nat} {vars vars' dsimp only at filled split at filled · cases filled - rename_i terms - split at filled - · cases filled rename_i sig split at filled · cases filled split at filled · cases filled cases filled - refine ⟨k, donor, member, chosen.1, chosen.2, ?_, ?_, rfl⟩ - · intro e member - have all : (donor.vars.ledger.extract 0 index).all (·.term == term) = true := by - cases hx : (donor.vars.ledger.extract 0 index).all (·.term == term) - · rw [hx] at terms - exact absurd rfl terms - · rfl - simpa using Array.all_eq_true_iff_forall_mem.mp all e member - · intro nonzero - simpa [nonzero] using sig + refine ⟨k, donor, member, chosen.1, chosen.2, ?_, rfl⟩ + intro nonzero + simpa [nonzero] using sig end Consensus.TraceValidation.Proofs.Life @@ -168,14 +160,14 @@ theorem initAsBackupSound (env : Env) : InitAsBackupSound env := by Life.TriN.run (Life.init_hold env saved) ⟨rfl, rfl, rfl⟩ ran have snap : snapshotOf c = some (index, term) := by simp [snapshotOf, notes] simp only [joinFinish, snap] at finished - obtain ⟨k, donor, member, committed, enough, terms, sig, filled⟩ := Life.fill_ok finished + obtain ⟨k, donor, member, committed, enough, sig, filled⟩ := Life.fill_ok finished subst filled have commit0 : saved.commitIdx = 0 := by simp only [inv, invChecks, List.all_cons, Bool.and_eq_true] at invSaved obtain ⟨_, le, _⟩ := invSaved simp only [decide_eq_true_eq, last0] at le omega - generalize hpre : donor.vars.ledger.extract 0 index = pre at terms sig + generalize hpre : donor.vars.ledger.extract 0 index = pre at sig have preSize : pre.size = index := by rw [← hpre, Array.size_extract] omega @@ -198,11 +190,11 @@ theorem initAsBackupSound (env : Env) : InitAsBackupSound env := by /\ e.term = term /\ e.sig = true := by intro nonzero have within : index - 1 < pre.size := by omega - refine ⟨pre[index - 1], ?_, terms _ (Array.getElem_mem within), ?_⟩ - · rw [← hentries] - simp [within] - · have := sig (by simpa using nonzero) - simpa [within] using this + have last := sig (by simpa using nonzero) + simp only [within, getElem?_pos, Option.any_some, Bool.and_eq_true, beq_iff_eq] at last + refine ⟨pre[index - 1], ?_, last.2, last.1⟩ + rw [← hentries] + simp [within] have endTerm : termAt entries index = term := by by_cases nonzero : index = 0 · simp only [nonzero, beq_self_eq_true, beq_iff_eq] at iff diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 141acd92355e..3d62395ef95d 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -104,8 +104,9 @@ Validation also tolerates the following without checking them exactly. `cft.h` compares that index only with later configurations and with indexes above the commit index, so the behaviour is the same. - **T2:** inputs that no trace point records are read from the node's next events: the batch size, `request_timeout`, the CheckQuorum acknowledgement timers, the flush threshold, the out-of-lock hook's snapshot version and `force_become_primary`. Every consequence of each one is still checked. -- **T3:** the view history of a node that joined from a snapshot is not traced, so M_tv assumes that every index up to the snapshot base is in the snapshot's view. - Only the base itself is read, and it is a committed signature in that view; any read below the base is rejected (S9). +- **T3:** the view history that a node joining from a snapshot receives with it is not traced, so M_tv takes the donor's view history up to the snapshot base. + The two are equal: both give each index up to the base the term of its committed entry (`inv`'s `terms_are_views`), so a snapshot whose prefix spans several views is modelled exactly. + The entries below the base remain a ghost, and any read of them is rejected (S9). - **T4:** on an election timeout with no configurations, `cft.h` returns early; the proof matches it with no clean step. ## Source From fc29fa37add538504a96a92c049bc4ec2bf5f7ad Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:39:48 +0000 Subject: [PATCH 20/25] Describe the replicate batch commit fix in the change notes Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .changes/commit-before-reconfiguration-in-batch.fixed.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changes/commit-before-reconfiguration-in-batch.fixed.md diff --git a/.changes/commit-before-reconfiguration-in-batch.fixed.md b/.changes/commit-before-reconfiguration-in-batch.fixed.md new file mode 100644 index 000000000000..6fb4f052abf5 --- /dev/null +++ b/.changes/commit-before-reconfiguration-in-batch.fixed.md @@ -0,0 +1,2 @@ +A signature replicated in the same batch as a later reconfiguration transaction adding the first other node now commits at once, rather than waiting for that node to acknowledge it. +See [Reconfiguration](doc/architecture/consensus/index.rst#reconfiguration). From ab894d80a7cfd8c087387cf99033835b27e09996 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 17:41:16 +0000 Subject: [PATCH 21/25] Say what to change when trace validation rejects a cft.h change Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/replay/README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 3d62395ef95d..5041e7519306 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -109,6 +109,13 @@ Validation also tolerates the following without checking them exactly. The entries below the base remain a ghost, and any read of them is rejected (S9). - **T4:** on an election timeout with no configurations, `cft.h` returns early; the proof matches it with no clean step. +## When a `cft.h` change is rejected + +A rejection names the trace line, the trace point and the field or rule that failed. +If its diagnostic says "known implementation and specification difference", the trace hit one of the cases listed [above](#known-implementation-and-specification-differences). +Otherwise either the change is wrong, or M_tv must follow it: a new or removed event field goes in `traceFields` in [`Observe.lean`](../Consensus/TraceValidation/Observe.lean) with its comparison, and a moved trace point or changed behaviour goes in the handler of that lock hold in [`Aft.lean`](../Consensus/TraceValidation/Aft.lean). +The build then fails until that handler's proof under [`Proofs/Handlers/`](../Consensus/TraceValidation/Proofs/Handlers) holds again, which is what shows the changed behaviour is still allowed by the consensus model. + ## Source - [`TraceValidation/`](../Consensus/TraceValidation): declared state, events, observation, abstraction, M_tv, the validator and proofs. From 284112143a504d96c4b7177cda9241fb4a711433 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 18:14:21 +0000 Subject: [PATCH 22/25] Move M_tv and the validator out of the reviewed folder The files directly in TraceValidation/ should be exactly the reviewed surface. Move the model of cft.h (handler monad, handlers, machine, invariant, full-ledger state) to TraceValidation/MTv/ and the executable validator and lock-step check to TraceValidation/Validator/. Only module paths change. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus.lean | 2 +- lean/consensus/Consensus/Tests/TraceValidationHooks.lean | 4 ++-- lean/consensus/Consensus/TraceValidation.lean | 2 +- lean/consensus/Consensus/TraceValidation/{ => MTv}/Aft.lean | 2 +- .../consensus/Consensus/TraceValidation/{ => MTv}/Full.lean | 4 ++-- .../Consensus/TraceValidation/{ => MTv}/Handler.lean | 4 ++-- .../Consensus/TraceValidation/{ => MTv}/Invariant.lean | 6 +++--- .../Consensus/TraceValidation/{ => MTv}/Machine.lean | 4 ++-- .../Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean | 2 +- .../TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean | 2 +- lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean | 2 +- .../Consensus/TraceValidation/Proofs/Obligation.lean | 4 ++-- .../Consensus/TraceValidation/Proofs/Validator.lean | 2 +- lean/consensus/Consensus/TraceValidation/State.lean | 2 +- .../Consensus/TraceValidation/{ => Validator}/Lockstep.lean | 4 ++-- .../{Validator.lean => Validator/Validate.lean} | 2 +- lean/consensus/README.md | 2 +- lean/consensus/replay/README.md | 6 +++--- lean/consensus/replay/ReplayMain.lean | 2 +- 19 files changed, 29 insertions(+), 29 deletions(-) rename lean/consensus/Consensus/TraceValidation/{ => MTv}/Aft.lean (99%) rename lean/consensus/Consensus/TraceValidation/{ => MTv}/Full.lean (96%) rename lean/consensus/Consensus/TraceValidation/{ => MTv}/Handler.lean (98%) rename lean/consensus/Consensus/TraceValidation/{ => MTv}/Invariant.lean (98%) rename lean/consensus/Consensus/TraceValidation/{ => MTv}/Machine.lean (99%) rename lean/consensus/Consensus/TraceValidation/{ => Validator}/Lockstep.lean (98%) rename lean/consensus/Consensus/TraceValidation/{Validator.lean => Validator/Validate.lean} (99%) diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 1f6b9d4bae94..01c0d61d4447 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -2,7 +2,7 @@ module public import Consensus.Properties public import Consensus.TraceValidation -public import Consensus.TraceValidation.Lockstep +public import Consensus.TraceValidation.Validator.Lockstep import Consensus.Tests.CanonicalTraces import Consensus.Tests.TraceValidationHooks diff --git a/lean/consensus/Consensus/Tests/TraceValidationHooks.lean b/lean/consensus/Consensus/Tests/TraceValidationHooks.lean index 324d491731ad..5796a9fc781b 100644 --- a/lean/consensus/Consensus/Tests/TraceValidationHooks.lean +++ b/lean/consensus/Consensus/Tests/TraceValidationHooks.lean @@ -1,8 +1,8 @@ module -meta import Consensus.TraceValidation.Lockstep +meta import Consensus.TraceValidation.Validator.Lockstep -public import Consensus.TraceValidation.Lockstep +public import Consensus.TraceValidation.Validator.Lockstep public section diff --git a/lean/consensus/Consensus/TraceValidation.lean b/lean/consensus/Consensus/TraceValidation.lean index b17d4575095c..6d67e7fad39c 100644 --- a/lean/consensus/Consensus/TraceValidation.lean +++ b/lean/consensus/Consensus/TraceValidation.lean @@ -10,7 +10,7 @@ public import Consensus.TraceValidation.Proofs.Refinement /-! # Trace validation (reviewed statement) -The validator `validate` (in `Consensus.TraceValidation.Validator`) checks a trace of +The validator `validate` (in `Consensus.TraceValidation.Validator.Validate`) checks a trace of `cft.h` trace points, split into one stream per node. The theorem below is what acceptance means: the accepted trace is a behaviour of the clean model `Consensus.Model.transitionSystem` under a state refinement mapping. Properties are diff --git a/lean/consensus/Consensus/TraceValidation/Aft.lean b/lean/consensus/Consensus/TraceValidation/MTv/Aft.lean similarity index 99% rename from lean/consensus/Consensus/TraceValidation/Aft.lean rename to lean/consensus/Consensus/TraceValidation/MTv/Aft.lean index e62062aa7f01..8788157bede1 100644 --- a/lean/consensus/Consensus/TraceValidation/Aft.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Aft.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Handler +public import Consensus.TraceValidation.MTv.Handler @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Full.lean b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean similarity index 96% rename from lean/consensus/Consensus/TraceValidation/Full.lean rename to lean/consensus/Consensus/TraceValidation/MTv/Full.lean index 0649f14cf0b5..de5b42575d8c 100644 --- a/lean/consensus/Consensus/TraceValidation/Full.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean @@ -10,11 +10,11 @@ public import Consensus.TraceValidation.Abs /-! # M_tv's working state (not reviewed) -The handlers (`Consensus.TraceValidation.Aft`) run on `State`: the reviewed declared +The handlers (`Consensus.TraceValidation.MTv.Aft`) run on `State`: the reviewed declared state (`Exec.Declared`) with the whole ledger instead of the entries the node holds. For a node that joined from a snapshot, the entries up to `base` are a ghost: the machine fills them at the `init_as_backup` release from a node that has committed them -(`Consensus.TraceValidation.Machine.fillSnapshot`), so that the clean `initAsBackup` input +(`Consensus.TraceValidation.MTv.Machine.fillSnapshot`), so that the clean `initAsBackup` input is admitted. `State.declared` projects them away; the machine checks that no hold's outcome depends on them (`Machine.ghostFree`). diff --git a/lean/consensus/Consensus/TraceValidation/Handler.lean b/lean/consensus/Consensus/TraceValidation/MTv/Handler.lean similarity index 98% rename from lean/consensus/Consensus/TraceValidation/Handler.lean rename to lean/consensus/Consensus/TraceValidation/MTv/Handler.lean index 9496f213feb1..965a03ee4b08 100644 --- a/lean/consensus/Consensus/TraceValidation/Handler.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Handler.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Full +public import Consensus.TraceValidation.MTv.Full @[expose] public section @@ -15,7 +15,7 @@ monad over `Ctx`, with no suspension. The run consumes the hold's actions from `Ctx.queue`, one per `trace` call, in order. The program counter is therefore the number of actions consumed: M_tv steps an event by rerunning the handler from the declared state at lock acquisition with one more action queued -(`Consensus.TraceValidation.Machine`). +(`Consensus.TraceValidation.MTv.Machine`). A run that has consumed every queued action stops (`Stop.blocked`) at the first state mutation, trace or peek after the last trace point, so the state it stops in is the diff --git a/lean/consensus/Consensus/TraceValidation/Invariant.lean b/lean/consensus/Consensus/TraceValidation/MTv/Invariant.lean similarity index 98% rename from lean/consensus/Consensus/TraceValidation/Invariant.lean rename to lean/consensus/Consensus/TraceValidation/MTv/Invariant.lean index 4a0e5552f490..4ad448b7c8e3 100644 --- a/lean/consensus/Consensus/TraceValidation/Invariant.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Invariant.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Aft +public import Consensus.TraceValidation.MTv.Aft @[expose] public section @@ -15,7 +15,7 @@ The refinement proof relates a node's clean state to its declared state by `Rel` before the node's first ledger entry, the clean initial state; in both cases with the local invariant `inv` of the declared state. Messages in flight satisfy `msgInv`. -The machine (`Consensus.TraceValidation.Machine`) evaluates `inv` at every release and +The machine (`Consensus.TraceValidation.MTv.Machine`) evaluates `inv` at every release and rejects the trace when a conjunct fails, so each handler obligation assumes `inv` of the declared state at release rather than proving it. A rejection by a conjunct is of one of two kinds, stated in its doc comment: @@ -27,7 +27,7 @@ two kinds, stated in its doc comment: implementation and specification difference. `msgInv` stays a conclusion of each obligation about the messages it sends; the -diagnostic lock-step check (`Consensus.TraceValidation.Lockstep`) evaluates it at every +diagnostic lock-step check (`Consensus.TraceValidation.Validator.Lockstep`) evaluates it at every send. Each conjunct of `inv` is named; the names are what rejections and lock-step findings diff --git a/lean/consensus/Consensus/TraceValidation/Machine.lean b/lean/consensus/Consensus/TraceValidation/MTv/Machine.lean similarity index 99% rename from lean/consensus/Consensus/TraceValidation/Machine.lean rename to lean/consensus/Consensus/TraceValidation/MTv/Machine.lean index f817e1017ff5..3ab373f72034 100644 --- a/lean/consensus/Consensus/TraceValidation/Machine.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Machine.lean @@ -5,8 +5,8 @@ module public import Consensus.Model public import Consensus.TraceValidation.Abs -public import Consensus.TraceValidation.Aft -public import Consensus.TraceValidation.Invariant +public import Consensus.TraceValidation.MTv.Aft +public import Consensus.TraceValidation.MTv.Invariant public import CCF.Sections @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean index 346bdefb1427..225c5476f2ee 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/AeFrame.lean @@ -4,7 +4,7 @@ module -- Licensed under the Apache 2.0 License. public import Consensus.TraceValidation.Proofs.Handlers.AeHoare -public import Consensus.TraceValidation.Aft +public import Consensus.TraceValidation.MTv.Aft @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean index ba2adadb5934..bb7b6a9f9228 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Handlers/ReplUpdateCommit.lean @@ -4,7 +4,7 @@ module -- Licensed under the Apache 2.0 License. public import Consensus.TraceValidation.Proofs.Monad -public import Consensus.TraceValidation.Invariant +public import Consensus.TraceValidation.MTv.Invariant public import CCF.Proofs.Finset @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean index ecd9548c5344..52728e40d5c8 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Monad.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Handler +public import Consensus.TraceValidation.MTv.Handler @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean index 25d8f88c7d5f..b4a9d34c48a0 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Obligation.lean @@ -3,8 +3,8 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Invariant -public import Consensus.TraceValidation.Machine +public import Consensus.TraceValidation.MTv.Invariant +public import Consensus.TraceValidation.MTv.Machine @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean index 69e60439b811..0caff72a424b 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Validator.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Validator +public import Consensus.TraceValidation.Validator.Validate @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/State.lean b/lean/consensus/Consensus/TraceValidation/State.lean index c44d4b6c01bb..2de1e6deb09f 100644 --- a/lean/consensus/Consensus/TraceValidation/State.lean +++ b/lean/consensus/Consensus/TraceValidation/State.lean @@ -12,7 +12,7 @@ public import Lean.Data.Json One `Declared` state per node. Every field mirrors one implementation member, named in its doc comment; there is no control, thread, lock or ghost state here. M_tv runs on -an extension of it (`Consensus.TraceValidation.Full`), which is not part of the reviewed +an extension of it (`Consensus.TraceValidation.MTv.Full`), which is not part of the reviewed surface. `Consensus.TraceValidation.Observe` compares trace events against projections of this structure only. diff --git a/lean/consensus/Consensus/TraceValidation/Lockstep.lean b/lean/consensus/Consensus/TraceValidation/Validator/Lockstep.lean similarity index 98% rename from lean/consensus/Consensus/TraceValidation/Lockstep.lean rename to lean/consensus/Consensus/TraceValidation/Validator/Lockstep.lean index 992997ef51ba..2265c1506b71 100644 --- a/lean/consensus/Consensus/TraceValidation/Lockstep.lean +++ b/lean/consensus/Consensus/TraceValidation/Validator/Lockstep.lean @@ -3,8 +3,8 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Validator -public import Consensus.TraceValidation.Invariant +public import Consensus.TraceValidation.Validator.Validate +public import Consensus.TraceValidation.MTv.Invariant @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Validator.lean b/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean similarity index 99% rename from lean/consensus/Consensus/TraceValidation/Validator.lean rename to lean/consensus/Consensus/TraceValidation/Validator/Validate.lean index c86ca93e5d77..c4f9c10cec5a 100644 --- a/lean/consensus/Consensus/TraceValidation/Validator.lean +++ b/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Machine +public import Consensus.TraceValidation.MTv.Machine @[expose] public section diff --git a/lean/consensus/README.md b/lean/consensus/README.md index 7bfdcdecfd2e..556c36fdefa4 100644 --- a/lean/consensus/README.md +++ b/lean/consensus/README.md @@ -55,7 +55,7 @@ Append regressions check configuration heartbeats followed by flushing, pre-comm These are regression examples, not exhaustive checking. `lake check` checks both default targets, `Consensus` and `consensus-replay`, in one invocation. It runs without sandboxing here, so build-time code must be trusted. -`Consensus.lean` reexports `Properties.lean`, `TraceValidation.lean` and the diagnostic `TraceValidation/Lockstep.lean`, while importing tests privately. +`Consensus.lean` reexports `Properties.lean`, `TraceValidation.lean` and the diagnostic `TraceValidation/Validator/Lockstep.lean`, while importing tests privately. The shared `check-imports` command rejects modules missing from that import closure. ## Proofs diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 5041e7519306..4dbb376407dd 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -47,7 +47,7 @@ Records are split into one stream per node, ordered by `h_ts`; all of a node's r `h_ts` is never compared across nodes, so captures with one process per node, or with shuffled lines, validate the same way. Each node's state is the declared state ([`State`](../Consensus/TraceValidation/State.lean)), one field per `cft.h` member, extended by the position inside the current lock hold. -[`Aft`](../Consensus/TraceValidation/Aft.lean) mirrors the `cft.h` functions statement by statement; it takes one step per trace point, running the code from the previous trace point up to this one. +[`Aft`](../Consensus/TraceValidation/MTv/Aft.lean) mirrors the `cft.h` functions statement by statement; it takes one step per trace point, running the code from the previous trace point up to this one. The first trace point of a lock hold opens a section; a silent release, inserted when the node's next event opens another section or its stream ends, runs the code after the last trace point and publishes the hold's sends. Where `cft.h` depends on something no trace point records, such as a timer or a batch size, the handler follows the branch that the node's next event requires. @@ -61,7 +61,7 @@ A node that joined from a snapshot holds only the ledger after it: its declared Each release checks that the base is a committed signature in that view, and that the hold's outcome does not depend on the entries up to the base, which the node does not hold. For the proof only, the model takes those entries, which no trace point records, from another node's committed ledger. -With `--refine`, [`Lockstep`](../Consensus/TraceValidation/Lockstep.lean) also checks every release against the [clean model](../Consensus/Model/Node.lean): the clean inputs of the hold are rebuilt, the clean `Node.step`s run from the node's clean state, and the result must agree ([`Abs`](../Consensus/TraceValidation/Abs.lean)) with the declared state, with the same sends in the same order, and satisfy the invariants the proofs use. +With `--refine`, [`Lockstep`](../Consensus/TraceValidation/Validator/Lockstep.lean) also checks every release against the [clean model](../Consensus/Model/Node.lean): the clean inputs of the hold are rebuilt, the clean `Node.step`s run from the node's clean state, and the result must agree ([`Abs`](../Consensus/TraceValidation/Abs.lean)) with the declared state, with the same sends in the same order, and satisfy the invariants the proofs use. This check is a diagnostic and a regression oracle for the proofs, not part of what acceptance means. ## What acceptance means @@ -113,7 +113,7 @@ Validation also tolerates the following without checking them exactly. A rejection names the trace line, the trace point and the field or rule that failed. If its diagnostic says "known implementation and specification difference", the trace hit one of the cases listed [above](#known-implementation-and-specification-differences). -Otherwise either the change is wrong, or M_tv must follow it: a new or removed event field goes in `traceFields` in [`Observe.lean`](../Consensus/TraceValidation/Observe.lean) with its comparison, and a moved trace point or changed behaviour goes in the handler of that lock hold in [`Aft.lean`](../Consensus/TraceValidation/Aft.lean). +Otherwise either the change is wrong, or M_tv must follow it: a new or removed event field goes in `traceFields` in [`Observe.lean`](../Consensus/TraceValidation/Observe.lean) with its comparison, and a moved trace point or changed behaviour goes in the handler of that lock hold in [`Aft.lean`](../Consensus/TraceValidation/MTv/Aft.lean). The build then fails until that handler's proof under [`Proofs/Handlers/`](../Consensus/TraceValidation/Proofs/Handlers) holds again, which is what shows the changed behaviour is still allowed by the consensus model. ## Source diff --git a/lean/consensus/replay/ReplayMain.lean b/lean/consensus/replay/ReplayMain.lean index 1d076a697cff..b40c032017e1 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Lockstep +public import Consensus.TraceValidation.Validator.Lockstep public section From 58d7a2f0081ba7cf0a5b4e4c7dba8cc0677fa02f Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 18:16:44 +0000 Subject: [PATCH 23/25] Make the trusted path from a trace file reviewed, apart from the scheduler The decoder and the split into per-node streams are trusted, not proved, so they belong to the reviewed surface; the scheduler is covered by the theorem and does not. Move Env and environment from the validator and Abs into a reviewed Input module with one load function the CLI uses, and state the refinement over the streams' nodes instead of the verdict's keys (equal by validate_sound), so that the theorem reads only validate and its observations from unreviewed code. Each reviewed header now says what a reviewer checks it against. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus/TraceValidation.lean | 25 +++--- .../Consensus/TraceValidation/Abs.lean | 14 +--- .../Consensus/TraceValidation/Action.lean | 5 +- .../Consensus/TraceValidation/Event.lean | 9 +- .../Consensus/TraceValidation/Input.lean | 84 +++++++++++++++++++ .../Consensus/TraceValidation/MTv/Full.lean | 2 +- .../Consensus/TraceValidation/Observe.lean | 6 +- .../TraceValidation/Proofs/Refinement.lean | 5 +- .../Consensus/TraceValidation/State.lean | 6 +- .../TraceValidation/Validator/Validate.lean | 38 --------- lean/consensus/replay/ReplayMain.lean | 48 +++++------ 11 files changed, 138 insertions(+), 104 deletions(-) create mode 100644 lean/consensus/Consensus/TraceValidation/Input.lean diff --git a/lean/consensus/Consensus/TraceValidation.lean b/lean/consensus/Consensus/TraceValidation.lean index 6d67e7fad39c..1ba94c956eed 100644 --- a/lean/consensus/Consensus/TraceValidation.lean +++ b/lean/consensus/Consensus/TraceValidation.lean @@ -10,20 +10,23 @@ public import Consensus.TraceValidation.Proofs.Refinement /-! # Trace validation (reviewed statement) -The validator `validate` (in `Consensus.TraceValidation.Validator.Validate`) checks a trace of -`cft.h` trace points, split into one stream per node. The theorem below is what -acceptance means: the accepted trace is a behaviour of the clean model +`load` decodes a trace file of `cft.h` trace points into trace-wide parameters `env` and one +stream of events per node, and the validator `validate` checks them. The theorem below is +what acceptance means: the accepted trace is a behaviour of the clean model `Consensus.Model.transitionSystem` under a state refinement mapping. Properties are stated and proved of the clean model only (`Consensus.Properties`); nothing here is claimed of the implementation beyond this refinement. -To review, the state refinement mapping and the observations it is checked at: -`State` (the declared state: the `cft.h` variables of a node, with the ledger it -holds), `Abs` (the relation `related` of a clean node state to a declared state), -`Event` (decoded trace points), `Action` and `Observe` (what each trace point is -compared with), `CCF.Observation` (the refinement statement, in `lean/common`), and this -file. The behaviour refinement, that is the proof of the theorem, is in -`Consensus.TraceValidation.Proofs` and is not reviewed. +The reviewed surface is this file and the files directly in `TraceValidation/`: `State` +(the declared state: the `cft.h` variables of a node, with the ledger it holds), `Event` +(decoded trace points and per-node streams), `Input` (`load` and `env`), `Action` and +`Observe` (what each trace point is compared with), and `Abs` (the relation `related` of a +clean node state to a declared state); with `CCF.Observation` (the refinement statement, in +`lean/common`). They import only each other, the clean model and `lean/common`. This file's +only other references are the validator `validate` and the `observations` of its result +(`TraceValidation/Validator/`), and the proof `Proofs.validate_refines`; those, the model +of `cft.h` it runs (`TraceValidation/MTv/`) and the proofs (`TraceValidation/Proofs/`) are +not reviewed. -/ namespace Consensus.TraceValidation @@ -45,7 +48,7 @@ theorem accepted_refines {env : Env} : streamsMatch streams v.observations /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) /\ CCF.ObservationRefinement.Refines - (Consensus.Model.transitionSystem env.genesis v.keys) nodeState + (Consensus.Model.transitionSystem env.genesis (streams.map Prod.fst)) nodeState (fun node clean declared => related env.names node clean declared.1 = true) opens v.observations := diff --git a/lean/consensus/Consensus/TraceValidation/Abs.lean b/lean/consensus/Consensus/TraceValidation/Abs.lean index 0d7cee8e4b00..952fd5d01891 100644 --- a/lean/consensus/Consensus/TraceValidation/Abs.lean +++ b/lean/consensus/Consensus/TraceValidation/Abs.lean @@ -15,7 +15,8 @@ public import CCF.Observation The declared state is `Consensus.TraceValidation.Exec.Declared`: one structure of `cft.h` members per node, each field documented with the member it mirrors. This file maps it to the clean model's node state; `accepted_refines` says an accepted trace is a behaviour of -the clean model under this mapping. +the clean model under this mapping. A reviewer checks each clean field against the +`cft.h` members it is projected from. `Declared.abs names d` is the clean `NodeState` that the declared state `d` stands for: each clean field is a projection of declared fields. Node ids are strings in the @@ -154,16 +155,7 @@ def related (names : Names) (node : NodeID) (c : NodeState) (d : Declared) : Boo names.id d.nodeId == node && (d.agrees names c || (d.lastIdx == 0 && d.base == 0 && c.commitIndex == 0)) -/-! ## Trace-wide parameters and observations -/ - -/-- Trace-wide parameters, computed by the decoder. -/ -structure Env where - /-- The trace's node ids, sorted. -/ - names : Names - /-- Every node's address, as in configuration hooks. -/ - addrs : List (Exec.NodeId × String) - /-- The genesis configuration: the node whose first event is `become_leader`. -/ - genesis : Finset NodeID +/-! ## Observations -/ /-- Events that take the lock: the observation points. -/ def opens (e : Ev) : Bool := Exec.heads.contains e.function diff --git a/lean/consensus/Consensus/TraceValidation/Action.lean b/lean/consensus/Consensus/TraceValidation/Action.lean index f8897011522b..d122499d5fb5 100644 --- a/lean/consensus/Consensus/TraceValidation/Action.lean +++ b/lean/consensus/Consensus/TraceValidation/Action.lean @@ -8,12 +8,13 @@ public import Lean.Data.Json @[expose] public section /-! -# M_tv actions +# M_tv actions (reviewed) One action per trace event: the trace point reached and the event fields the model consumes as input (see `Observe.inputFields`). The silent lock release is `none : Option Action`. Each step also returns a `Label`: the values the model -computed at the trace point for the event's remaining non-state fields. +computed at the trace point for the event's remaining non-state fields. A reviewer +checks that these carry nothing but the trace point and its event's fields. -/ namespace Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Event.lean b/lean/consensus/Consensus/TraceValidation/Event.lean index e37bd01e650a..8486cfb7e1ae 100644 --- a/lean/consensus/Consensus/TraceValidation/Event.lean +++ b/lean/consensus/Consensus/TraceValidation/Event.lean @@ -8,7 +8,7 @@ public import Lean.Data.Json @[expose] public section /-! -# Trace events for messy-model trace validation +# Trace events (reviewed) Decoding only: one record per line, `{process_id, h_ts, msg}`. Command records (`msg.cmd`) are driver provenance and are kept apart. Every other record is one @@ -16,7 +16,8 @@ trace event of the node named by `msg.state.node_id` (or `msg.node_id` for `retired_committed_tx`, which carries no snapshot). Events are split into one stream per node, ordered by `h_ts` within the node's -process. The global order across processes is never used. +process. The global order across processes is never used. A reviewer checks this +against the record format the drivers and `cft_trace_msgpack.h` write. -/ namespace Consensus.TraceValidation.Exec @@ -83,10 +84,6 @@ def decode (file input : String) : Except String Trace := do events := events.push { file, line, process, hts, node, function, msg } return { events, commands, records } -def readTrace (path : System.FilePath) : IO (Except String Trace) := do - let input ← IO.FS.readFile path - return decode path.toString input - /-- One stream per node, ordered by `h_ts`; a node must live in one process. -/ def streams (trace : Trace) : Except String (List (String × Array Ev)) := do let nodes := (trace.events.toList.map (·.node)).mergeSort.eraseDups diff --git a/lean/consensus/Consensus/TraceValidation/Input.lean b/lean/consensus/Consensus/TraceValidation/Input.lean new file mode 100644 index 000000000000..ccad780f2a85 --- /dev/null +++ b/lean/consensus/Consensus/TraceValidation/Input.lean @@ -0,0 +1,84 @@ +module + +-- Copyright (c) Microsoft Corporation. All rights reserved. +-- Licensed under the Apache 2.0 License. + +public import Consensus.TraceValidation.Abs +public import Consensus.TraceValidation.Event + +@[expose] public section + +/-! +# Validator input (reviewed) + +The trusted path from a trace file to the arguments of `validate`: `load` decodes the file +(`Exec.decode`), splits it into one stream per node (`Exec.streams`) and computes the +trace-wide parameters (`environment`). A reviewer checks it against the capture format in +`cft_trace_msgpack.h` and `consensus/replay/README.md`. +-/ + +namespace Consensus.TraceValidation + +open Lean +open CCF (Finset) +open Consensus.Model.Node +open Consensus.TraceValidation.Exec (Ev) + +/-- Trace-wide parameters, computed by the decoder. -/ +structure Env where + /-- The trace's node ids, sorted. -/ + names : Names + /-- Every node's address, as in configuration hooks. -/ + addrs : List (Exec.NodeId × String) + /-- The genesis configuration: the node whose first event is `become_leader`. -/ + genesis : Finset NodeID + +/-- The `(node id, address)` pairs anywhere in an event. -/ +partial def collectAddrs (j : Json) (acc : List (Exec.NodeId × String)) + : List (Exec.NodeId × String) := + match j with + | .obj kvs => + kvs.toArray.foldl (init := acc) + fun acc (k, v) => + match v.getObjValAs? String "address" with + | .ok a => if acc.contains (k, a) then acc else (k, a) :: acc + | .error _ => collectAddrs v acc + | .arr vs => vs.foldl (init := acc) fun acc v => collectAddrs v acc + | _ => acc + +/-- +The environment and the per-node streams, keyed by clean id: the node ids are those with a +stream or an address, the genesis configuration is the one node whose stream starts with +`become_leader`. +-/ +def environment (ss : List (Exec.NodeId × Array Ev)) + : Except String (Env × List (NodeID × List Ev)) := do + let addrs := + ss.foldl (init := []) + fun acc (_, evs) => + evs.foldl (init := acc) fun acc e => collectAddrs e.msg acc + for (n, a) in addrs do + if addrs.any fun (m, b) => m == n && b != a then throw s!"node {n} has two addresses" + let ids := ((ss.map Prod.fst) ++ addrs.map Prod.fst).mergeSort (· <= ·) |>.eraseDups + let names : Names := { known := ids.toArray } + let firsts := + ss.filterMap + fun (n, evs) => + if (evs[0]?.map (·.function)) == some "become_leader" then + some (names.id n) + else + none + unless firsts.length == 1 do + throw + s!"expected one genesis node (stream starting with become_leader), found {firsts.length}" + let env : Env := { names, addrs, genesis := CCF.Finset.ofList firsts } + return (env, ss.map fun (n, evs) => (names.id n, evs.toList)) + +/-- A trace file, as `validate`'s arguments. -/ +def load (path : System.FilePath) + : IO (Except String (Env × List (NodeID × List Ev))) := do + let input ← IO.FS.readFile path + return do + environment (← Exec.streams (← Exec.decode path.toString input)) + +end Consensus.TraceValidation diff --git a/lean/consensus/Consensus/TraceValidation/MTv/Full.lean b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean index de5b42575d8c..3c33cc662a01 100644 --- a/lean/consensus/Consensus/TraceValidation/MTv/Full.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean @@ -3,7 +3,7 @@ module -- Copyright (c) Microsoft Corporation. All rights reserved. -- Licensed under the Apache 2.0 License. -public import Consensus.TraceValidation.Abs +public import Consensus.TraceValidation.Input @[expose] public section diff --git a/lean/consensus/Consensus/TraceValidation/Observe.lean b/lean/consensus/Consensus/TraceValidation/Observe.lean index 604a222f1676..dfec75914d28 100644 --- a/lean/consensus/Consensus/TraceValidation/Observe.lean +++ b/lean/consensus/Consensus/TraceValidation/Observe.lean @@ -10,7 +10,7 @@ public import Consensus.TraceValidation.Action @[expose] public section /-! -# Trace validation surface (reviewed) +# Observations (reviewed) Each trace event maps to exactly one M_tv action (`actionOf`). After the model steps that action, the event is observed against the declared state (`Declared`) at the @@ -23,7 +23,9 @@ the fields its trace point declares (`traceFields`): entry contents that only the hooks reveal); * the label: values the model computed at the trace point (packets, indices). -Depends only on the declared state, the action type and event decoding. +Depends only on the declared state, the action type and event decoding. A reviewer +checks `traceFields` against `cft_trace_msgpack.h`, and each comparison against the +`cft.h` code at its trace point. -/ namespace Consensus.TraceValidation.Exec diff --git a/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean index a46060f9f2eb..583656fc622d 100644 --- a/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean +++ b/lean/consensus/Consensus/TraceValidation/Proofs/Refinement.lean @@ -67,11 +67,12 @@ theorem validate_refines {env : Env} : streamsMatch streams v.observations /\ (forall o, o ∈ v.observations -> Exec.consistent o.event o.declared = true) /\ CCF.ObservationRefinement.Refines - (Consensus.Model.transitionSystem env.genesis v.keys) nodeState + (Consensus.Model.transitionSystem env.genesis (streams.map Prod.fst)) nodeState (fun node clean declared => related env.names node clean declared.1 = true) opens v.observations := by - obtain ⟨accepts, _, matches_, nonempty, consistent⟩ := validate_sound h + obtain ⟨accepts, keys, matches_, nonempty, consistent⟩ := validate_sound h + rw [← keys] exact ⟨matches_, consistent, observation_refines (refinement env (obligations env)) declare (fun node clean declared => related env.names node clean declared.1 = true) (fun node c l h idle => factors env node c l h idle) (frame env) v.keys _ _ (fun _ init keys => ⟨nonempty, keys, init⟩) diff --git a/lean/consensus/Consensus/TraceValidation/State.lean b/lean/consensus/Consensus/TraceValidation/State.lean index 2de1e6deb09f..5a576df83ba1 100644 --- a/lean/consensus/Consensus/TraceValidation/State.lean +++ b/lean/consensus/Consensus/TraceValidation/State.lean @@ -12,9 +12,9 @@ public import Lean.Data.Json One `Declared` state per node. Every field mirrors one implementation member, named in its doc comment; there is no control, thread, lock or ghost state here. M_tv runs on -an extension of it (`Consensus.TraceValidation.MTv.Full`), which is not part of the reviewed -surface. `Consensus.TraceValidation.Observe` compares trace events against projections of -this structure only. +an extension of it (in `MTv/`, not reviewed). `Consensus.TraceValidation.Observe` compares +trace events against projections of this structure only. A reviewer checks each field +against the `cft.h` member its doc comment names. The ledger is what the node holds: a node that joined from a snapshot holds only the entries after the snapshot (`Ledger::init_idx`); the snapshot's index and view are diff --git a/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean b/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean index c4f9c10cec5a..3169b4c9b0aa 100644 --- a/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean +++ b/lean/consensus/Consensus/TraceValidation/Validator/Validate.lean @@ -346,42 +346,4 @@ def validate (env : Env) (streams : List (NodeID × List Ev)) : Except String Ve | .error err => .error err | .ok w => conclude env ticking streams w -/-! ## Trace-wide parameters, from the decoded trace -/ - -partial def collectAddrs (j : Json) (acc : List (Exec.NodeId × String)) - : List (Exec.NodeId × String) := - match j with - | .obj kvs => - kvs.toArray.foldl (init := acc) - fun acc (k, v) => - match v.getObjValAs? String "address" with - | .ok a => if acc.contains (k, a) then acc else (k, a) :: acc - | .error _ => collectAddrs v acc - | .arr vs => vs.foldl (init := acc) fun acc v => collectAddrs v acc - | _ => acc - -/-- The environment and the per-node streams, keyed by clean id. -/ -def environment (ss : List (Exec.NodeId × Array Ev)) - : Except String (Env × List (NodeID × List Ev)) := do - let addrs := - ss.foldl (init := []) - fun acc (_, evs) => - evs.foldl (init := acc) fun acc e => collectAddrs e.msg acc - for (n, a) in addrs do - if addrs.any fun (m, b) => m == n && b != a then throw s!"node {n} has two addresses" - let ids := ((ss.map Prod.fst) ++ addrs.map Prod.fst).mergeSort (· <= ·) |>.eraseDups - let names : Names := { known := ids.toArray } - let firsts := - ss.filterMap - fun (n, evs) => - if (evs[0]?.map (·.function)) == some "become_leader" then - some (names.id n) - else - none - unless firsts.length == 1 do - throw - s!"expected one genesis node (stream starting with become_leader), found {firsts.length}" - let env : Env := { names, addrs, genesis := CCF.Finset.ofList firsts } - return (env, ss.map fun (n, evs) => (names.id n, evs.toList)) - end Consensus.TraceValidation diff --git a/lean/consensus/replay/ReplayMain.lean b/lean/consensus/replay/ReplayMain.lean index b40c032017e1..1023a15a49fb 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -7,39 +7,31 @@ public import Consensus.TraceValidation.Validator.Lockstep public section -open Lean Consensus.TraceValidation.Exec - /-- -Validate one trace with `Consensus.TraceValidation.validate`, the validator whose -acceptance `Consensus.TraceValidation.accepted_refines` is about. With `refine`, also -run the diagnostic lock-step check against the clean model and fail on any finding. +Validate one trace with `Consensus.TraceValidation.validate` on the arguments +`Consensus.TraceValidation.load` decodes, the validator whose acceptance +`Consensus.TraceValidation.accepted_refines` is about. With `refine`, also run the +diagnostic lock-step check against the clean model and fail on any finding. -/ def check (refine : Bool) (path : String) : IO Bool := do let t0 ← IO.monoMsNow - match ← readTrace path with + let r := + (← Consensus.TraceValidation.load path).bind + fun (env, ss) => (Consensus.TraceValidation.validate env ss).map (env, ·) + let t1 ← IO.monoMsNow + match r with | .error e => IO.eprintln s!"FAIL {path}: {e}"; return false - | .ok trace => - let r := do - let (env, ss) ← Consensus.TraceValidation.environment (← streams trace) - Consensus.TraceValidation.validate env ss - let t1 ← IO.monoMsNow - match r with - | .ok v => - IO.println - s!"PASS {path}: nodes={v.keys.length} events={v.observations.length} sections={v.sections} actions={v.actions.length} ms={t1 - t0}" - if !refine then return true - let (env, _) ← - IO.ofExcept - (do - Consensus.TraceValidation.environment (← streams trace)) - match Consensus.TraceValidation.lockstep env v with - | .error e => IO.eprintln s!"REFINE-ERROR {path}: {e}"; return false - | .ok [] => return true - | .ok fs => - for f in fs do - IO.eprintln s!"REFINE {path}: {f}" - return false - | .error e => IO.eprintln s!"FAIL {path}: {e}"; return false + | .ok (env, v) => + IO.println + s!"PASS {path}: nodes={v.keys.length} events={v.observations.length} sections={v.sections} actions={v.actions.length} ms={t1 - t0}" + if !refine then return true + match Consensus.TraceValidation.lockstep env v with + | .error e => IO.eprintln s!"REFINE-ERROR {path}: {e}"; return false + | .ok [] => return true + | .ok fs => + for f in fs do + IO.eprintln s!"REFINE {path}: {f}" + return false def main (args : List String) : IO UInt32 := do let (refine, args) := From 7c7f1eef166dbc31fcf782c3e598397ef74850e8 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 18:19:17 +0000 Subject: [PATCH 24/25] Keep the reviewed trace-validation files independent of their subfolders The files directly in TraceValidation/ are the reviewed surface, so a reviewer must be able to read them without M_tv, the validator or the proofs. Add that as an architecture rule checked by check-imports: they may import model modules, lean/common definitions other than CCF.Proofs, the TraceValidation entrypoint and each other. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/common/CCF/Architecture.lean | 7 ++++++- lean/common/README.md | 3 ++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lean/common/CCF/Architecture.lean b/lean/common/CCF/Architecture.lean index 7acdc4a0a4d7..7d76f5d8eb1b 100644 --- a/lean/common/CCF/Architecture.lean +++ b/lean/common/CCF/Architecture.lean @@ -22,11 +22,14 @@ def allowedImport (root owner dependency : Name) : Bool := let model := root ++ `Model let properties := root ++ `Properties let proofs := root ++ `Proofs + let traceValidation := root ++ `TraceValidation + -- The reviewed trace-validation surface: the modules directly in `TraceValidation/`. + let reviewed (module : Name) := module.getPrefix == traceValidation if (`CCF).isPrefixOf owner then !root.isPrefixOf dependency else if !root.isPrefixOf dependency then -- The `CCF` entrypoint reexports `CCF.Proofs`, so models must import definitions directly. - !(model.isPrefixOf owner + !((model.isPrefixOf owner || reviewed owner) && ((`CCF.Proofs).isPrefixOf dependency || dependency == `CCF)) else if model.isPrefixOf owner then model.isPrefixOf dependency && (owner == model || dependency != model) @@ -37,6 +40,8 @@ def allowedImport (root owner dependency : Name) : Bool := else if properties.isPrefixOf owner then model.isPrefixOf dependency || (dependency != properties && properties.isPrefixOf dependency) + else if reviewed owner then + model.isPrefixOf dependency || dependency == traceValidation || reviewed dependency else if proofs.isPrefixOf owner then model.isPrefixOf dependency || proofs.isPrefixOf dependency diff --git a/lean/common/README.md b/lean/common/README.md index 4f6965f64685..ee640d4e628f 100644 --- a/lean/common/README.md +++ b/lean/common/README.md @@ -107,5 +107,6 @@ The same rules apply to every specification namespace, including multi-component - The `Properties` entrypoint can import model modules, property helpers, and proofs. - Property helpers can import model modules and other property helpers, but not proofs or the `Properties` entrypoint. - Proofs can import model modules, property helpers, and other proofs, but not the `Properties` entrypoint. -- Other modules, such as tests and trace validation, are unrestricted. +- Modules directly in `TraceValidation/`, the reviewed trace-validation surface, can import model modules, the `TraceValidation` entrypoint and each other, but not `CCF.Proofs` or the `CCF` entrypoint. +- Other modules, such as tests and the trace-validation subfolders, are unrestricted. Imports outside the specification namespace are unrestricted except for the `CCF` restrictions above. From 8cf7b4b86eb3fc505fcb714deae459bfc0754d84 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Tue, 17 Nov 2026 18:19:17 +0000 Subject: [PATCH 25/25] Document the reviewed and unreviewed trace-validation folders State in the layout policy, the consensus README and the replay README that the reviewed surface is TraceValidation.lean and the files directly in TraceValidation/, and that MTv/, Validator/ and Proofs/ are not reviewed. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/AGENT.md | 28 ++++++++++--------- .../Consensus/TraceValidation/MTv/Full.lean | 2 +- lean/consensus/README.md | 26 ++++++++--------- lean/consensus/replay/README.md | 12 +++++--- 4 files changed, 37 insertions(+), 31 deletions(-) diff --git a/lean/AGENT.md b/lean/AGENT.md index 1b9ff7f270a6..89282043cf66 100644 --- a/lean/AGENT.md +++ b/lean/AGENT.md @@ -13,17 +13,18 @@ To be clear being able to save 1 line of human readable code at the cost of 1000 Within a model's library directory, use this layout: -| Location | Responsibility | -| ---------------------- | ----------------------------------------------------------------------------------------------------- | -| `Model.lean` | Assemble the executable model, including configuration and network composition. | -| `Model/` | Model-specific definitions and transitions. For disaster recovery, this includes `Model/Local.lean`. | -| `../common/CCF/` | Reusable transition systems, network composition, and execution definitions in the `CCF` namespace. | -| `Properties.lean` | State safety theorems and witness lemmas explicitly, linked to checked implementations. | -| `Properties/` | Definitions needed to state and understand those claims, such as state and trace predicates. | -| `Proofs/` | Supporting derivations, ghost state, strengthening invariants, and correspondence proofs. | -| `Tests/` | Executable model checks and regression cases. | -| `TraceValidation.lean` | State that accepted implementation traces refine the model. | -| `TraceValidation/` | Declared state, trace events, observation, state mapping, implementation model, validator and proofs. | +| Location | Responsibility | +| ---------------------- | ---------------------------------------------------------------------------------------------------- | +| `Model.lean` | Assemble the executable model, including configuration and network composition. | +| `Model/` | Model-specific definitions and transitions. For disaster recovery, this includes `Model/Local.lean`. | +| `../common/CCF/` | Reusable transition systems, network composition, and execution definitions in the `CCF` namespace. | +| `Properties.lean` | State safety theorems and witness lemmas explicitly, linked to checked implementations. | +| `Properties/` | Definitions needed to state and understand those claims, such as state and trace predicates. | +| `Proofs/` | Supporting derivations, ghost state, strengthening invariants, and correspondence proofs. | +| `Tests/` | Executable model checks and regression cases. | +| `TraceValidation.lean` | State that accepted implementation traces refine the model. | +| `TraceValidation/` | Reviewed: declared state, trace events and their decoding, observation and state mapping. | +| `TraceValidation/*/` | Not reviewed: the implementation model, validator and proofs, each in a sensibly named subfolder. | ## Dependency direction @@ -32,6 +33,7 @@ Within a model's library directory, use this layout: - Property helpers in `Properties/` should depend on the model, shared definitions, and other property helpers. They may not import `Properties.lean` or `Proofs/`. - Let `Proofs/` depend on model definitions, property helpers, and other supporting proofs, but not `Properties.lean`. +- Files directly in `TraceValidation/` may import only the model, `common/CCF/` definitions (not `CCF.Proofs`), `TraceValidation.lean` and each other, so the reviewed surface reads without its subfolders. `Properties.lean` publicly imports the types and helpers needed to understand its statements and privately imports proof implementations. Write the full logical statement in each public safety theorem and existential witness lemma, rather than defining a separate named proposition. @@ -78,7 +80,7 @@ Moving ghost definitions into `Properties/` merely to remove an import does not Review the model, full statements and proof links in `Properties.lean`, and the property helpers used by those statements. Keep the detailed proof implementations machine-checked and within the axiom allowlist. -For trace validation, review the files that `consensus/replay/README.md` lists; its proofs under `TraceValidation/Proofs/` follow the same rule. +For trace validation, review `TraceValidation.lean` and the files directly in `TraceValidation/`; its subfolders are machine-checked like `Proofs/`. Retain the package-level import root, whole-package import coverage with `lake exe check-imports`, and kernel and axiom-dependency checks with `lake check`. The proof entrypoint does not replace either check. @@ -87,4 +89,4 @@ For disaster recovery, see the [validation commands](disaster-recovery/README.md The shared `lake exe check-imports` command checks dependency direction for every specification library root discovered from Lake. Do not add per-model architecture tests; see [the common package](common/README.md#architecture-checks) for the policy. -It keeps common and model modules independent of properties and proofs, property helpers independent of proofs and theorem entrypoints, and proof implementations independent of the final theorem entrypoint. +It keeps common and model modules independent of properties and proofs, property helpers independent of proofs and theorem entrypoints, proof implementations independent of the final theorem entrypoint, and the reviewed trace-validation files independent of their subfolders. diff --git a/lean/consensus/Consensus/TraceValidation/MTv/Full.lean b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean index 3c33cc662a01..a07a063218b4 100644 --- a/lean/consensus/Consensus/TraceValidation/MTv/Full.lean +++ b/lean/consensus/Consensus/TraceValidation/MTv/Full.lean @@ -14,7 +14,7 @@ The handlers (`Consensus.TraceValidation.MTv.Aft`) run on `State`: the reviewed state (`Exec.Declared`) with the whole ledger instead of the entries the node holds. For a node that joined from a snapshot, the entries up to `base` are a ghost: the machine fills them at the `init_as_backup` release from a node that has committed them -(`Consensus.TraceValidation.MTv.Machine.fillSnapshot`), so that the clean `initAsBackup` input +(`fillSnapshot` in `MTv/Machine.lean`), so that the clean `initAsBackup` input is admitted. `State.declared` projects them away; the machine checks that no hold's outcome depends on them (`Machine.ghostFree`). diff --git a/lean/consensus/README.md b/lean/consensus/README.md index 556c36fdefa4..a68c161a9fe9 100644 --- a/lean/consensus/README.md +++ b/lean/consensus/README.md @@ -5,19 +5,19 @@ It assumes familiarity with the [CCF consensus protocol documentation](../../doc ## Source map -| Area | Source | -| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| Node state, log entries, log queries | [`Model/NodeState.lean`](Consensus/Model/NodeState.lean) | -| Configurations, quorums, retirement | [`Model/ClusterConfig.lean`](Consensus/Model/ClusterConfig.lean) (`activeConfigurations`, `hasQuorum`, `NodeState.retirement`) | -| Messages | [`Model/Messages.lean`](Consensus/Model/Messages.lean) | -| Protocol policy (one node's step) | [`Model/Node.lean`](Consensus/Model/Node.lean) (`Node.step`, `receive`, `act`, `highestCommittableIndex`, `eligiblePeers`) | -| Initial states and network composition | [`Model.lean`](Consensus/Model.lean) (`initialNodeState`, `transitionSystem`) | -| Safety theorems and witness lemmas | [`Properties.lean`](Consensus/Properties.lean) | -| Valid initial memberships | [`Properties/Config.lean`](Consensus/Properties/Config.lean) | -| Supporting proofs and executions | [`Proofs/`](Consensus/Proofs) | -| Trace validation: statement | [`TraceValidation.lean`](Consensus/TraceValidation.lean) (`accepted_refines`) | -| Trace validation: model and validator | [`TraceValidation/`](Consensus/TraceValidation) (declared state, observation, `abs`, M_tv, validator, proofs) | -| Action-trace tests | [`Tests/CanonicalTraces.lean`](Consensus/Tests/CanonicalTraces.lean) | +| Area | Source | +| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Node state, log entries, log queries | [`Model/NodeState.lean`](Consensus/Model/NodeState.lean) | +| Configurations, quorums, retirement | [`Model/ClusterConfig.lean`](Consensus/Model/ClusterConfig.lean) (`activeConfigurations`, `hasQuorum`, `NodeState.retirement`) | +| Messages | [`Model/Messages.lean`](Consensus/Model/Messages.lean) | +| Protocol policy (one node's step) | [`Model/Node.lean`](Consensus/Model/Node.lean) (`Node.step`, `receive`, `act`, `highestCommittableIndex`, `eligiblePeers`) | +| Initial states and network composition | [`Model.lean`](Consensus/Model.lean) (`initialNodeState`, `transitionSystem`) | +| Safety theorems and witness lemmas | [`Properties.lean`](Consensus/Properties.lean) | +| Valid initial memberships | [`Properties/Config.lean`](Consensus/Properties/Config.lean) | +| Supporting proofs and executions | [`Proofs/`](Consensus/Proofs) | +| Trace validation: reviewed statement and mapping | [`TraceValidation.lean`](Consensus/TraceValidation.lean) (`accepted_refines`) and the files directly in [`TraceValidation/`](Consensus/TraceValidation) | +| Trace validation: not reviewed | [`TraceValidation/MTv/`](Consensus/TraceValidation/MTv) (M_tv), [`Validator/`](Consensus/TraceValidation/Validator), [`Proofs/`](Consensus/TraceValidation/Proofs) | +| Action-trace tests | [`Tests/CanonicalTraces.lean`](Consensus/Tests/CanonicalTraces.lean) | Transition systems, traces, effects and network composition come from the local [`ccf_common` package](../common/README.md). Each node reads membership, quorums and retirement from its own ledger; there is no model-wide configuration after initialization. diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 4dbb376407dd..d803088de866 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -74,9 +74,9 @@ Its proof, in [`TraceValidation/Proofs`](../Consensus/TraceValidation/Proofs), i Properties are stated and proved of the clean model only ([`Properties.lean`](../Consensus/Properties.lean)); trace validation claims nothing more of the implementation than this refinement. The proof reduces it to one obligation per `cft.h` handler, each stated in [`Obligation.lean`](../Consensus/TraceValidation/Proofs/Obligation.lean) and proved in its own file under [`Proofs/Handlers/`](../Consensus/TraceValidation/Proofs/Handlers) ([`Handlers.lean`](../Consensus/TraceValidation/Proofs/Handlers.lean) assembles them). -To review: `TraceValidation.lean`, `CCF.Observation`, and `State`, `Event`, `Action`, `Observe` and `Abs` in [`TraceValidation/`](../Consensus/TraceValidation). -`Handler`, `Aft`, `Machine` and `Validator` are the executable model and its scheduler, and `Invariant` and `Lockstep` the invariants and the diagnostic check; the proofs cover them. -The decoder (`Event`) and the per-node split are trusted. +To review: [`TraceValidation.lean`](../Consensus/TraceValidation.lean), the files directly in [`TraceValidation/`](../Consensus/TraceValidation) (`State`, `Event`, `Input`, `Action`, `Observe` and `Abs`), and [`CCF.Observation`](../../common/CCF/Observation.lean). +They import only each other, the clean model and `lean/common` definitions, which `lake exe check-imports` enforces; the decoder and the split into per-node streams (`Event`, `Input`) are trusted, so they are among them. +Nothing in a subfolder is reviewed: [`MTv/`](../Consensus/TraceValidation/MTv) is M_tv (the handler monad, the `cft.h` handlers, the machine, its invariant and its full-ledger state), [`Validator/`](../Consensus/TraceValidation/Validator) the scheduler, certification and the lock-step check, and [`Proofs/`](../Consensus/TraceValidation/Proofs) the proof; the theorem covers them. ## Known implementation and specification differences @@ -115,10 +115,14 @@ A rejection names the trace line, the trace point and the field or rule that fai If its diagnostic says "known implementation and specification difference", the trace hit one of the cases listed [above](#known-implementation-and-specification-differences). Otherwise either the change is wrong, or M_tv must follow it: a new or removed event field goes in `traceFields` in [`Observe.lean`](../Consensus/TraceValidation/Observe.lean) with its comparison, and a moved trace point or changed behaviour goes in the handler of that lock hold in [`Aft.lean`](../Consensus/TraceValidation/MTv/Aft.lean). The build then fails until that handler's proof under [`Proofs/Handlers/`](../Consensus/TraceValidation/Proofs/Handlers) holds again, which is what shows the changed behaviour is still allowed by the consensus model. +A change to `Observe.lean`, or to any other file directly in `TraceValidation/`, changes the reviewed surface and needs review; a change under `MTv/` or `Proofs/` does not. ## Source -- [`TraceValidation/`](../Consensus/TraceValidation): declared state, events, observation, abstraction, M_tv, the validator and proofs. +- [`TraceValidation.lean`](../Consensus/TraceValidation.lean) and the files directly in [`TraceValidation/`](../Consensus/TraceValidation) (reviewed): the theorem, declared state, events and their decoding, observation and state mapping. +- [`TraceValidation/MTv/`](../Consensus/TraceValidation/MTv): M_tv, the model of `cft.h`. +- [`TraceValidation/Validator/`](../Consensus/TraceValidation/Validator): the scheduler, certification and the lock-step check. +- [`TraceValidation/Proofs/`](../Consensus/TraceValidation/Proofs): the proof of `accepted_refines`. - [`ReplayMain.lean`](ReplayMain.lean): validation CLI. - [`cft_scenarios_runner.py`](../../../tests/cft_scenarios_runner.py): native scenario runner and capture generation.