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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changes/cross-node-consensus-replay.added.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions .changes/per-node-consensus-replay.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The [consensus trace replayer](lean/consensus/replay/README.md#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.
12 changes: 2 additions & 10 deletions .github/workflows/lean-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
1 change: 0 additions & 1 deletion lean/consensus/Consensus.lean
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,3 @@ public import Consensus.Properties
public import Consensus.Replay.Groups

import Consensus.Tests.CanonicalTraces
import Consensus.Tests.ReplayDelivery
5 changes: 2 additions & 3 deletions lean/consensus/Consensus/Replay/Groups.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}

/--
Expand Down
2 changes: 2 additions & 0 deletions lean/consensus/Consensus/Replay/Input.lean
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ def prepareEvents (records : Array Record)
match body with
| .retiredCommittedTx event => declared := event.retired_node_id :: declared
| .addConfiguration event => declared := event.nodes ++ declared
| .recv event => declared := event.from_node_id :: declared
| .send event => declared := event.to_node_id :: declared
| _ => pure ()
let streams :=
pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node)
Expand Down
422 changes: 181 additions & 241 deletions lean/consensus/Consensus/Replay/Interpreter.lean

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lean/consensus/Consensus/Replay/Reduction.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions lean/consensus/Consensus/Replay/Trace.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
71 changes: 0 additions & 71 deletions lean/consensus/Consensus/Tests/ReplayDelivery.lean

This file was deleted.

65 changes: 46 additions & 19 deletions lean/consensus/replay/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
28 changes: 8 additions & 20 deletions lean/consensus/replay/ReplayMain.lean
Original file line number Diff line number Diff line change
Expand Up @@ -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) =>
Expand All @@ -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
Loading