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
2 changes: 2 additions & 0 deletions .changes/cft-trace-entry-and-term-history.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
In the `ccf.cft` consensus trace records defined in [cft_trace_msgpack.h](src/consensus/aft/cft_trace_msgpack.h), `execute_append_entries_sync` now records the view (`vw`), seqno (`sn`) and signature flag (`gc`) of its entry, and so is traced only once the entry has applied, and `init_as_backup` records the snapshot's term history (`th`), the first seqno of each view.
The [consensus trace replayer](lean/consensus/replay/README.md#replay-contract) requires these fields, and uses them to check that a node applies the entries it was sent and that a joiner's snapshot agrees with the committed prefix it starts from.
5 changes: 1 addition & 4 deletions lean/consensus/Consensus/Replay/Groups.lean
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ def Reduced.watermark (reduced : Reduced) (ran : Array Nat) : Float :=

/--
Prepare replay identities and reduce each node's events into its queue of groups.
Request IDs continue across nodes, so they are unique in the trace.
If `lenient`, a node's groups end before its first event that no rule consumes.
-/
def reduce (streams : Array (Array Event)) (declared : List String) (lenient := false)
Expand All @@ -79,10 +78,9 @@ def reduce (streams : Array (Array Event)) (declared : List String) (lenient :=
let mut bootstrap := none
let mut queues := #[]
let mut counts := #[]
let mut nextRequestId := 1
for events in streams do
let ((found, consumed), state) ←
(CCF.Parsec.run events ((node lenient).run { header, nextRequestId })).mapError
(CCF.Parsec.run events ((node lenient).run { header })).mapError
fun error =>
match events.back? with
| some last =>
Expand All @@ -97,7 +95,6 @@ def reduce (streams : Array (Array Event)) (declared : List String) (lenient :=
bootstrap := some leader
queues := queues.push found
counts := counts.push (events.size, consumed)
nextRequestId := state.nextRequestId
let some leader := bootstrap | throw "no node bootstraps the network"
let header := { header with bootstrap := {← header.nodeId leader} }
return { header, queues, events := counts }
Expand Down
98 changes: 74 additions & 24 deletions lean/consensus/Consensus/Replay/Interpreter.lean
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,16 @@ def Header.initial (header : Header) : Model.State :=

inductive Step where
| local (node : String) (input : Input)
/-- `applied` holds the entries, by index, which the node traced applying from the packet. -/
| receive (source destination : String) (packet : Packet)
/-- Initialize from a node's committed prefix ending at `index` in term `view`. -/
| initAsBackup (node : String) (index view : Nat)
(applied : List (Nat × Entry) := [])

def Step.name : Step → String
| .local _ (.append _) => "append"
| .local _ (.sendEntries ..) => "sendEntries"
| .local _ (.timeout _) => "timeout"
| .local _ .nominateSuccessor => "nominateSuccessor"
| .local _ (.initAsBackup _) | .initAsBackup .. => "initAsBackup"
| .local _ (.initAsBackup _) => "initAsBackup"
| .receive .. => "receive"

structure ReplayState where
Expand Down Expand Up @@ -244,25 +244,46 @@ private def missing (header : Header) (pending : List Envelope)
| .error error => s!"{error}; {queued}"
| .ok _ => queued

/-- Deliver any matching queued envelope; loss is non-delivery. -/
/-- Whether a message has each of the `applied` entries at its index. -/
private def carries (applied : List (Nat × Entry)) : Model.Node.Message → Bool
| .appendEntriesRequest request =>
applied.all
fun (index, entry) =>
request.prevLogIndex < index
&& request.entries[index - request.prevLogIndex - 1]? == some entry
| _ => applied.isEmpty

/--
Deliver any matching queued envelope which carries the `applied` entries; loss is
non-delivery.
-/
private def selectPacket (replay : ReplayState) (source destination : NodeID)
(packet : Packet)
(packet : Packet) (applied : List (Nat × Entry))
: Except String Envelope := do
let pending := pendingBetween replay source 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
let matching :=
pending.filter
fun other =>
(checkPacket packet other.payload).isOk && carries applied other.payload
let some envelope := matching.head?
| throw
s!"no matching packet from '{source}' to '{destination}' carries the entries applied at {applied.map (·.1)}"
unless matching.all (·.payload == envelope.payload) do
throw
s!"ambiguous delivery from '{source}' to '{destination}': matching packets differ in model payload"
return envelope

/-- A node whose committed prefix has a signature at `index` in term `view`. -/
private def initSource (replay : ReplayState) (index view : Nat)
/--
A node whose committed prefix has the length of `entries`, the log of a snapshot as its node
traced it, and ends as it does: at a signature, in the same term.
-/
private def initSource (replay : ReplayState) (entries : List Entry)
: Except String NodeState := do
let index := entries.length
let view := termAt entries index
-- Committed prefixes in a reachable state are comparable, so any such node will do.
let some (_, source) :=
replay.state.nodes.find?
Expand All @@ -273,6 +294,25 @@ private def initSource (replay : ReplayState) (index view : Nat)
| throw s!"no node has a committed signature at {index} in term {view}"
return source

/--
Check a committed prefix against `entries`, the log of a snapshot as its node traced it:
the term of each entry, the configuration in force and the retirements. A snapshot traces
neither a configuration which a later one replaced, nor a retirement since removed, nor
which entries before its last are signatures.
-/
private def checkSnapshot (committed entries : List Entry) : Except String Unit := do
let configuration (log : List Entry) :=
(log.filterMap (·.content.metadata.configuration)).getLast?
let retired (log : List Entry) :=
log.foldl (· ∪ ·.content.metadata.retirementConfirmations) (∅ : Finset NodeID)
unless committed.map Entry.term == entries.map Entry.term do
throw
s!"term history: observed terms {entries.map Entry.term}, model {committed.map Entry.term}"
unless configuration committed == configuration entries do
throw "snapshot configuration differs from the model's"
unless (retired entries).sort.all (· ∈ retired committed) do
throw "snapshot retirement which the model has not confirmed"

/-- Run one model action, recording the envelopes it queues. -/
private def ReplayState.run (replay : ReplayState) (header : Header)
(action : Model.Action) (name : String)
Expand Down Expand Up @@ -304,6 +344,11 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr
throw
s!"model queued {render (Packet.ofMessage envelope.payload)} to '{target}' with no native send"
return { replay with queued := [] }
| .action (step@(.local node (.initAsBackup entries))) _ =>
let joiner ← header.nodeId node
let committed := (← initSource replay entries).log.take entries.length
checkSnapshot committed entries
replay.run header (.local joiner (.initAsBackup committed)) step.name
| .action (step@(.local node input)) _ =>
let node ← header.nodeId node
match input with
Expand All @@ -323,15 +368,20 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr
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
let source ← initSource replay index view
replay.run header (.local joiner (.initAsBackup (source.log.take index))) step.name
| .action (.receive source destination packet applied) _ =>
let before := (← lookup header replay destination).log
let envelope ←
selectPacket replay (← header.nodeId source) (← header.nodeId destination) packet
applied
let next ← replay.run header (.deliver envelope) "receive"
-- The model applies the entries after those the node keeps.
let after := (← lookup header next destination).log
let kept := ((before.zip after).takeWhile fun (a, b) => a == b).length
let model := ((after.zipIdx 1).drop kept).map fun (entry, index) => (index, entry)
unless model == applied do
throw
s!"the model applied the entries at {model.map (·.1)}, the node traced applying {applied.map (·.1)}"
return next

/--
Why a step must wait: a receive has no matching queued packet, or an initialization has no
Expand All @@ -341,15 +391,15 @@ The reason is built only on demand: a waiting group is retried after every other
-/
private def Step.waiting (header : Header) (replay : ReplayState)
: Step → Except String (Option (Unit → String))
| .receive source destination packet => do
| .receive source destination packet _ => do
let source ← header.nodeId source
let destination ← header.nodeId destination
let pending := pendingBetween replay source destination
if pending.any fun envelope => (checkPacket packet envelope.payload).isOk then
return none
return some fun _ => missing header pending source destination packet
| .initAsBackup _ index view =>
match initSource replay index view with
| .local _ (.initAsBackup entries) =>
match initSource replay entries with
| .ok _ => return none
| .error reason => return some fun _ => reason
| .local .. => pure none
Expand Down Expand Up @@ -400,7 +450,7 @@ private def stuck (rest : Array Group) (blocked : Array (Group × (Unit → Stri
fun (group, reason) =>
let waiting := s!"node '{group.node}' waits at {reason ()}"
match group.instructions.find? (· matches .action ..) with
| some (.action (.receive source destination packet) _) =>
| some (.action (.receive source destination packet _) _) =>
let sender := rest.filter (·.node == source)
match sender.findSome? (·.send? destination packet) with
| none => .inl s!"{waiting}; '{source}' sends no such packet later"
Expand Down
117 changes: 93 additions & 24 deletions lean/consensus/Consensus/Replay/Reduction.lean
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ open CCF.Parsec (failure validated attempt many_ optional_)

structure ReductionState where
header : Header
nextRequestId : ReqID := 1
instructions : Array Instruction := #[]
/-- The node, if its events start by bootstrapping the network. -/
bootstrap : Option String := none
Expand Down Expand Up @@ -132,16 +131,12 @@ private def readAppendContent (head : Event) (seqno : Nat) (signature : Bool)
some <$> modelMembers config fields.nodes
| none => pure none
let retirementConfirmations ← modelMembers head retiredNodes
let request := (← get).nextRequestId
modify fun s => { s with nextRequestId := request + 1 }
return .transaction request { configuration, retirementConfirmations }
-- Named by position, so every node names an entry alike; genesis, at index 1, is zero.
return .transaction (seqno - 1) { configuration, retirementConfirmations }

/-- One entry of a batch: its replicate event, retirements, configuration and flush. -/
private def readReplicateEntry (head : Event) : Reduction AppendEntryInput := do
let .replicateEntry entry := head.body | mismatch head
let some seqno := entry.seqno | liftExcept head (throw "seqno: missing")
-- consume
event head "replicate_entry"
/-- The retirements and configuration that the ledger hooks of entry `seqno` trace. -/
private def readEntryHooks (head : Event) (seqno : Nat)
: Reduction (List String × Option (Event × AddConfiguration)) := do
let retiredNodes ←
CCF.Parsec.many do
let retirement ← peek
Expand All @@ -157,6 +152,15 @@ private def readReplicateEntry (head : Event) : Reduction AppendEntryInput := do
let .addConfiguration fields := config.body | mismatch config
many_ (event head "send_append_entries")
return (config, fields)
return (retiredNodes, config)

/-- One entry of a batch: its replicate event, retirements, configuration and flush. -/
private def readReplicateEntry (head : Event) : Reduction AppendEntryInput := do
let .replicateEntry entry := head.body | mismatch head
let some seqno := entry.seqno | liftExcept head (throw "seqno: missing")
-- consume
event head "replicate_entry"
let (retiredNodes, config) ← readEntryHooks head seqno
let flushes ←
CCF.Parsec.optionalRule do
event head "batch_flush"
Expand Down Expand Up @@ -202,27 +206,39 @@ private def readReceive (head : Event) (families : List String) : Reduction Step
(require (families.contains packet.msg) "receive function/packet mismatch")
return .receive from_node_id head.node packet

/-- An entry of the packet received from `source`, which the node traced applying. -/
private def readAppliedEntry (head : Event) (source : String)
: Reduction (Nat × Entry) := do
let next ← peek
event head "execute_append_entries_sync"
let .executeAppendEntries entry := next.body | mismatch next
liftExcept next
(require (entry.from_node_id == source) s!"expected an entry from {source}")
let (retiredNodes, config) ← readEntryHooks head entry.seqno
let content ←
readAppendContent next entry.seqno entry.globally_committable config retiredNodes
return (entry.seqno, ⟨entry.view, content⟩)

private def ruleRecvAppendEntries : Reduction Unit := do
let head ← peek
let action ← readReceive head ["append_entries"]
let .receive source destination packet _ ← readReceive head ["append_entries"]
| mismatch head
-- 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_ (nominate head)))
let applied ←
CCF.Parsec.many
((some <$> readAppliedEntry head source)
<|> (do
event head "commit"
optional_ (nominate head)
return none))
optional_ (event head "send_append_entries_response")
-- emit
emitObserve head "recv-append-entries"
emitAction head "recv-append-entries" action
emitAction head "recv-append-entries"
(.receive source destination packet (applied.filterMap id))
emitObserveSends head (← extractSends start)

private def ruleRecvAppendEntriesResponse : Reduction Unit := do
Expand Down Expand Up @@ -361,6 +377,58 @@ private def ruleDrop : Reduction Unit := do
-- consume
event head "drop_pending_to"

/--
The log of a snapshot at `seqno`, as far as its node traces it. `termHistory` is the first seqno
of each view, which gives each entry its term; the signature ends the log; and the hooks
which ran before `init` give its configurations and retirements. A hook at `seqno` itself
is of the state which the signature signs, so it goes on the entry before.
Which earlier entries were signatures is not traced.
-/
private def readSnapshotLog (init : Event) (seqno view : Nat) (termHistory : List Nat)
: Reduction (List Entry) := do
let hooks ←
liftM (m := CCF.Parsec.Parser Event)
((fun input => .success input (input.events.extract 0 input.position))
: CCF.Parsec.Parser Event (Array Event))
let viewAt (index : Nat) := (termHistory.filter (· ≤ index)).length
liftExcept init do
require ((termHistory.zip termHistory.tail).all fun (a, b) => a ≤ b)
"term history out of order"
require (termHistory.all fun start => 1 ≤ start && start ≤ seqno)
"term history outside the snapshot"
require (viewAt seqno == view) "the term history gives the snapshot another view"
let mut updates : Array (Nat × (TransactionMetadata → TransactionMetadata)) := #[]
for hook in hooks do
let (index, update) ←
match hook.body with
| .addConfiguration fields => do
let nodes ← modelMembers hook fields.nodes
pure
(
fields.idx.getD 0,
fun (m : TransactionMetadata) => { m with configuration := some nodes }
)
| .retiredCommittedTx fields => do
let retired ← modelMembers hook [fields.retired_node_id]
pure
(
fields.seqno,
fun (m : TransactionMetadata) =>
{ m with retirementConfirmations := m.retirementConfirmations ∪ retired }
)
| _ => continue
liftExcept hook
(require (1 ≤ index && index ≤ seqno && 2 ≤ seqno)
s!"hook outside the snapshot at {seqno}")
updates := updates.push (min index (seqno - 1), update)
if seqno == 0 then return []
let mut entries := #[]
for index in [1:seqno] do
let metadata :=
updates.foldl (fun m (at_, update) => if at_ == index then update m else m) {}
entries := entries.push ⟨viewAt index, .transaction (index - 1) metadata⟩
return (entries.push ⟨view, .signature⟩).toList

/--
Snapshot installation runs ledger hooks outside the consensus lock, so bare ticks
may interleave with their events.
Expand All @@ -387,10 +455,11 @@ private def ruleInitAsBackup : Reduction Unit := do
let init ← peek
event head "init_as_backup"
event head "become_follower"
let .initAsBackup { seqno, view, .. } := init.body | mismatch init
let .initAsBackup { seqno, view, term_history, .. } := init.body | mismatch init
let entries ← readSnapshotLog init seqno view term_history
-- emit
emitObserve init "init-as-backup"
emitAction init "init-as-backup" (.initAsBackup head.node seqno view)
emitAction init "init-as-backup" (.local head.node (.initAsBackup entries))

def ruleStep : Reduction Unit := do
-- Recv rules
Expand Down
Loading