diff --git a/.changes/cross-node-consensus-replay.added.md b/.changes/cross-node-consensus-replay.added.md new file mode 100644 index 00000000000..ba5bbd5b188 --- /dev/null +++ b/.changes/cross-node-consensus-replay.added.md @@ -0,0 +1,2 @@ +The [consensus trace replayer](lean/consensus/replay/README.md#cross-node-checks) now checks nodes against each other: every received packet must have a traced send, and nodes holding the same signature must hold the same entries behind it. +With `--lenient`, receives with no traced send are counted in the new `unsent` field of the result rather than rejected. diff --git a/.changes/per-node-consensus-replay.added.md b/.changes/per-node-consensus-replay.added.md new file mode 100644 index 00000000000..e174b9fd4a0 --- /dev/null +++ b/.changes/per-node-consensus-replay.added.md @@ -0,0 +1 @@ +The [consensus trace replayer](lean/consensus/replay/README.md#per-node-validation) now validates each node on its own events alone, replacing the global scheduler and its `--schedule` diagnostic, and reports the least fraction of any node's events that validated. diff --git a/.github/workflows/lean-package.yml b/.github/workflows/lean-package.yml index e5866886a31..38434f5e068 100644 --- a/.github/workflows/lean-package.yml +++ b/.github/workflows/lean-package.yml @@ -133,17 +133,9 @@ jobs: echo "::endgroup::" done - - name: Replay an incomplete CCF consensus trace + - name: Check per-node replay of cut and altered captures if: inputs.package == 'consensus' - run: | - set -euo pipefail - replay() { - scripts/pack-trace.py < "lean/consensus/replay/fixtures/$1" > "$RUNNER_TEMP/trace.msgpack" - lean/consensus/.lake/build/bin/consensus-replay --lenient "$RUNNER_TEMP/trace.msgpack" - } - [ "$(replay valid/replication.ndjson | jq .watermark)" = 1 ] - [ "$(replay invalid/missing-packet.ndjson | jq '.watermark < 1')" = true ] - if replay invalid/snapshot-mismatch.ndjson; then exit 1; fi + run: python3 lean/consensus/replay/check-per-node.py lean/consensus/.lake/build/bin/consensus-replay - name: Check recovery trace fixtures against their schema if: inputs.package == 'disaster-recovery' diff --git a/lean/consensus/Consensus.lean b/lean/consensus/Consensus.lean index 9cfc5f96e5c..01f5e223edd 100644 --- a/lean/consensus/Consensus.lean +++ b/lean/consensus/Consensus.lean @@ -4,4 +4,3 @@ public import Consensus.Properties public import Consensus.Replay.Groups import Consensus.Tests.CanonicalTraces -import Consensus.Tests.ReplayDelivery diff --git a/lean/consensus/Consensus/Replay/Groups.lean b/lean/consensus/Consensus/Replay/Groups.lean index 62cfe180486..290e3a398c7 100644 --- a/lean/consensus/Consensus/Replay/Groups.lean +++ b/lean/consensus/Consensus/Replay/Groups.lean @@ -11,8 +11,6 @@ public section Runs the reduction rules over each node's events: peek the next event, run one rule from it, and take what the rule emitted as a group. The peeked event gives the group's node and times, so the rules track neither. -A receive or `init_as_backup` must be its rule's first action, since replay decides from -that action whether the group waits. -/ namespace Consensus.Replay @@ -36,7 +34,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 } /-- diff --git a/lean/consensus/Consensus/Replay/Input.lean b/lean/consensus/Consensus/Replay/Input.lean index b9a8efa4a94..d4f2c46a501 100644 --- a/lean/consensus/Consensus/Replay/Input.lean +++ b/lean/consensus/Consensus/Replay/Input.lean @@ -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) diff --git a/lean/consensus/Consensus/Replay/Interpreter.lean b/lean/consensus/Consensus/Replay/Interpreter.lean index 840a5a205cb..96e73802c10 100644 --- a/lean/consensus/Consensus/Replay/Interpreter.lean +++ b/lean/consensus/Consensus/Replay/Interpreter.lean @@ -6,13 +6,15 @@ module public import Consensus.Model public import Consensus.Replay.Trace +import Std.Data.HashMap.Basic + public section namespace Consensus.Replay open Model.Node open CCF (Finset) -open CCF.MultiNodeTransitionSystem (nodeState removeOne) +open CCF.MultiNodeTransitionSystem (removeOne) abbrev Envelope := Model.Envelope @@ -36,14 +38,6 @@ def Header.nodeId (header : Header) (node : String) : Except String NodeID := do | 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) /-- `applied` holds the entries, by index, which the node traced applying from the packet. -/ @@ -58,10 +52,13 @@ def Step.name : Step → String | .local _ (.initAsBackup _) => "initAsBackup" | .receive .. => "receive" +/-- One node, replayed alone. -/ structure ReplayState where - state : Model.State - /-- Envelopes queued by actions since the last send observation. -/ + 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 /-- A traced native send, or the proposal a nomination implies. -/ structure NativeSend where @@ -96,6 +93,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 := @@ -109,18 +108,11 @@ private def check {α : Type} [BEq α] [Repr α] (field : String) (observed : Op unless observed == model () do throw s!"{field}: observed {repr observed}, model {repr (model ())}" -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 - /-- Compare an action-boundary snapshot with the current model node. -/ def observeState (header : Header) (node : String) (expected : StateSnapshot) (replay : ReplayState) : Except String Unit := do - let state ← lookup header replay node + let state := replay.state let self ← header.nodeId node check "node_id" (some expected.node_id) fun _ => node check "leadership_state" expected.leadership_state @@ -222,106 +214,73 @@ private def closest (packet : Packet) (envelopes : List Envelope) : Option Envel <|> envelopes.find? fun envelope => (Packet.ofMessage envelope.payload).msg == packet.msg -private def pendingBetween (replay : ReplayState) (source destination : NodeID) - : List Envelope := - replay.state.network.filter - fun envelope => envelope.source == source && envelope.target == destination - -/-- Why no queued envelope renders `packet`, diffing the closest in rendered order. -/ -private def missing (header : Header) (pending : List Envelope) - (source destination : NodeID) (packet : Packet) - : String := - let name (node : NodeID) := header.declared[node]?.getD (toString node) - let sorted := - (pending.map fun envelope => (render (Packet.ofMessage envelope.payload), envelope)) - |>.mergeSort fun a b => a.1 ≤ b.1 - let pending := sorted.map Prod.snd - match closest packet pending <|> pending.head? with - | none => s!"no pending packet from '{name source}' to '{name destination}'" - | some envelope => - let queued := s!"queued from '{name source}': {sorted.map Prod.fst}" - match checkPacket packet envelope.payload with - | .error error => s!"{error}; {queued}" - | .ok _ => queued - -/-- 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) (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 - 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 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? - 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}" - return source +/-- Why a group does not validate. -/ +private inductive Failure where + /-- The trace contradicts the model. -/ + | mismatch (reason : String) + /-- The model did more than the trace shows, as when the capture ends inside the group. -/ + | incomplete (reason : String) /-- -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. +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 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) +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 heldThrough := + p.prev_idx + + ((List.range (p.idx - p.prev_idx)).takeWhile + fun k => + (entryAt? log (p.prev_idx + k + 1)).any (·.term == p.term_of_idx)).length + unless applied.all + (fun (i, entry) => + heldThrough < i && i ≤ p.idx && entry.term == p.term_of_idx) + && (applied.zip applied.tail).all (fun (a, b) => a.1 + 1 == b.1) + && applied.head?.all (·.1 == heldThrough + 1) do + throw "applied entries do not follow those the node holds, in the packet's term" + let entries := + (List.range (p.idx - p.prev_idx)).map + fun k => + let i := p.prev_idx + k + 1 + match if i ≤ heldThrough then entryAt? log i else applied.lookup i with + | some entry => (i, entry, true) + | none => (i, ⟨p.term_of_idx, .transaction (i - 1) {}⟩, false) + pure + ( + Message.appendEntriesRequest + ⟨p.term, p.prev_idx, p.prev_term, entries.map (·.2.1), p.leader_commit_idx⟩, + (entries.find? (!·.2.2)).map fun (i, entry, _) => (i, entry) + ) + | .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) + +/-- Run one action on the model of the node, recording the envelopes it queues. -/ +private def ReplayState.run (replay : ReplayState) (self : NodeID) + (event : Model.Node.Event) (name : String) : Except String ReplayState := do - let some state := Model.networkStep header.bootstrap replay.state action + let some (state, outputs) := + (Model.Node.step (CCF.Capabilities.record self) self replay.state event).run {} | 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 } + return { replay with state, queued := replay.queued ++ outputs.outgoing } /-- Observations never change model state or repair a disabled action. -/ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instruction) @@ -339,16 +298,7 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr | throw s!"{context}: not queued by the model: {render send.packet}" (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 {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 + return { replay with queued } | .action (step@(.local node input)) _ => let node ← header.nodeId node match input with @@ -367,114 +317,85 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr unless destination < header.declared.length do throw s!"undeclared model node {destination}" | _ => pure () - replay.run header (.local node input) step.name + replay.run node (.internal input) 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 + let source ← header.nodeId source + let (message, firstUntraced) ← packet.toMessage replay.state.log applied + let next ← + replay.run (← header.nodeId destination) (.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 } /-- -Why a step must wait: a receive has no matching queued packet, or an initialization has no -committed source. Both only become enabled as other nodes act. Other steps are local to a -node changed only by its own groups, so a disabled one fails when its group runs. -The reason is built only on demand: a waiting group is retried after every other group. +Run a group's instructions with no other group's actions between them. +What the model did and the group does not show makes it incomplete, unless its sends show +that the node was past an entry it did not trace applying. -/ -private def Step.waiting (header : Header) (replay : ReplayState) - : Step → Except String (Option (Unit → String)) - | .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 - | .local _ (.initAsBackup entries) => - match initSource replay entries with - | .ok _ => return none - | .error reason => return some fun _ => reason - | .local .. => pure none - -/-- Why a group must wait before its first action, located at that action. -/ -private def Group.waiting (header : Header) (replay : ReplayState) (group : Group) - : Except String (Option (Unit → String)) := do - let some (.action step origin) := group.instructions.find? (· matches .action ..) - | return none - let located := (s!"{origin.label}: " ++ ·) - return (located ∘ ·) <$> (← (step.waiting header replay).mapError located) - -/-- Run a group's instructions with no other group's actions between them. -/ private def runGroup (header : Header) (replay : ReplayState) (group : Group) - : Except String ReplayState := - group.instructions.foldlM - (fun replay instruction => - (runInstruction header replay instruction).mapError - (s!"{instruction.origin.label}: " ++ ·)) - replay + : Except Failure ReplayState := do + let replay ← + (group.instructions.foldlM + (fun replay instruction => + (runInstruction header 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 structure Result where /-- Groups run of each node, fewer than it has only if replay is lenient. -/ ran : Array Nat actions : Nat observations : Nat + /-- Receives with no traced send, none unless replay is lenient. -/ + unsent : Nat deriving Repr, BEq -/-- Where a group natively sends `packet` to `destination`. -/ -private def Group.send? (group : Group) (destination : String) (packet : Packet) - : Option Origin := - group.instructions.findSome? - fun - | .observeSends sends _ => - (sends.find? fun send => send.target == destination && send.packet == packet).map - (·.origin) - | _ => none - /-- -Explain a replay in which every node's next group waits. A receive whose sender does not -send its packet in the rest of the trace can never run; the other groups wait for another -node. +The signatures which `log` holds after the entries it shares with `before`, each by index and +term, with the entries behind it, from the signature before. Every node which holds the +signature must hold these, and so, signature by signature, the same log up to it. -/ -private def stuck (rest : Array Group) (blocked : Array (Group × (Unit → String))) - : String := - let (never, waits) := - blocked.toList.partitionMap - 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 _) _) => - let sender := rest.filter (·.node == source) - match sender.findSome? (·.send? destination packet) with - | none => .inl s!"{waiting}; '{source}' sends no such packet later" - | some origin => - .inr s!"{waiting}; '{source}' sends it later at {origin.label}" - | _ => .inr waiting - let list (title : String) (lines : List String) := - if lines.isEmpty then "" else s!"\n{title}:\n {"\n ".intercalate lines}" - "no enabled group" - ++ list "can never run" never - ++ list "waiting for another node" waits +private def signatures (before log : List Entry) : List ((Nat × Nat) × List Entry) := + if before == log then + [] + else + let shared := ((before.zip log).takeWhile fun (a, b) => a == b).length + let indexed := log.zipIdx 1 + (indexed.filter fun (entry, index) => shared < index && entry.content.isSignature).map + fun (entry, index) => + let previous := + (indexed.filter + fun (entry, i) => i < index && entry.content.isSignature).getLast? + ( + (index, entry.term), + (log.take (index - 1)).drop ((previous.map (·.2)).getD 1 - 1) + ) /-- -Run each node's groups in order, recording the groups run, ending with any that failed. -The enabled group with the earliest wall-clock time runs, then by node; without wall-clock -times `m_ts` stands in, which is the order of execution within a process and otherwise only -makes diagnostics reproducible, as counters of different processes are not comparable. -A group's node changes only through its own groups, other nodes only add packets it may -receive, and a committed prefix stays committed, so the verdict does not depend on which -enabled group runs. -If `lenient`, replay ends without failing once no group may run. +Validate each node alone: run its groups, in order, on the model of that node from its +initial state. If `lenient`, a node stops before a final group which is incomplete. +Then check the nodes against each other. Nodes which hold the same signature, by index and +term, must hold the same entries behind it; a snapshot's entries are inferred, so they are +not compared. Each receive must have a send of its packet, traced by its source, as a +multiset; if `lenient`, the source's trace may have ended before the send, so a receive +without one is counted instead. -/ -def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) - : ExceptT String (StateM (Array Group)) Result := do +def validate (header : Header) (queues : Array (Array Group)) (lenient := false) + : Except String Result := do unless !header.declared.isEmpty && header.declared.all (!·.isEmpty) && header.declared.eraseDups == header.declared do @@ -486,36 +407,55 @@ def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) for node in header.bootstrap.sort do unless node < header.declared.length do throw s!"undeclared model node {node}" - let total := queues.foldl (· + ·.size) 0 - let key (group : Group) := group.ts.getD group.m_ts - let mut state : ReplayState := { state := header.initial } - let mut next := Array.replicate queues.size 0 - for _ in [:total] do - let heads := - (queues.zipIdx.filterMap - fun (groups, queue) => (·, queue) <$> groups[next[queue]!]?) - |>.qsort fun (a, i) (b, j) => key a < key b || (key a == key b && i < j) - let mut chosen := none - let mut blocked := #[] - for (group, queue) in heads do - match ← ofExcept (group.waiting header state) with - | none => - chosen := some (group, queue) - break - | some reason => blocked := blocked.push (group, reason) - let some (group, queue) := chosen - | - if lenient then - break - let rest := queues.zipIdx.flatMap fun (groups, queue) => groups.extract next[queue]! - throw (stuck rest blocked) - modify (·.push group) - state ← ofExcept (runGroup header state group) - next := next.modify queue (· + 1) + let mut next := #[] + let mut signed : Std.HashMap (Nat × Nat) (String × List Entry) := {} + for groups in queues do + let mut ran := 0 + if let some first := groups[0]? then + let self ← header.nodeId first.node + let mut replay : ReplayState := + { state := Model.initialNodeState header.bootstrap self } + for group in groups do + match runGroup header replay group with + | .ok after => + unless group.instructions.any + (· matches .action (.local _ (.initAsBackup _)) _) do + for (signature, behind) in signatures replay.state.log after.state.log do + match signed[signature]? with + | none => signed := signed.insert signature (group.node, behind) + | some (other, entries) => + unless entries == behind do + throw + s!"{group.label}: nodes '{other}' and '{group.node}' hold different entries behind the signature at index {signature.1} of term {signature.2}" + replay := after + ran := ran + 1 + | .error (.incomplete reason) => + unless lenient && group.final do + throw reason + break + | .error (.mismatch reason) => throw reason + next := next.push ran let instructions := queues.zipIdx.flatMap fun (groups, queue) => (groups.extract 0 next[queue]!).flatMap (·.instructions) + let mut sent : Std.HashMap (String × String × Packet) Nat := {} + for group in queues.flatten do + for instruction in group.instructions do + if let .observeSends sends _ := instruction then + for send in sends do + sent := + sent.alter (group.node, send.target, send.packet) fun n => some (n.getD 0 + 1) + let mut unsent := 0 + for instruction in instructions do + if let .action (.receive source destination packet _) origin := instruction then + let key := (source, destination, packet) + if sent.getD key 0 > 0 then + sent := sent.modify key (· - 1) + else if lenient then + unsent := unsent + 1 + else + throw s!"{origin.label}: no node traced sending {render packet} from '{source}'" let actions := (instructions.filter (· matches .action ..)).size - return { ran := next, actions, observations := instructions.size - actions } + return { ran := next, actions, observations := instructions.size - actions, unsent } end Consensus.Replay diff --git a/lean/consensus/Consensus/Replay/Reduction.lean b/lean/consensus/Consensus/Replay/Reduction.lean index 948836d3714..54fdff1ed95 100644 --- a/lean/consensus/Consensus/Replay/Reduction.lean +++ b/lean/consensus/Consensus/Replay/Reduction.lean @@ -371,7 +371,7 @@ private def ruleNomination : Reduction Unit := do emitAction head "nomination" (.local head.node .nominateSuccessor) emitObserveSends head (← extractSends start) -/-- Dropped packets stay queued in the model network, never delivered. -/ +/-- The node drops packets it had yet to send, which no rule observes. -/ private def ruleDrop : Reduction Unit := do let head ← peek -- consume diff --git a/lean/consensus/Consensus/Replay/Trace.lean b/lean/consensus/Consensus/Replay/Trace.lean index 3008ffc42fe..06c92d1eff9 100644 --- a/lean/consensus/Consensus/Replay/Trace.lean +++ b/lean/consensus/Consensus/Replay/Trace.lean @@ -69,7 +69,7 @@ msgpack_struct! deriving instance Inhabited for StateSnapshot deriving instance - DecidableEq, Repr + DecidableEq, Hashable, Repr for Packet.AppendEntries, Packet.AppendEntriesResponse, Packet.RequestVote, Packet.RequestVoteResponse, Packet.ProposeRequestVote @@ -82,7 +82,7 @@ inductive Packet where | requestVoteResponse (packet : Packet.RequestVoteResponse) | requestPreVoteResponse (packet : Packet.RequestVoteResponse) | proposeRequestVote (packet : Packet.ProposeRequestVote) -deriving DecidableEq, Repr +deriving DecidableEq, Hashable, Repr /-- The packet's `msg`. -/ def Packet.msg : Packet → String diff --git a/lean/consensus/Consensus/Tests/ReplayDelivery.lean b/lean/consensus/Consensus/Tests/ReplayDelivery.lean deleted file mode 100644 index a04d4ae58d1..00000000000 --- a/lean/consensus/Consensus/Tests/ReplayDelivery.lean +++ /dev/null @@ -1,71 +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 - } - } - -/-- Node 1 receives the packet of `appendEntries`, tracing that it applied `applied`. -/ -private def receive (network : List Envelope) (applied : List ReqID := [1]) - : Except String ReplayState := - runInstruction header { state := { header.initial with network } } - (.action - (.receive "0" "1" (Packet.ofMessage (appendEntries 1).payload) - (applied.map - fun request => (1, { term := 2, content := .transaction request {} }))) - default) - -/-- Checks delivery selection by rendered packet and by the entries the receiver applied. -/ -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 - | .ok replay => - unless !replay.state.network.contains (appendEntries 1) do - throw (IO.userError "different entries: the applied entry must select the packet") - | .error error => throw (IO.userError s!"different entries: {error}") - match receive [appendEntries 2] with - | .error error => - unless error.startsWith "no matching packet" do - throw (IO.userError s!"entry not sent: unexpected error {error}") - | .ok _ => throw (IO.userError "entry not sent: delivery must fail") - match receive [appendEntries 1] (applied := []) with - | .error error => - unless error.startsWith "the model applied" do - throw (IO.userError s!"entry not traced: unexpected error {error}") - | .ok _ => throw (IO.userError "entry not traced: delivery must fail") - IO.println "Replay delivery checks passed." - -#eval run - -end Consensus.Tests.ReplayDelivery diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 3d5ddb73138..4ef46b8581c 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -57,38 +57,65 @@ A native `replicate` event and the entries that follow it, each starting with it A `replicate` call rejected at its first entry traces no entries and appends nothing. Snapshot installation runs its `add_configuration` and `retired_committed_tx` hooks outside the lock, before the node's `init_as_backup`; the hooks form no group, so the initialization's group starts at `init_as_backup` and groups that fall between them, such as ticks of any node, replay as usual. -Replay repeatedly runs the next group of some node, with no other group's actions between its actions. -It runs the enabled group with the earliest `ts`, the wall-clock emission time in nanoseconds that a record may carry; without it `m_ts` stands in, which is the order of execution within a process and otherwise only makes diagnostics reproducible, as counters of different processes are not comparable. -A group whose first action is a receive waits until a matching packet is queued, and one whose first action is `init_as_backup` waits until some node has committed a signature at the snapshot's seqno, in its view; other actions must be enabled when their group runs. -Clocks of different hosts therefore only choose among enabled groups, and cannot fail a trace. -If groups remain but none may run, replay fails, listing first the groups that can never run, such as a receive whose packet is never sent. -`--schedule` prints the groups in the order they ran, ending with any that failed. -`--lenient` accepts a trace that is incomplete, for example because a node was killed before it sent its last events: a node's groups end before its first event that no rule consumes, and replay ends once no group may run. -The reported `watermark` is then the least fraction of a node's events that replay consumed; a group that the model disagrees with still fails the trace. After bootstrap, each group emits one read-only observation before its model actions, comparing the native group's entry snapshot with the current model state. A tick with no action emits no group, so its snapshot is not compared: the node's next group compares the state it starts from. A trace may so have no group at all. -A receive delivers any queued model envelope from its sender whose rendered packet has exactly the native packet's fields, with equal values. -A packet omits the entries of an AppendEntries, so the receiver's `execute_append_entries_sync` events constrain them: each traces the view, seqno and signature flag of an entry the node applied, and the ledger hooks which follow it trace the entry's retirements and configuration. -The delivered envelope must carry those entries, and the model must apply exactly those, so a trace fails if a node applies an entry which differs from the one sent, or one more or fewer than the model. -A transaction's request is named by its seqno, as neither node traces it. -Replay delivers the queued **model payload**, not reconstructing unrecorded native bytes; if matching envelopes still differ in payload, replay fails with an ambiguous delivery. -An `init_as_backup` copies the committed prefix of a node, which must agree with what the joiner traces of its snapshot: the term of every entry, from the term history (`th`, the first seqno of each view), and, from the hooks which ran before it, the configuration in force and the retirements. -A snapshot traces neither a configuration which a later one replaced, nor which of its earlier entries are signatures. -A term history which is out of order or starts a view after the snapshot fails the trace, as does a hook after the snapshot. -An envelope that is never delivered stays queued, which models loss, so `drop_pending_to` emits no observation or action. +A receive gives the node the message that its own events describe, whose rendered packet has exactly the native packet's fields, with equal values. +Nothing is delivered for a `drop_pending_to`, so it 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. +## Per-node validation + +Replay validates each node alone, in three steps. + +1. **Reduce:** the rules turn one node's events into its groups, up to the first event that no rule reads. +2. **Validate:** [`validate`](../Consensus/Replay/Interpreter.lean) runs the node's groups on `Node.step` from its initial state, comparing the boundary snapshots and the multiset of sends, up to the first group that does not validate. +3. **Report:** `watermark` is the minimum over nodes of the fraction of the node's events that are both reduced and validated. + +No step reads another node's state; the [cross-node checks](#cross-node-checks) then compare what the nodes observed. + +`consensus-replay TRACE.msgpack` requires every event to reduce and every group to validate. +`--lenient` is for a capture that was cut short, which CI may not assume complete. +Reduction then ends at the first event that no rule reads, whatever the reason, as it did before. +Validation ends before a node's last group if that group is incomplete: the model sent a packet which the trace does not show. +A group which contradicts the model, by a snapshot, a disabled action, a send the model did not make or an entry it did not apply, is an error in either mode. + +A node's own events give every input of its model: + +- **Receive:** votes, responses and empty heartbeats are fully determined by the packet. A packet omits the entries of a nonempty AppendEntries, so they are those the node holds, then those it traced applying: each `execute_append_entries_sync` gives the view, seqno and signature flag of one, and the hooks that follow give its configuration and retirements. An entry the node rejected unread is a placeholder, which the model must not apply. +- **Join:** `init_as_backup` gives the snapshot's seqno, view and term history, the first seqno of each view, and the hooks before it give the snapshot's configurations and retirements. The node's log is built from these: each entry's term, and the signature that ends it. Which earlier entries were signatures is not traced, and the node does not depend on it. + +Replay uses `seqno - 1` as the model's request ID of a transaction, so every node names an entry alike without coordination. + +## Cross-node checks + +After the nodes validate alone, `validate` checks them against each other. + +- **Every receive has a send:** the packets that nodes received must be among the packets that their sources traced sending, as a multiset of source, destination and packet. A packet that was sent need not be received. A node's trace can end before its last sends, which other nodes still receive, so with `--lenient` a receive with no send is not an error: the result counts such receives as `unsent`, which is 0 otherwise. +- **Logs behind signatures align:** nodes that hold the same signature, by index and term, must hold the same entries behind it, back to the signature before: term, signature flag, configuration and retirements. Signature by signature, they so hold the same log up to it. This compares what each node observed whenever its log gained a signature, so it is an error with `--lenient` too. A snapshot's entries are inferred rather than observed, so they are not compared; the signatures the joiner applies afterwards are. + +The e2e test infrastructure knows when a capture is not cut short: a node that exits cleanly logs how many events each of its trace sinks dropped, and a killed node logs nothing. +If every node of a network reports none for the capture's sink, [`network.py`](../../../tests/infra/network.py) ends the capture with a `capture.complete` record, which replay skips like any record of another tag. +[`cft_trace_validation.py`](../../../tests/cft_trace_validation.py) still replays every capture with `--lenient`, and fails a complete one whose `unsent` is not 0. + +Packets are paired by their fields alone: `m_ts` orders one process only and `ts` is subject to clock skew, so replay does not check that a send precedes its receive. +Nodes do not yet trace the Merkle root that a signature signs, so the alignment check compares the model's entries, not the ledger's. + +[`check-per-node.py`](check-per-node.py) checks exact watermarks for captures cut short, that a capture altered elsewhere is an error, and that the cross-node checks reject a receive with no send and logs that differ behind a signature. + +```sh +python3 replay/check-per-node.py .lake/build/bin/consensus-replay +``` + ## Source and checks - [`Trace.lean`](../Consensus/Replay/Trace.lean): the types of trace records, each declared with the reader of its MessagePack map. - [`Input.lean`](../Consensus/Replay/Input.lean): read events, order and split them into per-node streams and collect identities. - [`Reduction.lean`](../Consensus/Replay/Reduction.lean): named rules, each reducing one lock hold of a node, explicit boundaries and rule-tagged snapshot checks. - [`Groups.lean`](../Consensus/Replay/Groups.lean): runs the rules over each node's stream, taking each rule's instructions as a group. -- [`Interpreter.lean`](../Consensus/Replay/Interpreter.lean): boundary-state field comparisons, packet selection, send checks, group scheduling and model execution. +- [`Interpreter.lean`](../Consensus/Replay/Interpreter.lean): instructions and groups, and the validation of each node's groups on the model of that node, then of the nodes against each other. - [`ReplayMain.lean`](ReplayMain.lean): single-trace validation CLI. -- [`ReplayDelivery.lean`](../Consensus/Tests/ReplayDelivery.lean): delivery selection by rendered packet and by the entries the receiver applied. - [`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. diff --git a/lean/consensus/replay/ReplayMain.lean b/lean/consensus/replay/ReplayMain.lean index b968ace3e7d..80daed7c150 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -17,28 +17,16 @@ def main (args : List String) : IO UInt32 := do let (flags, paths) := args.partition (·.startsWith "--") match flags.eraseDups, paths with | flags, [path] => - unless flags.all (["--schedule", "--lenient"].contains ·) do + unless flags.all (· == "--lenient") do IO.eprintln s!"unknown option {flags}" return 2 let lenient := flags.contains "--lenient" let records ← readLog path - let reduced := do + let result := do let (streams, declared) ← prepareEvents (← records) - reduce streams declared lenient - let (result, ran) := - match reduced with - | .error error => (Except.error error, #[]) - | .ok reduced => - let (result, ran) := - (schedule reduced.header reduced.queues lenient).run.run #[] - ( - result.map - fun (result : Result) => (reduced.watermark result.ran, result), - ran - ) - if flags.contains "--schedule" then - for group in ran do - IO.eprintln s!"{group.ts.getD group.m_ts} node '{group.node}' {group.label}" + let reduced ← reduce streams declared lenient + let result ← validate reduced.header reduced.queues lenient + return (reduced.watermark result.ran, result) match result with | .error error => IO.eprintln s!"{path}: {error}"; return 1 | .ok (watermark, result) => @@ -49,13 +37,13 @@ def main (args : List String) : IO UInt32 := do ("watermark", toJson watermark), ("groups", toJson result.ran.sum), ("actions", toJson result.actions), - ("observations", toJson result.observations) + ("observations", toJson result.observations), + ("unsent", toJson result.unsent) ] IO.println result.compress return 0 | _, _ => - IO.eprintln "usage: consensus-replay [--schedule] [--lenient] TRACE.msgpack"; - return 2 + IO.eprintln "usage: consensus-replay [--lenient] TRACE.msgpack"; return 2 catch error => IO.eprintln s!"{error}" return 1 diff --git a/lean/consensus/replay/check-per-node.py b/lean/consensus/replay/check-per-node.py new file mode 100755 index 00000000000..bbc263f6bfe --- /dev/null +++ b/lean/consensus/replay/check-per-node.py @@ -0,0 +1,114 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Check what replay accepts of a capture which was cut short, and of one altered.""" + +import copy +import json +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main(executable): + here = Path(__file__).resolve().parent + fixtures = here / "fixtures" + pack = here.parents[2] / "scripts" / "pack-trace.py" + with tempfile.TemporaryDirectory() as tmp: + trace = Path(tmp) / "trace.msgpack" + + def write(raw): + with trace.open("wb") as stream: + subprocess.run( + [sys.executable, pack], input=raw, stdout=stream, check=True + ) + + def replay(raw, *args, error=False): + write(raw) + proc = subprocess.run( + [executable, *args, trace], text=True, capture_output=True, check=False + ) + if proc.returncode != int(error): + raise RuntimeError( + f"{args}: {proc.returncode}: {proc.stdout}{proc.stderr}" + ) + return proc.stderr if error else json.loads(proc.stdout) + + history = [ + json.loads(line) + for line in (fixtures / "valid" / "replication.ndjson") + .read_bytes() + .splitlines() + ] + + def raw(records, *more): + return b"\n".join(json.dumps(r).encode() for r in [*records, *more]) + + def without(*m_ts): + return [r for r in history if r["m_ts"] not in m_ts] + + def altered(m_ts, **fields): + records = copy.deepcopy(history) + next(r for r in records if r["m_ts"] == m_ts)["msg"].update(fields) + return records + + # A later event of the follower, after which its last group is not final. + later = copy.deepcopy(next(r for r in history if r["m_ts"] == 15)) + later["m_ts"] = 99 + + # A node validates alone, but its receive needs a send of the leader, unless + # the leader's trace may have ended before it. + assert "no node traced sending" in replay(raw(without(21, 22)), error=True) + unsent = replay(raw(without(21, 22)), "--lenient") + assert (unsent["watermark"], unsent["unsent"]) == (1, 1), unsent + # It holds the entries of a packet it receives again, so traces applying none. + again = copy.deepcopy([r for r in history if r["m_ts"] in (23, 27)]) + for record, m_ts in zip(again, (30, 31)): + record["m_ts"] = m_ts + again[0]["msg"]["st"].update(li=4, ci=2) + # The leader sent the packet once. + replay(raw(history, *again), error=True) + assert replay(raw(history, *again), "--lenient")["watermark"] == 1 + # The follower applies another configuration than the leader appended, behind + # the signature which both hold: an error wherever the capture ends. + nodes = {"0": {}, "1": {}, "2": {}} + for args in [(), ("--lenient",)]: + assert "different entries behind the signature at index 4" in replay( + raw(altered(25, nds=nodes)), *args, error=True + ) + + # The capture ends before the follower's last send: the group earns no credit. + replay(raw(without(27)), error=True) + cut = replay(raw(without(27)), "--lenient") + assert (cut["groups"], cut["watermark"]) == (8, 6 / 10), cut + # Nor does a group whose last entry the follower had yet to trace. + assert round(replay(raw(history[:26]), "--lenient")["watermark"], 5) == 0.66667 + # A join which ends inside its rule is not reduced. + assert round(replay(raw(history[:17]), "--lenient")["watermark"], 5) == 0.66667 + # Only a final group may be incomplete. + replay(raw(without(27), later), "--lenient", error=True) + # Its response shows that the follower was past an entry it did not trace. + assert "did not trace" in replay(raw(without(26)), "--lenient", error=True) + + # What the trace does show must agree with the model, wherever it is. + for records in [ + without(24, 25, 27), # an entry applied after a gap + altered(24, vw=3), # in another view than its packet + ]: + assert "do not follow" in replay(raw(records), "--lenient", error=True) + # Reduction ends at an event which no rule reads, and must not unless lenient. + for records, reason in [ + (altered(24, frm="1"), "expected an entry from 0"), + (altered(16, vw=7), "another view"), # than the snapshot's history gives + (altered(16, th=[2, 1]), "out of order"), + (altered(14, idx=99), "outside the snapshot"), + (altered(16, th=[1, 1, 99]), "outside the snapshot"), + ]: + assert reason in replay(raw(records), error=True), reason + assert replay(raw(records), "--lenient")["watermark"] < 1 + print("Per-node replay checks passed.") + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/lean/consensus/replay/fixtures/README.md b/lean/consensus/replay/fixtures/README.md index 9868848b7e5..b1b1cbbea0f 100644 --- a/lean/consensus/replay/fixtures/README.md +++ b/lean/consensus/replay/fixtures/README.md @@ -10,28 +10,23 @@ The [rejected replicate](valid/rejected-replicate.ndjson) control is a `replicat The [bootstrap](valid/bootstrap.ndjson) control starts like a real node: a bare tick and a nomination before genesis, then a flush of the genesis entry. The [interleaved](valid/interleaved.ndjson) control records the replication history with each node in a process of its own, `ts` in the order of the lines and the joiner's events among the leader's, as clock skew would place them: its initialization inside the leader's signature batch, before the leader commits, its receives before their sends, and a whole receive group, including its own `add_configuration`, between the leader's `add_configuration` and its send. -| Fixture | Expected failure | -| --------------------------------------------------------------------------------- | --------------------------------------------------------- | -| [Snapshot mismatch](invalid/snapshot-mismatch.ndjson) | Observed view differs from the model | -| [Unsupported snapshot field](invalid/unsupported-snapshot-field.ndjson) | Unknown key in a `st` (state) | -| [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 | -| [Snapshot term history mismatch](invalid/snapshot-term-history-mismatch.ndjson) | Joiner's term history differs from the committed prefix | -| [Snapshot term history outside](invalid/snapshot-term-history-outside.ndjson) | Joiner's term history starts a view after the snapshot | -| [Snapshot configuration mismatch](invalid/snapshot-configuration-mismatch.ndjson) | Joiner's snapshot hook traces another configuration | -| [Applied signature mismatch](invalid/applied-signature-mismatch.ndjson) | Follower applies a transaction where a signature was sent | -| [Applied configuration mismatch](invalid/applied-configuration-mismatch.ndjson) | Follower applies another configuration than was sent | -| [Bootstrap event](invalid/bootstrap-event.ndjson) | Event other than a tick or nomination before genesis | -| [Bootstrap flush send](invalid/bootstrap-flush-send.ndjson) | Send from the genesis flush, which must send nothing | +| Fixture | Expected failure | +| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | +| [Snapshot mismatch](invalid/snapshot-mismatch.ndjson) | Observed view differs from the model | +| [Unsupported snapshot field](invalid/unsupported-snapshot-field.ndjson) | Unknown key in a `st` (state) | +| [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) | Vote request with no traced response | +| [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` | +| [Bootstrap event](invalid/bootstrap-event.ndjson) | Event other than a tick or nomination before genesis | +| [Bootstrap flush send](invalid/bootstrap-flush-send.ndjson) | Send from the genesis flush, which must send nothing | +| [Snapshot term history outside](invalid/snapshot-term-history-outside.ndjson) | Joiner's term history starts a view after the snapshot | +| [Applied configuration mismatch](invalid/applied-configuration-mismatch.ndjson) | Follower applies another configuration than the leader appended, behind a signature both hold | From `lean/consensus`, inspect a failure directly (exit status 1 is expected). Packing needs Python `msgpack`: diff --git a/lean/consensus/replay/fixtures/invalid/applied-signature-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/applied-signature-mismatch.ndjson deleted file mode 100644 index 7d3d43b0da3..00000000000 --- a/lean/consensus/replay/fixtures/invalid/applied-signature-mismatch.ndjson +++ /dev/null @@ -1,30 +0,0 @@ -{"pid":"driver","m_ts":0,"msg":{"fn":"become_leader","st":{"id":"0"}}} -{"pid":"driver","m_ts":1,"msg":{"fn":"replicate","st":{"id":"0"}}} -{"pid":"driver","m_ts":2,"msg":{"fn":"replicate_entry","st":{"id":"0"},"gc":false}} -{"pid":"driver","m_ts":3,"msg":{"fn":"add_configuration","st":{"id":"0"},"nds":{"0":{}}}} -{"pid":"driver","m_ts":4,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"}}} -{"pid":"driver","m_ts":5,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"},"sn":2,"gc":true}} -{"pid":"driver","m_ts":6,"msg":{"fn":"commit","st":{"id":"0"},"idx":2}} -{"pid":"driver","m_ts":7,"msg":{"cmd":"trust_nodes,2,1"}} -{"pid":"driver","m_ts":8,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":9,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"},"sn":3,"gc":false}} -{"pid":"driver","m_ts":10,"msg":{"fn":"add_configuration","st":{"id":"0"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":11,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":12,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":13,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"},"sn":4,"gc":true}} -{"pid":"driver","m_ts":14,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":2,"nds":{"0":{}}}} -{"pid":"driver","m_ts":15,"msg":{"fn":"tick","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"}}} -{"pid":"driver","m_ts":16,"msg":{"fn":"init_as_backup","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"},"sn":2,"vw":2,"th":[1,1]}} -{"pid":"driver","m_ts":17,"msg":{"fn":"become_follower","st":{"id":"1"}}} -{"pid":"driver","m_ts":18,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":19,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":20,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":21,"msg":{"fn":"tick","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":22,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":23,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":24,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":3,"gc":false}} -{"pid":"driver","m_ts":25,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":26,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":4,"gc":false}} -{"pid":"driver","m_ts":27,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":28,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":29,"msg":{"fn":"commit","st":{"id":"0"},"idx":4}} diff --git a/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson deleted file mode 100644 index 828ef1b176c..00000000000 --- a/lean/consensus/replay/fixtures/invalid/packet-mismatch.ndjson +++ /dev/null @@ -1,24 +0,0 @@ -{"pid":"driver","m_ts":0,"msg":{"fn":"become_leader","st":{"id":"0"}}} -{"pid":"driver","m_ts":1,"msg":{"fn":"replicate","st":{"id":"0"}}} -{"pid":"driver","m_ts":2,"msg":{"fn":"replicate_entry","st":{"id":"0"},"gc":false}} -{"pid":"driver","m_ts":3,"msg":{"fn":"add_configuration","st":{"id":"0"},"nds":{"0":{}}}} -{"pid":"driver","m_ts":4,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"}}} -{"pid":"driver","m_ts":5,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"},"sn":2,"gc":true}} -{"pid":"driver","m_ts":6,"msg":{"fn":"commit","st":{"id":"0"},"idx":2}} -{"pid":"driver","m_ts":7,"msg":{"cmd":"trust_nodes,2,1"}} -{"pid":"driver","m_ts":8,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":9,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"},"sn":3,"gc":false}} -{"pid":"driver","m_ts":10,"msg":{"fn":"add_configuration","st":{"id":"0"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":11,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":12,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":13,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"},"sn":4,"gc":true}} -{"pid":"driver","m_ts":14,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":2,"nds":{"0":{}}}} -{"pid":"driver","m_ts":15,"msg":{"fn":"tick","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"}}} -{"pid":"driver","m_ts":16,"msg":{"fn":"init_as_backup","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"},"sn":2,"vw":2,"th":[1,1]}} -{"pid":"driver","m_ts":17,"msg":{"fn":"become_follower","st":{"id":"1"}}} -{"pid":"driver","m_ts":18,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":19,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":20,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":21,"msg":{"fn":"tick","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":22,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":23,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":999,"lci":2,"toi":2,"cnv":false}}} diff --git a/lean/consensus/replay/fixtures/invalid/snapshot-configuration-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/snapshot-configuration-mismatch.ndjson deleted file mode 100644 index d4f67c69cbb..00000000000 --- a/lean/consensus/replay/fixtures/invalid/snapshot-configuration-mismatch.ndjson +++ /dev/null @@ -1,30 +0,0 @@ -{"pid":"driver","m_ts":0,"msg":{"fn":"become_leader","st":{"id":"0"}}} -{"pid":"driver","m_ts":1,"msg":{"fn":"replicate","st":{"id":"0"}}} -{"pid":"driver","m_ts":2,"msg":{"fn":"replicate_entry","st":{"id":"0"},"gc":false}} -{"pid":"driver","m_ts":3,"msg":{"fn":"add_configuration","st":{"id":"0"},"nds":{"0":{}}}} -{"pid":"driver","m_ts":4,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"}}} -{"pid":"driver","m_ts":5,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"},"sn":2,"gc":true}} -{"pid":"driver","m_ts":6,"msg":{"fn":"commit","st":{"id":"0"},"idx":2}} -{"pid":"driver","m_ts":7,"msg":{"cmd":"trust_nodes,2,1"}} -{"pid":"driver","m_ts":8,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":9,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"},"sn":3,"gc":false}} -{"pid":"driver","m_ts":10,"msg":{"fn":"add_configuration","st":{"id":"0"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":11,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":12,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":13,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"},"sn":4,"gc":true}} -{"pid":"driver","m_ts":14,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":2,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":15,"msg":{"fn":"tick","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"}}} -{"pid":"driver","m_ts":16,"msg":{"fn":"init_as_backup","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"},"sn":2,"vw":2,"th":[1,1]}} -{"pid":"driver","m_ts":17,"msg":{"fn":"become_follower","st":{"id":"1"}}} -{"pid":"driver","m_ts":18,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":19,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":20,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":21,"msg":{"fn":"tick","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":22,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":23,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":24,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":3,"gc":false}} -{"pid":"driver","m_ts":25,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":26,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":4,"gc":true}} -{"pid":"driver","m_ts":27,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":28,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":29,"msg":{"fn":"commit","st":{"id":"0"},"idx":4}} diff --git a/lean/consensus/replay/fixtures/invalid/snapshot-term-history-mismatch.ndjson b/lean/consensus/replay/fixtures/invalid/snapshot-term-history-mismatch.ndjson deleted file mode 100644 index c9f98a74cde..00000000000 --- a/lean/consensus/replay/fixtures/invalid/snapshot-term-history-mismatch.ndjson +++ /dev/null @@ -1,30 +0,0 @@ -{"pid":"driver","m_ts":0,"msg":{"fn":"become_leader","st":{"id":"0"}}} -{"pid":"driver","m_ts":1,"msg":{"fn":"replicate","st":{"id":"0"}}} -{"pid":"driver","m_ts":2,"msg":{"fn":"replicate_entry","st":{"id":"0"},"gc":false}} -{"pid":"driver","m_ts":3,"msg":{"fn":"add_configuration","st":{"id":"0"},"nds":{"0":{}}}} -{"pid":"driver","m_ts":4,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"}}} -{"pid":"driver","m_ts":5,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"},"sn":2,"gc":true}} -{"pid":"driver","m_ts":6,"msg":{"fn":"commit","st":{"id":"0"},"idx":2}} -{"pid":"driver","m_ts":7,"msg":{"cmd":"trust_nodes,2,1"}} -{"pid":"driver","m_ts":8,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":9,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"},"sn":3,"gc":false}} -{"pid":"driver","m_ts":10,"msg":{"fn":"add_configuration","st":{"id":"0"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":11,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":12,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":13,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"},"sn":4,"gc":true}} -{"pid":"driver","m_ts":14,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":2,"nds":{"0":{}}}} -{"pid":"driver","m_ts":15,"msg":{"fn":"tick","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"}}} -{"pid":"driver","m_ts":16,"msg":{"fn":"init_as_backup","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"},"sn":2,"vw":2,"th":[1,2]}} -{"pid":"driver","m_ts":17,"msg":{"fn":"become_follower","st":{"id":"1"}}} -{"pid":"driver","m_ts":18,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":19,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":20,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":2}}} -{"pid":"driver","m_ts":21,"msg":{"fn":"tick","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":22,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":23,"msg":{"fn":"recv_append_entries","st":{"id":"1","vw":2,"li":2,"ci":2,"ls":"Follower"},"frm":"0","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":4,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":24,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":3,"gc":false}} -{"pid":"driver","m_ts":25,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":26,"msg":{"fn":"execute_append_entries_sync","st":{"id":"1"},"frm":"0","vw":2,"sn":4,"gc":true}} -{"pid":"driver","m_ts":27,"msg":{"fn":"send_append_entries_response","st":{"id":"1"},"to":"0","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":28,"msg":{"fn":"recv_append_entries_response","st":{"id":"0","vw":2,"li":4,"ci":2,"ls":"Leader"},"frm":"1","pkt":{"msg":"append_entries_response","tm":2,"ok":"OK","lli":4}}} -{"pid":"driver","m_ts":29,"msg":{"fn":"commit","st":{"id":"0"},"idx":4}} 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 3302fa157bc..00000000000 --- a/lean/consensus/replay/fixtures/invalid/uncommitted-snapshot.ndjson +++ /dev/null @@ -1,18 +0,0 @@ -{"pid":"driver","m_ts":0,"msg":{"fn":"become_leader","st":{"id":"0"}}} -{"pid":"driver","m_ts":1,"msg":{"fn":"replicate","st":{"id":"0"}}} -{"pid":"driver","m_ts":2,"msg":{"fn":"replicate_entry","st":{"id":"0"},"gc":false}} -{"pid":"driver","m_ts":3,"msg":{"fn":"add_configuration","st":{"id":"0"},"nds":{"0":{}}}} -{"pid":"driver","m_ts":4,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"}}} -{"pid":"driver","m_ts":5,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":1,"ci":0,"ls":"Leader"},"sn":2,"gc":true}} -{"pid":"driver","m_ts":6,"msg":{"fn":"commit","st":{"id":"0"},"idx":2}} -{"pid":"driver","m_ts":7,"msg":{"cmd":"trust_nodes,2,1"}} -{"pid":"driver","m_ts":8,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":9,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":2,"ci":2,"ls":"Leader"},"sn":3,"gc":false}} -{"pid":"driver","m_ts":10,"msg":{"fn":"add_configuration","st":{"id":"0"},"idx":3,"nds":{"0":{},"1":{}}}} -{"pid":"driver","m_ts":11,"msg":{"fn":"send_append_entries","st":{"id":"0"},"to":"1","pkt":{"msg":"append_entries","tm":2,"pi":2,"pt":2,"idx":2,"lci":2,"toi":2,"cnv":false}}} -{"pid":"driver","m_ts":12,"msg":{"fn":"replicate","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"}}} -{"pid":"driver","m_ts":13,"msg":{"fn":"replicate_entry","st":{"id":"0","vw":2,"li":3,"ci":2,"ls":"Leader"},"sn":4,"gc":true}} -{"pid":"driver","m_ts":14,"msg":{"fn":"add_configuration","st":{"id":"1"},"idx":2,"nds":{"0":{}}}} -{"pid":"driver","m_ts":15,"msg":{"fn":"tick","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"}}} -{"pid":"driver","m_ts":16,"msg":{"fn":"init_as_backup","st":{"id":"1","vw":0,"li":0,"ci":0,"ls":"None"},"sn":4,"vw":2,"th":[1,1]}} -{"pid":"driver","m_ts":17,"msg":{"fn":"become_follower","st":{"id":"1"}}} diff --git a/tests/cft_trace_validation.py b/tests/cft_trace_validation.py index 9d403bbb048..9df9f2378d8 100755 --- a/tests/cft_trace_validation.py +++ b/tests/cft_trace_validation.py @@ -7,10 +7,12 @@ usage: cft_trace_validation.py CONSENSUS_REPLAY DIRECTORY... A capture may be incomplete, for example if a node was killed, so replay need -not consume every event. Fails if the model disagrees with a capture, if replay -consumes less than WATERMARK of the events of one of its nodes, or if there is -no capture to replay. Captures without ccf.cft events, as of a network whose -first node did not start, are not replayed. +not validate every event. Fails if the model disagrees with a capture, if replay +validates less than WATERMARK of the events of one of its nodes, or if there is +no capture to replay. The test infrastructure marks a capture complete if every +node exited having sent all of its events: such a capture also fails if a node +received a packet which no node traced sending. Captures without ccf.cft +events, as of a network whose first node did not start, are not replayed. """ import concurrent.futures @@ -24,20 +26,26 @@ import msgpack WATERMARK = 0.9 +# As infra.network.TRACE_COMPLETE, which ends a complete capture. +COMPLETE = msgpack.packb(["capture.complete", None, {}]) def replay(replayer, path): - """Whether the capture is accepted, and the replayer's output.""" + """The least validated fraction of a node's events, if replay accepts the + capture, and the replayer's output.""" result = subprocess.run( [replayer, "--lenient", str(path)], capture_output=True, text=True, check=False, ) - accepted = ( - result.returncode == 0 and json.loads(result.stdout)["watermark"] >= WATERMARK - ) - return accepted, (result.stdout + result.stderr).strip() + output = (result.stdout + result.stderr).strip() + if result.returncode != 0: + return None, output + report = json.loads(result.stdout) + if report["unsent"] and path.read_bytes().endswith(COMPLETE): + return None, f"{output}: a complete capture has receives with no send" + return report["watermark"], output def has_cft_events(path): @@ -57,10 +65,14 @@ def main(replayer, *directories): with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as pool: results = list(pool.map(functools.partial(replay, replayer), paths)) rejected = 0 - for path, (accepted, output) in zip(paths, results, strict=True): + for path, (watermark, output) in zip(paths, results, strict=True): + accepted = watermark is not None and watermark >= WATERMARK rejected += not accepted print(f"{'OK ' if accepted else 'FAIL'} {path}: {output}") print(f"{len(paths) - rejected} accepted, {rejected} rejected") + watermarks = [w for w, _ in results if w is not None] + if watermarks: + print(f"Minimum validated watermark: {min(watermarks):.2%}") return 0 if paths and not rejected else 1 diff --git a/tests/infra/network.py b/tests/infra/network.py index b4815227471..487273cde5c 100644 --- a/tests/infra/network.py +++ b/tests/infra/network.py @@ -36,6 +36,7 @@ import infra.path import infra.proc import infra.remote +import msgpack from infra.clients import CCFConnectionException, CCFIOException, flush_info from infra.consortium import slurp_file from infra.node import CCFVersion @@ -52,6 +53,21 @@ _cleared_trace_folders = set() # More than any test network configures. TRACE_MAX_NODES = 256 +# Ends a capture to which every node sent all of its events. +TRACE_COMPLETE = msgpack.packb(["capture.complete", None, {}]) + + +def _sent_all_events(node): + """Whether the node exited cleanly, dropping no event of its last + trace sink, which is the capture's. A killed node logs no report.""" + out, _ = node.get_logs() + if out is None or not os.path.isfile(out): + return False + with open(out, encoding="utf-8", errors="replace") as log: + reports = re.findall( + r"Fluentd exporter shutdown: (\d+) dropped events", log.read() + ) + return bool(reports) and reports[-1] == "0" class NodeRole(Enum): @@ -398,6 +414,7 @@ def _add_trace_sink(self, node, args, node_args, recovery=False): shutil.rmtree(folder, ignore_errors=True) os.makedirs(folder, exist_ok=True) self.trace = ExitStack() + self.trace_nodes = [] # Networks that share a label each get a capture. for index in itertools.count(): self.trace_path = os.path.join(folder, f"{index}.msgpack") @@ -422,10 +439,12 @@ def _add_trace_sink(self, node, args, node_args, recovery=False): {**self.trace_endpoint, "tag-prefix-allow-list": [""]} ) node_args["observability"] = observability + self.trace_nodes.append(node) def _finish_trace(self): """Stop recording trace events, if started, and keep the capture - unless the collector failed.""" + unless the collector failed, marking it complete if every node sent + all of its events.""" trace, self.trace = self.trace, None if trace is None: return @@ -435,6 +454,9 @@ def _finish_trace(self): os.remove(self.trace_path) LOG.info(f"Discarded trace capture: {error}") else: + if all(_sent_all_events(node) for node in self.trace_nodes): + with open(self.trace_path, "ab") as output: + output.write(TRACE_COMPLETE) LOG.info(f"Trace capture in {self.trace_path}") def _setup_node(