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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/single-node-consensus-replay.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The [consensus trace replayer](lean/consensus/replay/README.md#single-node-validation) now supports `--mode=single-node` (with optional `--node=NODE`) to validate nodes independently on `Consensus.Model.Node.step` without modeling the network.
4 changes: 4 additions & 0 deletions .github/workflows/lean-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ jobs:
[ "$(replay invalid/missing-packet.ndjson | jq '.watermark < 1')" = true ]
if replay invalid/snapshot-mismatch.ndjson; then exit 1; fi

- name: Check single-node CCF consensus replay
if: inputs.package == 'consensus'
run: python3 lean/consensus/replay/check-single-node.py lean/consensus/.lake/build/bin/consensus-replay

- name: Check recovery trace fixtures against their schema
if: inputs.package == 'disaster-recovery'
run: |
Expand Down
44 changes: 33 additions & 11 deletions lean/consensus/Consensus/Replay/Groups.lean
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ private def group : Reduction (Option Group) := do
start,
m_ts := head.m_ts,
ts := head.ts,
instructions := state.instructions
instructions := state.instructions,
final := (← CCF.Parsec.peek).isNone
}

/--
Expand Down Expand Up @@ -68,6 +69,36 @@ def Reduced.watermark (reduced : Reduced) (ran : Array Nat) : Float :=
min low (consumed.toFloat / total.toFloat))
1

private def reduceStream (header : Header) (events : Array Event) (lenient : Bool)
: Except String ((Array Group × Nat) × Reducer.ReductionState) :=
(CCF.Parsec.run events ((node lenient).run { header })).mapError
fun error =>
match events.back? with
| some last =>
if error == "unexpected end of input" then
s!"{last.record.location}: the events of node '{last.node}' end inside a group"
else
error
| none => error

/--
Reduce one node's events into its groups. The node need not bootstrap the network; if it
does, it is its own initial membership.
-/
def reduceNode (events : Array Event) (declared : List String) (lenient := false)
: Except String Reduced := do
let header : Header := { bootstrap := ∅, declared }
let ((found, consumed), state) ← reduceStream header events lenient
let bootstrap ←
match state.bootstrap with
| some leader => pure {← header.nodeId leader}
| none => pure ∅
return {
header := { header with bootstrap },
queues := #[found],
events := #[(events.size, consumed)]
}

/--
Prepare replay identities and reduce each node's events into its queue of groups.
If `lenient`, a node's groups end before its first event that no rule consumes.
Expand All @@ -79,16 +110,7 @@ def reduce (streams : Array (Array Event)) (declared : List String) (lenient :=
let mut queues := #[]
let mut counts := #[]
for events in streams do
let ((found, consumed), state) ←
(CCF.Parsec.run events ((node lenient).run { header })).mapError
fun error =>
match events.back? with
| some last =>
if error == "unexpected end of input" then
s!"{last.record.location}: the events of node '{last.node}' end inside a group"
else
error
| none => error
let ((found, consumed), state) ← reduceStream header events lenient
if let some leader := state.bootstrap then
if let some other := bootstrap then
throw s!"nodes '{other}' and '{leader}' both bootstrap the network"
Expand Down
2 changes: 2 additions & 0 deletions lean/consensus/Consensus/Replay/Input.lean
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ def prepareEvents (records : Array Record)
match body with
| .retiredCommittedTx event => declared := event.retired_node_id :: declared
| .addConfiguration event => declared := event.nodes ++ declared
| .recv event => declared := event.from_node_id :: declared
| .send event => declared := event.to_node_id :: declared
| _ => pure ()
let streams :=
pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node)
Expand Down
229 changes: 196 additions & 33 deletions lean/consensus/Consensus/Replay/Interpreter.lean
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ structure Group where
ts : Option Nat
/-- What the group's rule emitted, run with no other group's actions in between. -/
instructions : Array Instruction
/-- No event of the node follows the group, so a capture cut short may have cut it. -/
final : Bool := false

/-- Where the group starts, with its rule. -/
def Group.label (group : Group) : String :=
Expand All @@ -116,12 +118,9 @@ private def lookup (header : Header) (replay : ReplayState) (node : String)
| throw s!"node '{node}' is not in the network"
return state

/-- Compare an action-boundary snapshot with the current model node. -/
def observeState (header : Header) (node : String) (expected : StateSnapshot)
(replay : ReplayState)
private def observeNodeState (node : String) (self : NodeID) (expected : StateSnapshot)
(state : NodeState)
: Except String Unit := do
let state ← lookup header replay node
let self ← header.nodeId node
check "node_id" (some expected.node_id) fun _ => node
check "leadership_state" expected.leadership_state
fun _ =>
Expand Down Expand Up @@ -169,6 +168,12 @@ def observeState (header : Header) (node : String) (expected : StateSnapshot)
check "retired_committed_idx" (expected.retired_committed_idx.map some)
fun _ => state.retiredCommittedIndex

