From 1d533d4c4e403a0d0664a445a9590c425c7cf176 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Fri, 4 Dec 2026 15:30:17 +0000 Subject: [PATCH] Add single-node consensus trace validation mode Keep complete mode (the global scheduler) as the default and add --mode=single-node (with optional --node=NODE) to reduce and validate nodes independently on Consensus.Model.Node.step without modeling the network. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../single-node-consensus-replay.added.md | 1 + .github/workflows/lean-package.yml | 4 + lean/consensus/Consensus/Replay/Groups.lean | 44 +++- lean/consensus/Consensus/Replay/Input.lean | 2 + .../Consensus/Replay/Interpreter.lean | 229 +++++++++++++++--- lean/consensus/replay/README.md | 18 +- lean/consensus/replay/ReplayMain.lean | 78 ++++-- lean/consensus/replay/check-single-node.py | 162 +++++++++++++ 8 files changed, 478 insertions(+), 60 deletions(-) create mode 100644 .changes/single-node-consensus-replay.added.md create mode 100755 lean/consensus/replay/check-single-node.py diff --git a/.changes/single-node-consensus-replay.added.md b/.changes/single-node-consensus-replay.added.md new file mode 100644 index 00000000000..dbbbf15835a --- /dev/null +++ b/.changes/single-node-consensus-replay.added.md @@ -0,0 +1 @@ +The [consensus trace replayer](lean/consensus/replay/README.md#single-node-validation) now supports `--mode=single-node` (with optional `--node=NODE`) to validate nodes independently on `Consensus.Model.Node.step` without modeling the network. diff --git a/.github/workflows/lean-package.yml b/.github/workflows/lean-package.yml index e5866886a31..963b28eb315 100644 --- a/.github/workflows/lean-package.yml +++ b/.github/workflows/lean-package.yml @@ -145,6 +145,10 @@ jobs: [ "$(replay invalid/missing-packet.ndjson | jq '.watermark < 1')" = true ] if replay invalid/snapshot-mismatch.ndjson; then exit 1; fi + - name: Check single-node CCF consensus replay + if: inputs.package == 'consensus' + run: python3 lean/consensus/replay/check-single-node.py lean/consensus/.lake/build/bin/consensus-replay + - name: Check recovery trace fixtures against their schema if: inputs.package == 'disaster-recovery' run: | diff --git a/lean/consensus/Consensus/Replay/Groups.lean b/lean/consensus/Consensus/Replay/Groups.lean index 62cfe180486..91fac0a8e37 100644 --- a/lean/consensus/Consensus/Replay/Groups.lean +++ b/lean/consensus/Consensus/Replay/Groups.lean @@ -36,7 +36,8 @@ private def group : Reduction (Option Group) := do start, m_ts := head.m_ts, ts := head.ts, - instructions := state.instructions + instructions := state.instructions, + final := (← CCF.Parsec.peek).isNone } /-- @@ -68,6 +69,36 @@ def Reduced.watermark (reduced : Reduced) (ran : Array Nat) : Float := min low (consumed.toFloat / total.toFloat)) 1 +private def reduceStream (header : Header) (events : Array Event) (lenient : Bool) + : Except String ((Array Group × Nat) × Reducer.ReductionState) := + (CCF.Parsec.run events ((node lenient).run { header })).mapError + fun error => + match events.back? with + | some last => + if error == "unexpected end of input" then + s!"{last.record.location}: the events of node '{last.node}' end inside a group" + else + error + | none => error + +/-- +Reduce one node's events into its groups. The node need not bootstrap the network; if it +does, it is its own initial membership. +-/ +def reduceNode (events : Array Event) (declared : List String) (lenient := false) + : Except String Reduced := do + let header : Header := { bootstrap := ∅, declared } + let ((found, consumed), state) ← reduceStream header events lenient + let bootstrap ← + match state.bootstrap with + | some leader => pure {← header.nodeId leader} + | none => pure ∅ + return { + header := { header with bootstrap }, + queues := #[found], + events := #[(events.size, consumed)] + } + /-- Prepare replay identities and reduce each node's events into its queue of groups. If `lenient`, a node's groups end before its first event that no rule consumes. @@ -79,16 +110,7 @@ def reduce (streams : Array (Array Event)) (declared : List String) (lenient := let mut queues := #[] let mut counts := #[] for events in streams do - let ((found, consumed), state) ← - (CCF.Parsec.run events ((node lenient).run { header })).mapError - fun error => - match events.back? with - | some last => - if error == "unexpected end of input" then - s!"{last.record.location}: the events of node '{last.node}' end inside a group" - else - error - | none => error + let ((found, consumed), state) ← reduceStream header events lenient if let some leader := state.bootstrap then if let some other := bootstrap then throw s!"nodes '{other}' and '{leader}' both bootstrap the network" 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..50e53f9a9be 100644 --- a/lean/consensus/Consensus/Replay/Interpreter.lean +++ b/lean/consensus/Consensus/Replay/Interpreter.lean @@ -96,6 +96,8 @@ structure Group where ts : Option Nat /-- What the group's rule emitted, run with no other group's actions in between. -/ instructions : Array Instruction + /-- No event of the node follows the group, so a capture cut short may have cut it. -/ + final : Bool := false /-- Where the group starts, with its rule. -/ def Group.label (group : Group) : String := @@ -116,12 +118,9 @@ private def lookup (header : Header) (replay : ReplayState) (node : String) | throw s!"node '{node}' is not in the network" return state -/-- Compare an action-boundary snapshot with the current model node. -/ -def observeState (header : Header) (node : String) (expected : StateSnapshot) - (replay : ReplayState) +private def observeNodeState (node : String) (self : NodeID) (expected : StateSnapshot) + (state : NodeState) : Except String Unit := do - let state ← lookup header replay node - let self ← header.nodeId node check "node_id" (some expected.node_id) fun _ => node check "leadership_state" expected.leadership_state fun _ => @@ -169,6 +168,12 @@ def observeState (header : Header) (node : String) (expected : StateSnapshot) check "retired_committed_idx" (expected.retired_committed_idx.map some) fun _ => state.retiredCommittedIndex +/-- Compare an action-boundary snapshot with the current model node. -/ +def observeState (header : Header) (node : String) (expected : StateSnapshot) + (replay : ReplayState) + : Except String Unit := do + observeNodeState node (← header.nodeId node) expected (← lookup header replay node) + /-- Physical packet coordinates; lower-term NACK hints are not election terms. -/ def Packet.ofMessage : Model.Node.Message → Packet | .appendEntriesRequest request => @@ -323,6 +328,36 @@ private def ReplayState.run (replay : ReplayState) (header : Header) let pending := replay.state.network.length - if action matches .deliver _ then 1 else 0 return { state, queued := replay.queued ++ state.network.drop pending } +private def matchSends (header : Header) (queued : List Envelope) + (sends : List NativeSend) + : Except String (List Envelope) := do + let mut queued := queued + for send in sends do + let context := s!"{send.origin.label}: send to '{send.target}'" + let target ← (header.nodeId send.target).mapError (s!"{context}: " ++ ·) + let some envelope := closest send.packet (queued.filter (·.target == target)) + | throw s!"{context}: not queued by the model: {render send.packet}" + (checkPacket send.packet envelope.payload).mapError (s!"{context}: " ++ ·) + queued := removeOne envelope queued + return queued + +private def checkLocalInput (header : Header) (input : Input) : Except String Unit := do + match input with + | .sendEntries destination _ => + unless destination < header.declared.length do + throw s!"undeclared model node {destination}" + | .append entries => + for entry in entries do + let metadata := entry.content.metadata + for member + in metadata.configuration.getD ∅ ∪ metadata.retirementConfirmations |>.sort do + unless member < header.declared.length do + throw s!"undeclared model node {member}" + for (destination, _) in entry.flushes do + unless destination < header.declared.length do + throw s!"undeclared model node {destination}" + | _ => pure () + /-- Observations never change model state or repair a disabled action. -/ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instruction) : Except String ReplayState := do @@ -331,14 +366,7 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr observeState header node expected replay return replay | .observeSends sends _ => - let mut queued := replay.queued - for send in sends do - let context := s!"{send.origin.label}: send to '{send.target}'" - let target ← (header.nodeId send.target).mapError (s!"{context}: " ++ ·) - let some envelope := closest send.packet (queued.filter (·.target == target)) - | throw s!"{context}: not queued by the model: {render send.packet}" - (checkPacket send.packet envelope.payload).mapError (s!"{context}: " ++ ·) - queued := removeOne envelope queued + let queued ← matchSends header replay.queued sends if let some envelope := queued.head? then let target := header.declared[envelope.target]?.getD (toString envelope.target) throw @@ -351,22 +379,7 @@ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instr replay.run header (.local joiner (.initAsBackup committed)) step.name | .action (step@(.local node input)) _ => let node ← header.nodeId node - match input with - | .sendEntries destination _ => - unless destination < header.declared.length do - throw s!"undeclared model node {destination}" - | .append entries => - for entry in entries do - let metadata := entry.content.metadata - for member - in metadata.configuration.getD ∅ ∪ metadata.retirementConfirmations - |>.sort do - unless member < header.declared.length do - throw s!"undeclared model node {member}" - for (destination, _) in entry.flushes do - unless destination < header.declared.length do - throw s!"undeclared model node {destination}" - | _ => pure () + checkLocalInput header input replay.run header (.local node input) step.name | .action (.receive source destination packet applied) _ => let before := (← lookup header replay destination).log @@ -473,19 +486,22 @@ receive, and a committed prefix stays committed, so the verdict does not depend enabled group runs. If `lenient`, replay ends without failing once no group may run. -/ -def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) - : ExceptT String (StateM (Array Group)) Result := do +private def checkHeader (header : Header) : Except String Unit := do unless !header.declared.isEmpty && header.declared.all (!·.isEmpty) && header.declared.eraseDups == header.declared do throw "declared nodes must be nonempty and distinct" unless header.declared == header.declared.mergeSort do throw "declared nodes must be sorted lexically" - unless header.bootstrap.Nonempty do - throw "initial membership must be nonempty" for node in header.bootstrap.sort do unless node < header.declared.length do throw s!"undeclared model node {node}" + +def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) + : ExceptT String (StateM (Array Group)) Result := do + ofExcept (checkHeader header) + unless header.bootstrap.Nonempty do + throw "initial membership must be nonempty" let total := queues.foldl (· + ·.size) 0 let key (group : Group) := group.ts.getD group.m_ts let mut state : ReplayState := { state := header.initial } @@ -518,4 +534,151 @@ def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) let actions := (instructions.filter (· matches .action ..)).size return { ran := next, actions, observations := instructions.size - actions } +/-- +The message of a received packet, the reverse of `Packet.ofMessage`. +A packet omits the entries of an AppendEntries, so they are those the node holds, up to its +first of another term, then those it traced applying, all in the packet's term. An entry +which the node did not read is unknown, so a placeholder stands for it: the second result is +the first, by index, which the model must not apply. +-/ +private def Packet.toMessage (packet : Packet) (log : List Entry) + (applied : List (Nat × Entry)) + : Except String (Message × Option (Nat × Entry)) := do + let vote (p : Packet.RequestVote) : RequestVoteRequest := + ⟨p.term, p.term_of_last_committable_idx, p.last_committable_idx⟩ + let (message, firstUntraced) ← + match packet with + | .appendEntries p => do + unless p.prev_idx ≤ p.idx && !p.contains_new_view do + throw "impossible AppendEntries header" + let count := p.idx - p.prev_idx + let held := ((log.drop p.prev_idx).take count).takeWhile (·.term == p.term_of_idx) + let heldThrough := p.prev_idx + held.length + unless applied.all (·.2.term == p.term_of_idx) + && applied.map Prod.fst + == (List.range applied.length).map (heldThrough + 1 + ·) + && held.length + applied.length ≤ count do + throw "applied entries do not follow those the node holds, in the packet's term" + let start := heldThrough + applied.length + 1 + let unread := + (List.range (count - held.length - applied.length)).map + fun k => ⟨p.term_of_idx, .transaction (start + k - 1) {}⟩ + let entries := held ++ applied.map Prod.snd ++ unread + pure + ( + Message.appendEntriesRequest + ⟨p.term, p.prev_idx, p.prev_term, entries, p.leader_commit_idx⟩, + unread.head?.map (start, ·) + ) + | .appendEntriesResponse p => + pure (.appendEntriesResponse ⟨p.term, p.success == "OK", p.last_log_idx⟩, none) + | .requestVote p => pure (.requestVoteRequest (vote p), none) + | .requestPreVote p => pure (.requestPreVoteRequest (vote p), none) + | .requestVoteResponse p => + pure (.requestVoteResponse ⟨p.term, p.vote_granted⟩, none) + | .requestPreVoteResponse p => + pure (.requestPreVoteResponse ⟨p.term, p.vote_granted⟩, none) + | .proposeRequestVote p => pure (.proposeRequestVoteRequest p.term, none) + checkPacket packet message + return (message, firstUntraced) + +/-- Why a single-node group does not validate. -/ +private inductive Failure where + | mismatch (reason : String) + | incomplete (reason : String) + +/-- One node, replayed alone on `Model.Node.step`. -/ +private structure NodeReplay where + state : NodeState + /-- Envelopes queued by the group's actions which no send observation has matched. -/ + queued : List Envelope := [] + /-- The model applied an entry which the node did not trace applying. -/ + untraced : Bool := false + +private def NodeReplay.run (replay : NodeReplay) (self : NodeID) + (event : Model.Node.Event) (name : String) + : Except String NodeReplay := do + let some (state, outputs) := + (Model.Node.step (CCF.Capabilities.record self) self replay.state event).run {} + | throw s!"disabled model action '{name}'" + return { replay with state, queued := replay.queued ++ outputs.outgoing } + +private def runNodeInstruction (header : Header) (self : NodeID) (replay : NodeReplay) + (instruction : Instruction) + : Except String NodeReplay := do + match instruction with + | .observeNodeState node expected _ => + observeNodeState node self expected replay.state + return replay + | .observeSends sends _ => + return { replay with queued := ← matchSends header replay.queued sends } + | .action (step@(.local node input)) _ => + unless (← header.nodeId node) == self do + throw s!"action belongs to node '{node}'" + checkLocalInput header input + replay.run self (.internal input) step.name + | .action (.receive source destination packet applied) _ => + unless (← header.nodeId destination) == self do + throw s!"receive belongs to node '{destination}'" + let source ← header.nodeId source + let (message, firstUntraced) ← packet.toMessage replay.state.log applied + let next ← replay.run self (.receive source message) "receive" + unless applied.all fun (i, entry) => entryAt? next.state.log i == some entry do + throw "the node traced applying an entry which the model did not" + let untraced := + next.state.log != replay.state.log + && firstUntraced.any fun (i, entry) => entryAt? next.state.log i == some entry + return { next with untraced := next.untraced || untraced } + +private def runNodeGroup (header : Header) (self : NodeID) (replay : NodeReplay) + (group : Group) + : Except Failure NodeReplay := do + let replay ← + (group.instructions.foldlM + (fun replay instruction => + (runNodeInstruction header self replay instruction).mapError + (s!"{instruction.origin.label}: " ++ ·)) + replay).mapError + .mismatch + if let some envelope := replay.queued.head? then + let target := header.declared[envelope.target]?.getD (toString envelope.target) + throw + (.incomplete + s!"{group.label}: model queued {render (Packet.ofMessage envelope.payload)} to '{target}' with no native send") + if replay.untraced then + throw + (.mismatch + s!"{group.label}: the model applied an entry which the node did not trace") + return replay + +/-- +Validate one node's groups alone on `Model.Node.step`, from its initial state. +No other node is read, so this does not show that a received packet was sent or that a +snapshot was committed. If `lenient`, stops before a final group which is incomplete. +-/ +def validateNode (header : Header) (groups : Array Group) (lenient := false) + : Except String Result := do + checkHeader header + let mut ran := 0 + if let some first := groups[0]? then + let self ← header.nodeId first.node + let mut replay : NodeReplay := + { state := Model.initialNodeState header.bootstrap self } + for group in groups do + unless group.node == first.node do + throw + s!"{group.label}: group belongs to node '{group.node}', expected '{first.node}'" + match runNodeGroup header self replay group with + | .ok after => + replay := after + ran := ran + 1 + | .error (.incomplete reason) => + unless lenient && group.final do + throw reason + break + | .error (.mismatch reason) => throw reason + let instructions := (groups.extract 0 ran).flatMap (·.instructions) + let actions := (instructions.filter (· matches .action ..)).size + return { ran := #[ran], actions, observations := instructions.size - actions } + end Consensus.Replay diff --git a/lean/consensus/replay/README.md b/lean/consensus/replay/README.md index 3d5ddb73138..a764010a4a1 100644 --- a/lean/consensus/replay/README.md +++ b/lean/consensus/replay/README.md @@ -80,15 +80,31 @@ A term history which is out of order or starts a view after the snapshot fails t An envelope that is never delivered stays queued, which models loss, so `drop_pending_to` emits no observation or action. After each rule's actions, the envelopes they queued must equal the rule's native sends, as a multiset of target and rendered packet. +## Single-node validation + +`consensus-replay --mode=single-node [--node=NODE] TRACE.msgpack` validates each node's events (or only `NODE`'s) alone, without modeling the network or requiring a bootstrap node or other peers in the capture. +[`reduceNode`](../Consensus/Replay/Groups.lean) reduces a node's stream into its groups, and [`validateNode`](../Consensus/Replay/Interpreter.lean) runs them on `Node.step` from the node's initial state, comparing the boundary snapshots and the multiset of sends. +Because no other node is read, single-node mode does not show that a received packet was sent or that a snapshot was committed; use `--mode=complete` (the default) for that. + +In single-node mode, the node's own events supply every input of its model: + +- **Receive:** votes, responses and empty heartbeats come from the packet. For a nonempty AppendEntries, the entries are those the node holds (up to its first of another term), then those it traced applying (`execute_append_entries_sync` and its hooks), with placeholders for any trailing entries the node rejected unread. The model must not apply a placeholder. +- **Join:** `init_as_backup` builds the node's log from its term history and snapshot hooks. + +With `--lenient`, reduction ends at the first event no rule reads, and validation stops before a node's final group if that group is incomplete (the model sent a packet the trace does not show). +A group that contradicts the model is an error in either mode. +`--schedule` is not supported with `--mode=single-node`, and `--node` requires `--mode=single-node`. + ## 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): boundary-state field comparisons, packet selection, send checks, complete-mode scheduling and single-node validation. - [`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. +- [`check-single-node.py`](check-single-node.py): single-node validation checks on complete, cut and altered captures. - [`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..5c460188c7b 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -17,25 +17,71 @@ 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 + let modeFlag := "--mode=" + let nodeFlag := "--node=" + let modes := flags.filterMap (·.dropPrefix? modeFlag |>.map (·.toString)) + let nodes := flags.filterMap (·.dropPrefix? nodeFlag |>.map (·.toString)) + unless flags.all + (fun f => + ["--schedule", "--lenient"].contains f + || f.startsWith modeFlag + || f.startsWith nodeFlag) + && modes.length ≤ 1 + && nodes.length ≤ 1 do IO.eprintln s!"unknown option {flags}" return 2 + let mode := modes.headD "complete" + unless mode == "complete" || mode == "single-node" do + IO.eprintln s!"unknown mode '{mode}' (expected 'complete' or 'single-node')" + return 2 let lenient := flags.contains "--lenient" + if mode == "single-node" && flags.contains "--schedule" then + IO.eprintln "--schedule is not supported with --mode=single-node" + return 2 + if mode == "complete" && !nodes.isEmpty then + IO.eprintln "--node requires --mode=single-node" + return 2 let records ← readLog path - let reduced := 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 mode == "single-node" then + let result := do + let (streams, declared) ← prepareEvents (← records) + let streams ← + match nodes with + | [target] => + let some stream := + streams.find? + fun s => s[0]?.any (fun (e : Event) => e.node == target) + | throw s!"node '{target}' not found in trace" + pure #[stream] + | _ => pure streams + let mut watermark : Float := 1 + let mut ran := #[] + let mut actions := 0 + let mut observations := 0 + for stream in streams do + let reduced ← reduceNode stream declared lenient + let result ← validateNode reduced.header reduced.queues[0]! lenient + watermark := min watermark (reduced.watermark result.ran) + ran := ran ++ result.ran + actions := actions + result.actions + observations := observations + result.observations + return (watermark, ({ ran, actions, observations } : Result)) + (result, #[]) + else + let reduced := do + let (streams, declared) ← prepareEvents (← records) + reduce streams declared lenient + 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}" @@ -54,7 +100,9 @@ def main (args : List String) : IO UInt32 := do IO.println result.compress return 0 | _, _ => - IO.eprintln "usage: consensus-replay [--schedule] [--lenient] TRACE.msgpack"; + IO.eprintln + "usage: consensus-replay [--mode=complete|single-node] [--node=NODE] [--schedule] [--lenient] TRACE.msgpack" + ; return 2 catch error => IO.eprintln s!"{error}" diff --git a/lean/consensus/replay/check-single-node.py b/lean/consensus/replay/check-single-node.py new file mode 100755 index 00000000000..88896677ca0 --- /dev/null +++ b/lean/consensus/replay/check-single-node.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Check single-node consensus trace validation on complete, cut and altered traces.""" + +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 replay(raw_bytes, *args, error=False): + with trace.open("wb") as stream: + subprocess.run( + [sys.executable, pack], input=raw_bytes, stdout=stream, check=True + ) + 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 + + # All nodes validate independently in single-node mode, or one via --node. + assert replay(raw(history), "--mode=single-node")["watermark"] == 1 + assert replay(raw(history), "--mode=complete")["watermark"] == 1 + assert replay(raw(history), "--mode=single-node", "--node=0")["watermark"] == 1 + assert replay(raw(history), "--mode=single-node", "--node=1")["watermark"] == 1 + + # A lone follower trace needs no bootstrap node, sender, or --node flag. + follower_only = [r for r in history if r["msg"].get("st", {}).get("id") == "1"] + assert replay(raw(follower_only), "--mode=single-node")["watermark"] == 1 + + # Unknown node fails; bad flag combinations exit 2. + assert "not found" in replay( + raw(history), "--mode=single-node", "--node=99", error=True + ) + for bad_args in ( + ("--mode=bogus",), + ("--mode=single-node", "--schedule"), + ("--node=0",), + ): + proc = subprocess.run( + [executable, *bad_args, trace], + text=True, + capture_output=True, + check=False, + ) + assert proc.returncode == 2, (bad_args, proc.stderr) + + # Receiving the same batch again holds its entries and 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) + assert ( + replay(raw(history, *again), "--mode=single-node", "--node=1")["watermark"] + == 1 + ) + + # 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 + + # Cut before the follower's last send: the incomplete final group earns no credit. + replay(raw(without(27)), "--mode=single-node", "--node=1", error=True) + cut = replay(raw(without(27)), "--mode=single-node", "--node=1", "--lenient") + assert (cut["groups"], cut["watermark"]) == (2, 6 / 10), cut + # Cut before the follower traces the last applied entry. + assert ( + round( + replay( + raw(history[:26]), "--mode=single-node", "--node=1", "--lenient" + )["watermark"], + 5, + ) + == 0.66667 + ) + # Join cut inside its rule is not reduced. + assert ( + round( + replay( + raw(history[:17]), "--mode=single-node", "--node=1", "--lenient" + )["watermark"], + 5, + ) + == 0.66667 + ) + # Only a final group may be incomplete. + replay( + raw(without(27), later), + "--mode=single-node", + "--node=1", + "--lenient", + error=True, + ) + # Its response shows the follower was past an entry it did not trace. + assert "did not trace" in replay( + raw(without(26)), "--mode=single-node", "--node=1", "--lenient", error=True + ) + + # Contradictions in applied entries fail in either mode. + for records in [ + without(24, 25, 27), # entry applied after a gap + altered(24, vw=3), # entry in another view than its packet + ]: + assert "do not follow" in replay( + raw(records), "--mode=single-node", "--node=1", "--lenient", error=True + ) + + # Reduction errors reject strictly and stop reduction when lenient. + for records, reason in [ + (altered(24, frm="1"), "expected an entry from 0"), + (altered(16, vw=7), "another view"), + (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), "--mode=single-node", "--node=1", error=True + ), reason + assert ( + replay(raw(records), "--mode=single-node", "--node=1", "--lenient")[ + "watermark" + ] + < 1 + ) + + print("Single-node replay checks passed.") + + +if __name__ == "__main__": + main(sys.argv[1])