/-- Compare an action-boundary snapshot with the current model node. -/
def observeState (header : Header) (node : String) (expected : StateSnapshot)
(replay : ReplayState)
: Except String Unit := do
observeNodeState node (← header.nodeId node) expected (← lookup header replay node)

/-- Physical packet coordinates; lower-term NACK hints are not election terms. -/
def Packet.ofMessage : Model.Node.Message → Packet
| .appendEntriesRequest request =>
Expand Down Expand Up @@ -323,6 +328,36 @@ private def ReplayState.run (replay : ReplayState) (header : Header)
let pending := replay.state.network.length - if action matches .deliver _ then 1 else 0
return { state, queued := replay.queued ++ state.network.drop pending }

private def matchSends (header : Header) (queued : List Envelope)
(sends : List NativeSend)
: Except String (List Envelope) := do
let mut queued := 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: {render send.packet}"
(checkPacket send.packet envelope.payload).mapError (s!"{context}: " ++ ·)
queued := removeOne envelope queued
return queued

private def checkLocalInput (header : Header) (input : Input) : Except String Unit := do
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 ()

/-- Observations never change model state or repair a disabled action. -/
def runInstruction (header : Header) (replay : ReplayState) (instruction : Instruction)
: Except String ReplayState := do
Expand All @@ -331,14 +366,7 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr
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: {render send.packet}"
(checkPacket send.packet envelope.payload).mapError (s!"{context}: " ++ ·)
queued := removeOne envelope queued
let queued ← matchSends header replay.queued sends
if let some envelope := queued.head? then
let target := header.declared[envelope.target]?.getD (toString envelope.target)
throw
Expand All @@ -351,22 +379,7 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr
replay.run header (.local joiner (.initAsBackup committed)) step.name
| .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 ()
checkLocalInput header input
replay.run header (.local node input) step.name
| .action (.receive source destination packet applied) _ =>
let before := (← lookup header replay destination).log
Expand Down Expand Up @@ -473,19 +486,22 @@ receive, and a committed prefix stays committed, so the verdict does not depend
enabled group runs.
If `lenient`, replay ends without failing once no group may run.
-/
def schedule (header : Header) (queues : Array (Array Group)) (lenient := false)
: ExceptT String (StateM (Array Group)) Result := do
private def checkHeader (header : Header) : Except String Unit := 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}"

def schedule (header : Header) (queues : Array (Array Group)) (lenient := false)
: ExceptT String (StateM (Array Group)) Result := do
ofExcept (checkHeader header)
unless header.bootstrap.Nonempty do
throw "initial membership must be nonempty"
let total := queues.foldl (· + ·.size) 0
let key (group : Group) := group.ts.getD group.m_ts
let mut state : ReplayState := { state := header.initial }
Expand Down Expand Up @@ -518,4 +534,151 @@ def schedule (header : Header) (queues : Array (Array Group)) (lenient := false)
let actions := (instructions.filter (· matches .action ..)).size
return { ran := next, actions, observations := instructions.size - actions }

/--
The message of a received packet, the reverse of `Packet.ofMessage`.
A packet omits the entries of an AppendEntries, so they are those the node holds, up to its
first of another term, then those it traced applying, all in the packet's term. An entry
which the node did not read is unknown, so a placeholder stands for it: the second result is
the first, by index, which the model must not apply.
-/
private def Packet.toMessage (packet : Packet) (log : List Entry)
(applied : List (Nat × Entry))
: Except String (Message × Option (Nat × Entry)) := do
let vote (p : Packet.RequestVote) : RequestVoteRequest :=
⟨p.term, p.term_of_last_committable_idx, p.last_committable_idx⟩
let (message, firstUntraced) ←
match packet with
| .appendEntries p => do
unless p.prev_idx ≤ p.idx && !p.contains_new_view do
throw "impossible AppendEntries header"
let count := p.idx - p.prev_idx
let held := ((log.drop p.prev_idx).take count).takeWhile (·.term == p.term_of_idx)
let heldThrough := p.prev_idx + held.length
unless applied.all (·.2.term == p.term_of_idx)
&& applied.map Prod.fst
== (List.range applied.length).map (heldThrough + 1 + ·)
&& held.length + applied.length ≤ count do
throw "applied entries do not follow those the node holds, in the packet's term"
let start := heldThrough + applied.length + 1
let unread :=
(List.range (count - held.length - applied.length)).map
fun k => ⟨p.term_of_idx, .transaction (start + k - 1) {}⟩
let entries := held ++ applied.map Prod.snd ++ unread
pure
(
Message.appendEntriesRequest
⟨p.term, p.prev_idx, p.prev_term, entries, p.leader_commit_idx⟩,
unread.head?.map (start, ·)
)
| .appendEntriesResponse p =>
pure (.appendEntriesResponse ⟨p.term, p.success == "OK", p.last_log_idx⟩, none)
| .requestVote p => pure (.requestVoteRequest (vote p), none)
| .requestPreVote p => pure (.requestPreVoteRequest (vote p), none)
| .requestVoteResponse p =>
pure (.requestVoteResponse ⟨p.term, p.vote_granted⟩, none)
| .requestPreVoteResponse p =>
pure (.requestPreVoteResponse ⟨p.term, p.vote_granted⟩, none)
| .proposeRequestVote p => pure (.proposeRequestVoteRequest p.term, none)
checkPacket packet message
return (message, firstUntraced)

/-- Why a single-node group does not validate. -/
private inductive Failure where
| mismatch (reason : String)
| incomplete (reason : String)

/-- One node, replayed alone on `Model.Node.step`. -/
private structure NodeReplay where
state : NodeState
/-- Envelopes queued by the group's actions which no send observation has matched. -/
queued : List Envelope := []
/-- The model applied an entry which the node did not trace applying. -/
untraced : Bool := false

private def NodeReplay.run (replay : NodeReplay) (self : NodeID)
(event : Model.Node.Event) (name : String)
: Except String NodeReplay := do
let some (state, outputs) :=
(Model.Node.step (CCF.Capabilities.record self) self replay.state event).run {}
| throw s!"disabled model action '{name}'"
return { replay with state, queued := replay.queued ++ outputs.outgoing }

private def runNodeInstruction (header : Header) (self : NodeID) (replay : NodeReplay)
(instruction : Instruction)
: Except String NodeReplay := do
match instruction with
| .observeNodeState node expected _ =>
observeNodeState node self expected replay.state
return replay
| .observeSends sends _ =>
return { replay with queued := ← matchSends header replay.queued sends }
| .action (step@(.local node input)) _ =>
unless (← header.nodeId node) == self do
throw s!"action belongs to node '{node}'"
checkLocalInput header input
replay.run self (.internal input) step.name
| .action (.receive source destination packet applied) _ =>
unless (← header.nodeId destination) == self do
throw s!"receive belongs to node '{destination}'"
let source ← header.nodeId source
let (message, firstUntraced) ← packet.toMessage replay.state.log applied
let next ← replay.run self (.receive source message) "receive"
unless applied.all fun (i, entry) => entryAt? next.state.log i == some entry do
throw "the node traced applying an entry which the model did not"
let untraced :=
next.state.log != replay.state.log
&& firstUntraced.any fun (i, entry) => entryAt? next.state.log i == some entry
return { next with untraced := next.untraced || untraced }

private def runNodeGroup (header : Header) (self : NodeID) (replay : NodeReplay)
(group : Group)
: Except Failure NodeReplay := do
let replay ←
(group.instructions.foldlM
(fun replay instruction =>
(runNodeInstruction header self replay instruction).mapError
(s!"{instruction.origin.label}: " ++ ·))
replay).mapError
.mismatch
if let some envelope := replay.queued.head? then
let target := header.declared[envelope.target]?.getD (toString envelope.target)
throw
(.incomplete
s!"{group.label}: model queued {render (Packet.ofMessage envelope.payload)} to '{target}' with no native send")
if replay.untraced then
throw
(.mismatch
s!"{group.label}: the model applied an entry which the node did not trace")
return replay

/--
Validate one node's groups alone on `Model.Node.step`, from its initial state.
No other node is read, so this does not show that a received packet was sent or that a
snapshot was committed. If `lenient`, stops before a final group which is incomplete.
-/
def validateNode (header : Header) (groups : Array Group) (lenient := false)
: Except String Result := do
checkHeader header
let mut ran := 0
if let some first := groups[0]? then
let self ← header.nodeId first.node
let mut replay : NodeReplay :=
{ state := Model.initialNodeState header.bootstrap self }
for group in groups do
unless group.node == first.node do
throw
s!"{group.label}: group belongs to node '{group.node}', expected '{first.node}'"
match runNodeGroup header self replay group with
| .ok after =>
replay := after
ran := ran + 1
| .error (.incomplete reason) =>
unless lenient && group.final do
throw reason
break
| .error (.mismatch reason) => throw reason
let instructions := (groups.extract 0 ran).flatMap (·.instructions)
let actions := (instructions.filter (· matches .action ..)).size
return { ran := #[ran], actions, observations := instructions.size - actions }

end Consensus.Replay
Loading