From f799bc5ebeba36508c7fc8775d9f5cb1a765c3ac Mon Sep 17 00:00:00 2001 From: Amaury Chamayou Date: Wed, 25 Nov 2026 15:57:24 +0000 Subject: [PATCH 1/5] Optimize consensus-replay execution Restores the replayer changes from 4fb00c2b0 that were moved out of the base PR. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- lean/consensus/Consensus/Replay/Groups.lean | 2 +- lean/consensus/Consensus/Replay/Input.lean | 366 ++++++++++++++++-- .../Consensus/Replay/Interpreter.lean | 333 ++++++++++++---- .../consensus/Consensus/Replay/Reduction.lean | 31 +- lean/consensus/replay/ReplayMain.lean | 10 +- tests/cft_trace_validation.py | 13 +- 6 files changed, 607 insertions(+), 148 deletions(-) diff --git a/lean/consensus/Consensus/Replay/Groups.lean b/lean/consensus/Consensus/Replay/Groups.lean index 8ba1688ac0c5..76cd1d901c68 100644 --- a/lean/consensus/Consensus/Replay/Groups.lean +++ b/lean/consensus/Consensus/Replay/Groups.lean @@ -72,7 +72,7 @@ If `lenient`, a node's groups end before its first event that no rule consumes. -/ def reduce (streams : Array (Array Event)) (declared : List String) (lenient := false) : Except String Reduced := do - let header : Header := { bootstrap := ∅, declared } + let header : Header := Header.withIndex { bootstrap := ∅, declared } let mut bootstrap := none let mut queues := #[] let mut counts := #[] diff --git a/lean/consensus/Consensus/Replay/Input.lean b/lean/consensus/Consensus/Replay/Input.lean index 54cdc3fbd39e..cf95271fd266 100644 --- a/lean/consensus/Consensus/Replay/Input.lean +++ b/lean/consensus/Consensus/Replay/Input.lean @@ -93,11 +93,105 @@ structure Event where message : Json /-- `msg.state`: the node's consensus state when the event was emitted. -/ state : Json + /-- Cache identifier shared by byte-identical `msg` payloads, for observation caching. -/ + stateId : Option Nat := none deriving Inhabited def Event.origin (event : Event) (rule : String) : Origin := { file := event.record.file, line := event.record.line, rule } +/-- A parsed CFT record queued in its emitting process's bucket before sorting by `m_ts`. -/ +private structure BucketEntry where + file : String + m_ts : Nat + line : Nat + ts : Option Nat + message : Json + stateId : Option Nat + +private structure ParsedMessage where + isCmd : Bool + function : String + node : String + state : Json + extraDeclared : List String + +private def parseMessage (message : Json) : Except String ParsedMessage := do + if (optional message "cmd").isSome then + return { + isCmd := true, function := "", node := "", state := Json.null, extraDeclared := [] + } + let function ← string message "function" + let state ← + if function == "retired_committed_tx" then + pure Json.null + else + field message "state" + let node ← + string (if function == "retired_committed_tx" then message else state) "node_id" + let mut extraDeclared : List String := [] + if function == "retired_committed_tx" then + extraDeclared := (← string message "retired_node_id") :: extraDeclared + if function == "add_configuration" then + extraDeclared := (← configuration message) ++ extraDeclared + return { isCmd := false, function, node, state, extraDeclared } + +private def buildStreamsFromBuckets (buckets : Std.HashMap String (Array BucketEntry)) + : Except String (Array (Array Event) × List String) := do + let sortedPids := buckets.keys.mergeSort + let mut nodeEvents : Std.HashMap String (Array Event) := {} + let mut pids : Std.HashMap String String := {} + let mut declared : List String := [] + let mut parsedCache : Std.HashMap Nat ParsedMessage := {} + for pid in sortedPids do + let entries := + (buckets[pid]!).qsort + fun a b => + a.m_ts < b.m_ts || (a.m_ts == b.m_ts && a.line < b.line) + let mut previous : Option (Nat × String × Nat) := none + for entry in entries do + let location := s!"{entry.file}:{entry.line}" + if let some (lastMts, earlierFile, earlierLine) := previous then + if lastMts == entry.m_ts then + throw + s!"{location}: m_ts {entry.m_ts} of pid '{pid}' repeats {earlierFile}:{earlierLine}" + previous := some (entry.m_ts, entry.file, entry.line) + let parsed ← + match entry.stateId.bind (parsedCache[·]?) with + | some cached => pure cached + | none => + let parsed ← (parseMessage entry.message).mapError (s!"{location}: " ++ ·) + if let some id := entry.stateId then + parsedCache := parsedCache.insert id parsed + pure parsed + unless parsed.isCmd do + if let some other := pids[parsed.node]? then + unless other == pid do + throw + s!"{location}: node '{parsed.node}' is traced by pids '{other}' and '{pid}'" + pids := pids.insert parsed.node pid + let record : Record := + { file := entry.file, line := entry.line, value := Json.null } + let ev : Event := + { + record + m_ts := entry.m_ts + ts := entry.ts + function := parsed.function + node := parsed.node + message := entry.message + state := parsed.state + stateId := entry.stateId + } + nodeEvents := + nodeEvents.alter parsed.node + fun + | some arr => some (arr.push ev) + | none => some #[ev] + declared := parsed.node :: parsed.extraDeclared ++ declared + let streams := pids.keys.mergeSort.toArray.map fun node => nodeEvents[node]?.getD #[] + return (streams, declared.mergeSort.eraseDups) + /-- Order each process's records by `m_ts`, skip driver command records and records with a `tag` other than `ccf.cft`, split events into per-node streams sorted by node, and collect @@ -108,48 +202,236 @@ def prepareEvents (records : Array Record) let records := records.filter fun record => (optional record.value "tag").all (· == Json.str "ccf.cft") - let keyed ← - records.mapM - fun record => - (do - return (← string record.value "pid", ← nat record.value "m_ts", record)) - |>.mapError (s!"{record.location}: " ++ ·) - let keyed := - keyed.toList.mergeSort fun (p, t, _) (q, u, _) => p < q || (p == q && t <= u) - let mut events : Array Event := #[] - let mut previous : Option (String × Nat × Record) := none - let mut pids : Std.HashMap String String := {} - let mut declared : List String := [] - for (pid, m_ts, record) in keyed do - if let some (last, lastMts, earlier) := previous then - if last == pid && lastMts == m_ts then - throw s!"{record.location}: m_ts {m_ts} of pid '{pid}' repeats {earlier.location}" - previous := some (pid, m_ts, record) - try - let message ← field record.value "msg" - unless (optional message "cmd").isSome do - let function ← string message "function" - let state ← - if function == "retired_committed_tx" then - pure Json.null - else - field message "state" - let node ← - string (if function == "retired_committed_tx" then message else state) "node_id" - if let some other := pids[node]? then - require (other == pid) s!"node '{node}' is traced by pids '{other}' and '{pid}'" - pids := pids.insert node pid + let mut buckets : Std.HashMap String (Array BucketEntry) := {} + for record in records do + let (pid, m_ts, ts, message) ← + (do + let pid ← string record.value "pid" + let m_ts ← nat record.value "m_ts" let ts ← (optional record.value "ts").mapM natural - events := events.push { record, m_ts, ts, function, node, message, state } - declared := node :: declared - if function == "retired_committed_tx" then - declared := (← string message "retired_node_id") :: declared - if function == "add_configuration" then - declared := (← configuration message) ++ declared - catch error => - throw s!"{record.location}: {error}" - let streams := - pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node) - return (streams, declared.mergeSort.eraseDups) + let message ← field record.value "msg" + return (pid, m_ts, ts, message)) + |>.mapError (s!"{record.location}: " ++ ·) + let entry : BucketEntry := + { file := record.file, m_ts, line := record.line, ts, message, stateId := none } + buckets := + buckets.alter pid + fun + | some arr => some (arr.push entry) + | none => some #[entry] + buildStreamsFromBuckets buckets + +private def byteEqAt (s : String) (pos : Nat) (lit : String) : Bool := + if pos + lit.utf8ByteSize > s.utf8ByteSize then + false + else + let rec go (i : Nat) : Bool := + if h : i < lit.utf8ByteSize then + if h2 : pos + i < s.utf8ByteSize then + if s.getUTF8Byte ⟨pos + i⟩ h2 == lit.getUTF8Byte ⟨i⟩ h then + go (i + 1) + else + false + else + false + else + true + termination_by lit.utf8ByteSize - i + go 0 + +private def scanAsciiNat (s : String) (pos : Nat) : Option (Nat × Nat) := + let rec go (i acc : Nat) (saw : Bool) : Option (Nat × Nat) := + if h : i < s.utf8ByteSize then + let b := s.getUTF8Byte ⟨i⟩ h + if b >= 48 && b <= 57 then + go (i + 1) (acc * 10 + (b - 48).toNat) true + else if saw then + some (acc, i) + else + none + else if saw then + some (acc, i) + else + none + termination_by s.utf8ByteSize - i + go pos 0 false + +private def scanSimpleJsonString (s : String) (pos : Nat) : Option (String × Nat) := + let rec go (i : Nat) : Option (String × Nat) := + if h : i < s.utf8ByteSize then + let b := s.getUTF8Byte ⟨i⟩ h + if b == 34 then + some (String.Pos.Raw.extract s ⟨pos⟩ ⟨i⟩, i + 1) + else if b == 92 || b < 32 || b >= 128 then + none + else + go (i + 1) + else + none + termination_by s.utf8ByteSize - i + go pos + +private inductive FastLine where + | skip + | fast (pid : String) (m_ts ts : Nat) (msgRaw : String) + | fallback + +/-- Match standard Fluentd NDJSON lines to skip non-`ccf.cft` tags and reuse identical `msg` JSON. -/ +private def matchFluentdLine (raw : String) : FastLine := + if !byteEqAt raw 0 "{\"tag\": \"" then + .fallback + else + match scanSimpleJsonString raw 9 with + | none => .fallback + | some (tag, p0) => + if tag != "ccf.cft" then + .skip + else if !byteEqAt raw p0 ", \"ts\": " then + .fallback + else + match scanAsciiNat raw (p0 + 8) with + | none => .fallback + | some (ts, p1) => + if !byteEqAt raw p1 ", \"pid\": \"" then + .fallback + else + match scanSimpleJsonString raw (p1 + 10) with + | none => .fallback + | some (pid, p2) => + if !byteEqAt raw p2 ", \"m_ts\": " then + .fallback + else + match scanAsciiNat raw (p2 + 10) with + | none => .fallback + | some (m_ts, p3) => + if !byteEqAt raw p3 ", \"msg\": " then + .fallback + else + let msgStart := p3 + 9 + let size := raw.utf8ByteSize + if h : msgStart < size then + if raw.getUTF8Byte ⟨size - 1⟩ + (Nat.sub_lt (Nat.lt_of_le_of_lt (Nat.zero_le _) h) + Nat.zero_lt_one) + == 125 then + .fast pid m_ts ts + (String.Pos.Raw.extract raw ⟨msgStart⟩ ⟨size - 1⟩) + else + .fallback + else + .fallback + +/-- +Stream an NDJSON trace file line by line, skipping non-`ccf.cft` lines before JSON parsing +and reusing parsed `msg` objects across consecutive identical events from the same process. +-/ +def readEvents (path : System.FilePath) + : IO (Except String (Array (Array Event) × List String)) := do + let path ← IO.FS.realPath path + let file := path.toString + let handle ← IO.FS.Handle.mk path .read + let mut line : Nat := 0 + let mut buckets : Std.HashMap String (Array BucketEntry) := {} + let mut msgCache : Std.HashMap String (String × Json × Nat) := {} + let mut nextStateId : Nat := 1 + let mut error : Option String := none + while error.isNone do + let raw ← handle.getLine + if raw.isEmpty then + break + line := line + 1 + let raw := + let raw := if raw.endsWith "\n" then raw.dropEnd 1 |>.toString else raw + if raw.endsWith "\r" then raw.dropEnd 1 |>.toString else raw + let mut handled := false + match matchFluentdLine raw with + | .skip => handled := true + | .fast pid m_ts ts msgRaw => + match msgCache[pid]? with + | some (cachedRaw, cachedJson, cachedId) => + if cachedRaw == msgRaw then + let entry : BucketEntry := + { + file + m_ts + line + ts := some ts + message := cachedJson + stateId := some cachedId + } + buckets := + buckets.alter pid + fun + | some arr => some (arr.push entry) + | none => some #[entry] + handled := true + else + match Json.parse msgRaw with + | .ok msgJson => + let id := nextStateId + nextStateId := nextStateId + 1 + msgCache := msgCache.insert pid (msgRaw, msgJson, id) + let entry : BucketEntry := + { + file, + m_ts, + line, + ts := some ts, + message := msgJson, + stateId := some id + } + buckets := + buckets.alter pid + fun + | some arr => some (arr.push entry) + | none => some #[entry] + handled := true + | .error _ => pure () + | none => + match Json.parse msgRaw with + | .ok msgJson => + let id := nextStateId + nextStateId := nextStateId + 1 + msgCache := msgCache.insert pid (msgRaw, msgJson, id) + let entry : BucketEntry := + { + file, + m_ts, + line, + ts := some ts, + message := msgJson, + stateId := some id + } + buckets := + buckets.alter pid + fun + | some arr => some (arr.push entry) + | none => some #[entry] + handled := true + | .error _ => pure () + | .fallback => pure () + unless handled do + match Json.parse raw with + | .error err => error := some s!"{file}:{line}: {err}" + | .ok value => + if (optional value "tag").all (· == Json.str "ccf.cft") then + match (do + let pid ← string value "pid" + let m_ts ← nat value "m_ts" + let ts ← (optional value "ts").mapM natural + let message ← field value "msg" + return (pid, m_ts, ts, message)) with + | .error err => error := some s!"{file}:{line}: {err}" + | .ok (pid, m_ts, ts, message) => + let entry : BucketEntry := + { file, m_ts, line, ts, message, stateId := none } + buckets := + buckets.alter pid + fun + | some arr => some (arr.push entry) + | none => some #[entry] + if let some err := error then + return .error err + return buildStreamsFromBuckets buckets end Consensus.Replay diff --git a/lean/consensus/Consensus/Replay/Interpreter.lean b/lean/consensus/Consensus/Replay/Interpreter.lean index e4aaf82bad2a..ae2bf7987a5f 100644 --- a/lean/consensus/Consensus/Replay/Interpreter.lean +++ b/lean/consensus/Consensus/Replay/Interpreter.lean @@ -6,6 +6,8 @@ module public import Consensus.Model public import Lean.Data.Json +import Std.Data.HashMap + public section namespace Consensus.Replay @@ -30,8 +32,20 @@ def Origin.label (origin : Origin) : String := structure Header where bootstrap : Finset NodeID declared : List String + nodeIds : Std.HashMap String NodeID := {} + +def Header.withIndex (header : Header) : Header := + let nodeIds := + header.declared.zipIdx.foldl + (fun acc (name, idx) => acc.insert name idx) + ({} : Std.HashMap String NodeID) + { header with nodeIds } def Header.nodeId (header : Header) (node : String) : Except String NodeID := do + if !header.nodeIds.isEmpty then + let some index := header.nodeIds[node]? + | throw s!"undeclared node '{node}'" + return index let some index := header.declared.findIdx? (· == node) | throw s!"undeclared node '{node}'" return index @@ -58,10 +72,29 @@ def Step.name : Step → String | .local _ (.initAsBackup _) | .initAsBackup .. => "initAsBackup" | .receive .. => "receive" +/-- Precomputed per-node observation fields derived in one pass over `state.log`. -/ +structure NodeObsCache where + nodeId : Json + leadershipState : Json + currentView : Json + lastIdx : Json + commitIdx : Json + committableIndices : Json + configurations : Json + membershipState : Json + retirementPhase : Json + retirementIdx : Json + retirementCommittableIdx : Json + retiredCommittedIdx : Json + /-- Cache key of the last `expected` snapshot already verified against this state. -/ + lastVerifiedId : Option Nat := none + structure ReplayState where state : Model.State /-- Envelopes queued by actions since the last send observation. -/ queued : List Envelope := [] + /-- Per-node cached observation summaries, invalidated when that node steps. -/ + obsCache : Array (Option NodeObsCache) := #[] /-- A traced native send, or the proposal a nomination implies. -/ structure NativeSend where @@ -73,12 +106,13 @@ structure NativeSend where inductive Instruction where | action (step : Step) (origin : Origin) | observeNodeState (node : String) (expected : Json) (origin : Origin) + (stateId : Option Nat := none) /-- The envelopes queued since the last send observation must equal `sends`, as a multiset. -/ | observeSends (sends : List NativeSend) (origin : Origin) def Instruction.origin : Instruction → Origin | .action _ origin - | .observeNodeState _ _ origin + | .observeNodeState _ _ origin _ | .observeSends _ origin => origin /-- @@ -131,41 +165,116 @@ private def members (header : Header) (nodes : Finset NodeID) : List String := fun (name, index) => if index ∈ nodes then some name else none -/-- Compare an action-boundary snapshot with the current model node. -/ -def observeState (header : Header) (node : String) (expected : Json) - (replay : ReplayState) - : Except String Unit := do - let state ← lookup header replay node - let self ← header.nodeId node +private def checkJson (actual expected : Json) : Except String Unit := do + unless expected == actual do + throw s!"observed {expected.compress}, model {actual.compress}" + +/-- Derive all observed fields for `state` in one pass over `state.log`. -/ +private def buildNodeObsCache (header : Header) (self : NodeID) (node : String) + (state : NodeState) + : NodeObsCache := + let ( + lastIdx, + firstCommittable, + lastCommittable, + configHistory, + committedCount, + _, + retirementIndex, + retirementCommittableIndex + ) := + state.log.foldl + (fun (index, firstC, lastC, configs, committed, prevIn, retIdx, retCommIdx) entry => + let index := index + 1 + match entry.content with + | .signature => + let (firstC, lastC) := + if index > state.commitIndex then + match firstC with + | none => (some index, lastC) + | some _ => (firstC, some index) + else + (firstC, lastC) + let retCommIdx := + if retIdx.isSome && retCommIdx.isNone then some index else retCommIdx + (index, firstC, lastC, configs, committed, prevIn, retIdx, retCommIdx) + | .transaction _ metadata => + match metadata.configuration with + | some nodes => + let configs := configs.push { index, nodes : Configuration } + let committed := + if index <= state.commitIndex then committed + 1 else committed + let inConfig := decide (self ∈ nodes) + let retIdx := + if retIdx.isNone && prevIn && !inConfig then some index else retIdx + (index, firstC, lastC, configs, committed, inConfig, retIdx, retCommIdx) + | none => + (index, firstC, lastC, configs, committed, prevIn, retIdx, retCommIdx)) + (0, none, none, (#[] : Array Configuration), 0, false, none, none) + let committable : List Nat := + match firstCommittable, lastCommittable with + | none, _ => [] + | some f, none => [f] + | some f, some l => [f, l] + let activeConfigs := + (configHistory.toList.drop (committedCount - 1)).filterMap + fun configuration => + if configuration.index == 0 then + none + else + some (configuration.index, members header configuration.nodes) + let phase : MembershipState := + match retirementIndex with + | none => .noRetirementObserved + | some index => + if state.retiredCommittedIndex.isSome then + .retiredCommitted + else if index <= state.commitIndex then + .retirementCompleted + else if retirementCommittableIndex.isSome then + .retirementSigned + else + .retirementOrdered + { + nodeId := toJson node + leadershipState := + toJson + (match state.role with + | .none => "None" + | .follower => "Follower" + | .preVoteCandidate => "PreVoteCandidate" + | .candidate => "Candidate" + | .primary => "Leader") + currentView := toJson state.currentTerm + lastIdx := toJson lastIdx + commitIdx := toJson state.commitIndex + committableIndices := toJson committable + configurations := toJson activeConfigs + membershipState := + toJson (if phase == .noRetirementObserved then "Active" else "Retired") + retirementPhase := + toJson + (match phase with + | .noRetirementObserved => (none : Option String) + | .retirementOrdered => some "Ordered" + | .retirementSigned => some "Signed" + | .retirementCompleted => some "Completed" + | .retiredCommitted => some "RetiredCommitted") + retirementIdx := toJson retirementIndex + retirementCommittableIdx := toJson retirementCommittableIndex + retiredCommittedIdx := toJson state.retiredCommittedIndex + } + +private def checkCachedObservation (cache : NodeObsCache) (expected : Json) + : Except String Unit := checkFields (fun - | "node_id" => some (checkValue node) - | "leadership_state" => - some - (checkValue - (match state.role with - | .none => "None" - | .follower => "Follower" - | .preVoteCandidate => "PreVoteCandidate" - | .candidate => "Candidate" - | .primary => "Leader")) - | "current_view" => some (checkValue state.currentTerm) - | "last_idx" => some (checkValue state.log.length) - | "commit_idx" => some (checkValue state.commitIndex) - | "committable_indices" => - let indices := - (state.log.zipIdx 1).filterMap - fun (entry, index) => - if index > state.commitIndex && entry.content.isSignature then - some index - else - none - -- Native telemetry records only the first and last cache entries. - some - (checkValue - (match indices with - | [] => [] - | first :: rest => first :: rest.getLast?.toList)) + | "node_id" => some (checkJson cache.nodeId) + | "leadership_state" => some (checkJson cache.leadershipState) + | "current_view" => some (checkJson cache.currentView) + | "last_idx" => some (checkJson cache.lastIdx) + | "commit_idx" => some (checkJson cache.commitIdx) + | "committable_indices" => some (checkJson cache.committableIndices) | "configurations" => some fun value => do @@ -175,37 +284,50 @@ def observeState (header : Header) (node : String) (expected : Json) let index ← configuration.getObjValAs? Nat "idx" let nodes ← configuration.getObjVal? "nodes" >>= Json.getObj? return (index, (nodes.toList.map Prod.fst).mergeSort) - let actual := - (activeConfigurations state.log state.commitIndex).filterMap - fun configuration => - if configuration.index == 0 then - none - else - some (configuration.index, members header configuration.nodes) - checkValue actual (toJson observed) - | "membership_state" => - some - (checkValue - (if (state.retirement self).phase == .noRetirementObserved then - "Active" - else - "Retired")) - | "retirement_phase" => - some - (checkValue - (match (state.retirement self).phase with - | .noRetirementObserved => none - | .retirementOrdered => some "Ordered" - | .retirementSigned => some "Signed" - | .retirementCompleted => some "Completed" - | .retiredCommitted => some "RetiredCommitted")) - | "retirement_idx" => some (checkValue (state.retirement self).index) - | "retirement_committable_idx" => - some (checkValue (state.retirement self).committableIndex) - | "retired_committed_idx" => some (checkValue state.retiredCommittedIndex) + checkJson cache.configurations (toJson observed) + | "membership_state" => some (checkJson cache.membershipState) + | "retirement_phase" => some (checkJson cache.retirementPhase) + | "retirement_idx" => some (checkJson cache.retirementIdx) + | "retirement_committable_idx" => some (checkJson cache.retirementCommittableIdx) + | "retired_committed_idx" => some (checkJson cache.retiredCommittedIdx) | _ => none) expected +/-- Compare an action-boundary snapshot with the current model node. -/ +def observeState (header : Header) (node : String) (expected : Json) + (replay : ReplayState) + : Except String Unit := do + let state ← lookup header replay node + let self ← header.nodeId node + checkCachedObservation (buildNodeObsCache header self node state) expected + +private def observeStateCached (header : Header) (node : String) (expected : Json) + (stateId : Option Nat) (replay : ReplayState) + : Except String ReplayState := do + let self ← header.nodeId node + if self < replay.obsCache.size then + match replay.obsCache[self]! with + | some cache => + if stateId.isSome && cache.lastVerifiedId == stateId then + return replay + checkCachedObservation cache expected + if stateId.isSome then + let obsCache := + replay.obsCache.set! self (some { cache with lastVerifiedId := stateId }) + return { replay with obsCache } + return replay + | none => + let some state := nodeState replay.state self + | throw s!"node '{node}' is not in the network" + let cache := buildNodeObsCache header self node state + checkCachedObservation cache expected + let obsCache := + replay.obsCache.set! self (some { cache with lastVerifiedId := stateId }) + return { replay with obsCache } + else + observeState header node expected replay + return replay + /-- Physical packet coordinates; lower-term NACK hints are not election terms. -/ def messageJson (message : Model.Node.Message) : Json := let fields := @@ -332,16 +454,26 @@ private def ReplayState.run (replay : ReplayState) (header : Header) | 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 } + let acted := + match action with + | .local node _ => node + | .deliver envelope => envelope.target + let obsCache := + if acted < replay.obsCache.size then + replay.obsCache.set! acted none + else + replay.obsCache + return { state, queued := replay.queued ++ state.network.drop pending, obsCache } /-- Observations never change model state or repair a disabled action. -/ def runInstruction (header : Header) (replay : ReplayState) (instruction : Instruction) : Except String ReplayState := do match instruction with - | .observeNodeState node expected _ => - observeState header node expected replay - return replay + | .observeNodeState node expected _ stateId => + observeStateCached header node expected stateId replay | .observeSends sends _ => + if sends.isEmpty && replay.queued.isEmpty then + return replay let mut queued := replay.queued for send in sends do let context := s!"{send.origin.label}: send to '{send.target}'" @@ -475,6 +607,7 @@ enabled group runs. If `lenient`, replay ends without failing once no group may run. -/ def schedule (header : Header) (queues : Array (Array Group)) (lenient := false) + (record := true) : ExceptT String (StateM (Array Group)) Result := do unless !header.declared.isEmpty && header.declared.all (!·.isEmpty) @@ -487,37 +620,67 @@ 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 header := header.withIndex let total := queues.foldl (· + ·.size) 0 if total == 0 then throw "replay groups must not be empty" let key (group : Group) := group.ts.getD group.m_ts - let mut state : ReplayState := { state := header.initial } + let mut state : ReplayState := + { + state := header.initial + obsCache := Array.replicate header.declared.length none + } let mut next := Array.replicate queues.size 0 + let mut actions : Nat := 0 + let mut observations : Nat := 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) + -- Fast path: find the earliest head without allocating; most groups are immediately ready. + let mut best : Option (Group × Nat × Nat) := none + for queue in [:queues.size] do + let idx := next[queue]! + let groups := queues[queue]! + if h : idx < groups.size then + let group := groups[idx] + let k := key group + match best with + | none => best := some (group, queue, k) + | some (_, bestQ, bestK) => + if k < bestK || (k == bestK && queue < bestQ) then + best := some (group, queue, k) + let some (firstGroup, firstQueue, _) := best | break + let mut chosen : Option (Group × Nat) := none + let mut blocked : Array (Group × (Unit → String)) := #[] + match ← ofExcept (firstGroup.waiting header state) with + | none => chosen := some (firstGroup, firstQueue) + | some firstReason => + blocked := blocked.push (firstGroup, firstReason) + let heads := + (queues.zipIdx.filterMap + fun (groups, queue) => + if queue == firstQueue then + none + else + (·, queue) <$> groups[next[queue]!]?) + |>.qsort fun (a, i) (b, j) => key a < key b || (key a == key b && i < j) + 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) + if record then + modify (·.push group) state ← ofExcept (runGroup header state group) + for instr in group.instructions do + match instr with + | .action .. => actions := actions + 1 + | _ => observations := observations + 1 next := next.modify queue (· + 1) - let instructions := - queues.zipIdx.flatMap - fun (groups, queue) => (groups.extract 0 next[queue]!).flatMap (·.instructions) - let actions := (instructions.filter (· matches .action ..)).size - return { ran := next, actions, observations := instructions.size - actions } + return { ran := next, actions, observations } end Consensus.Replay diff --git a/lean/consensus/Consensus/Replay/Reduction.lean b/lean/consensus/Consensus/Replay/Reduction.lean index b61fa455c4bc..277f9e4b43ec 100644 --- a/lean/consensus/Consensus/Replay/Reduction.lean +++ b/lean/consensus/Consensus/Replay/Reduction.lean @@ -96,7 +96,8 @@ private def emitAction (event : Event) (rule : String) (step : Step) : Reduction appendInstruction (.action step (event.origin rule)) private def emitObserve (event : Event) (rule : String) : Reduction Unit := - appendInstruction (.observeNodeState event.node event.state (event.origin rule)) + appendInstruction + (.observeNodeState event.node event.state (event.origin rule) event.stateId) private def emitObserveSends (event : Event) (sends : List NativeSend) : Reduction Unit := appendInstruction (.observeSends sends (event.origin "sends")) @@ -403,18 +404,20 @@ private def ruleInitAsBackup : Reduction Unit := do emitAction init "init-as-backup" (.initAsBackup head.node index view) def ruleStep : Reduction Unit := do - -- Recv rules - attempt ruleRecvAppendEntries - <|> attempt ruleRecvAppendEntriesResponse - <|> attempt ruleRecvRequestVote - <|> attempt ruleRecvProposeRequestVote - <|> attempt ruleRecvRequestVoteResponse - -- Async rules - <|> attempt ruleBootstrap - <|> attempt ruleInitAsBackup - <|> attempt ruleAppend - <|> attempt ruleTick - <|> attempt ruleNomination - <|> attempt ruleDrop + let head ← peek + match head.function with + | "tick" => attempt ruleTick + | "recv_append_entries" => attempt ruleRecvAppendEntries + | "recv_append_entries_response" => attempt ruleRecvAppendEntriesResponse + | "recv_request_vote" => attempt ruleRecvRequestVote + | "recv_propose_request_vote" => attempt ruleRecvProposeRequestVote + | "recv_request_vote_response" => attempt ruleRecvRequestVoteResponse + | "replicate" => attempt ruleAppend + | "nomination" => attempt ruleNomination + | "drop_pending_to" => attempt ruleDrop + | "become_leader" => attempt ruleBootstrap + | "init_as_backup" | "add_configuration" | "retired_committed_tx" => + attempt ruleInitAsBackup + | other => failure s!"{head.record.location}: unexpected event {other}" end Consensus.Replay.Reducer diff --git a/lean/consensus/replay/ReplayMain.lean b/lean/consensus/replay/ReplayMain.lean index 4633ea5056a4..113f832fef2e 100644 --- a/lean/consensus/replay/ReplayMain.lean +++ b/lean/consensus/replay/ReplayMain.lean @@ -18,22 +18,24 @@ def main (args : List String) : IO UInt32 := do IO.eprintln s!"unknown option {flags}" return 2 let lenient := flags.contains "--lenient" - let records ← readLog path + let recordSchedule := flags.contains "--schedule" + let events ← readEvents path let reduced := do - let (streams, declared) ← prepareEvents (← records) + let (streams, declared) ← events 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 #[] + (schedule reduced.header reduced.queues lenient recordSchedule).run.run + #[] ( result.map fun (result : Result) => (reduced.watermark result.ran, result), ran ) - if flags.contains "--schedule" then + if recordSchedule then for group in ran do IO.eprintln s!"{group.ts.getD group.m_ts} node '{group.node}' {group.label}" match result with diff --git a/tests/cft_trace_validation.py b/tests/cft_trace_validation.py index 339f57021018..171cdf4b777c 100644 --- a/tests/cft_trace_validation.py +++ b/tests/cft_trace_validation.py @@ -49,10 +49,19 @@ def main(replayer, *directories): for path in pathlib.Path(directory).rglob("*_trace/*.ndjson") if has_cft_events(path) ) + # Schedule largest captures first so long traces overlap with smaller ones. + by_size = sorted(paths, key=lambda path: path.stat().st_size, reverse=True) with concurrent.futures.ThreadPoolExecutor(os.cpu_count()) as pool: - results = list(pool.map(functools.partial(replay, replayer), paths)) + results = dict( + zip( + by_size, + pool.map(functools.partial(replay, replayer), by_size), + strict=True, + ) + ) rejected = 0 - for path, (accepted, output) in zip(paths, results, strict=True): + for path in paths: + accepted, output = results[path] rejected += not accepted print(f"{'OK ' if accepted else 'FAIL'} {path}: {output}") print(f"{len(paths) - rejected} accepted, {rejected} rejected") From 87fd16bb326c9ad8ef02447ee3d04bfadf83cd08 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 25 Nov 2026 16:16:29 +0000 Subject: [PATCH 2/5] Temporary: time ablation variants of the consensus replayer in CI To be removed once the numbers are in the PR description. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/replay-ablation/ablation.py | 97 +++++++++++++ .github/replay-ablation/mkvariants.py | 197 ++++++++++++++++++++++++++ .github/workflows/replay-ablation.yml | 65 +++++++++ 3 files changed, 359 insertions(+) create mode 100644 .github/replay-ablation/ablation.py create mode 100644 .github/replay-ablation/mkvariants.py create mode 100644 .github/workflows/replay-ablation.yml diff --git a/.github/replay-ablation/ablation.py b/.github/replay-ablation/ablation.py new file mode 100644 index 000000000000..c75b2eec91ac --- /dev/null +++ b/.github/replay-ablation/ablation.py @@ -0,0 +1,97 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Build and time ablation variants of the consensus replayer. + +usage: + ablation.py build PATCHES LEAN_CONSENSUS_DIR BINDIR + ablation.py time BINDIR VALIDATOR OLD_VALIDATOR CAPTURES ROUNDS OUT.csv + ablation.py report OUT.csv + +`time` runs the CI step (VALIDATOR BINARY CAPTURES) once per variant per round, with the +variants interleaved, and records wall time, CPU time and peak RSS of the step's process +tree, its exit status, and a hash of its output. +""" +import csv, hashlib, os, pathlib, shutil, statistics, subprocess, sys, tempfile, time + + +def build(patches, lean, bindir): + patches, lean, bindir = map(pathlib.Path, (patches, lean, bindir)) + bindir.mkdir(parents=True, exist_ok=True) + for variant in sorted(patches.iterdir()): + overlay = [p.relative_to(variant) for p in variant.rglob("*.lean")] + saved = {p: (lean / p).read_text() for p in overlay} + try: + for p in overlay: + (lean / p).write_text((variant / p).read_text()) + result = subprocess.run( + ["lake", "build", "--wfail", "consensus-replay"], + cwd=lean, capture_output=True, text=True, check=False, + ) + if result.returncode != 0: + sys.exit(f"{variant.name}:\n" + (result.stdout + result.stderr)[-4000:]) + shutil.copy(lean / ".lake/build/bin/consensus-replay", bindir / variant.name) + finally: + for p, text in saved.items(): + (lean / p).write_text(text) + print(f"built {variant.name}", flush=True) + + +def run(argv): + with tempfile.TemporaryFile() as out: + start = time.monotonic() + pid = os.fork() + if pid == 0: + os.dup2(out.fileno(), 1) + os.dup2(out.fileno(), 2) + os.execvp(argv[0], argv) + _, status, usage = os.wait4(pid, 0) + wall = time.monotonic() - start + out.seek(0) + text = out.read() + return ( + os.waitstatus_to_exitcode(status), + hashlib.sha256(text).hexdigest()[:12], + text.decode(errors="replace").strip().splitlines()[-1:], + wall, + usage.ru_utime + usage.ru_stime, + usage.ru_maxrss // 1024, + ) + + +def timeit(bindir, validator, old_validator, captures, rounds, out): + runs = [(b.name, validator, str(b)) for b in sorted(pathlib.Path(bindir).iterdir())] + runs.append(("no-largest-first", old_validator, str(pathlib.Path(bindir) / "full"))) + with open(out, "a", newline="") as fh: + writer = csv.writer(fh) + for rnd in range(int(rounds)): + for name, script, binary in runs: + code, digest, last, wall, cpu, rss = run(["python3", script, binary, captures]) + writer.writerow([rnd, name, code, digest, f"{wall:.2f}", f"{cpu:.2f}", rss]) + fh.flush() + print(rnd, name, code, digest, f"wall={wall:.1f}s cpu={cpu:.1f}s rss={rss}MB", last, flush=True) + + +def report(out): + rows = {} + for rnd, name, code, digest, wall, cpu, rss in csv.reader(open(out)): + rows.setdefault(name, []).append((int(code), digest, float(wall), float(cpu), int(rss))) + reference = {(code, digest) for code, digest, *_ in rows["full"]} + assert len(reference) == 1, reference + full_wall = statistics.median(r[2] for r in rows["full"]) + print("| Variant | Wall, median (range) / s | vs full | CPU, median / s | Peak RSS / MB | Output |") + print("| --- | --- | --- | --- | --- | --- |") + order = sorted(rows, key=lambda n: (n != "full", n != "unoptimised", -statistics.median(r[2] for r in rows[n]))) + for name in order: + rs = rows[name] + walls = [r[2] for r in rs] + same = {(r[0], r[1]) for r in rs} == reference + print( + f"| `{name}` | {statistics.median(walls):.1f} ({min(walls):.1f}-{max(walls):.1f}) " + f"| {statistics.median(walls) / full_wall:.2f}x | {statistics.median(r[3] for r in rs):.0f} " + f"| {max(r[4] for r in rs)} | {'same' if same else 'DIFFERS'} |" + ) + print(f"\n{len(rows['full'])} runs per variant") + + +if __name__ == "__main__": + {"build": build, "time": timeit, "report": report}[sys.argv[1]](*sys.argv[2:]) diff --git a/.github/replay-ablation/mkvariants.py b/.github/replay-ablation/mkvariants.py new file mode 100644 index 000000000000..178c85b9bd3b --- /dev/null +++ b/.github/replay-ablation/mkvariants.py @@ -0,0 +1,197 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Generate ablation variants of the consensus replayer. + +Each variant is the optimised replayer (FULL) with exactly one optimisation removed, as +files to overlay on lean/consensus. `unoptimised` is the replayer before the change. +usage: mkvariants.py REPO FULL_REV OUTDIR +""" +import pathlib, subprocess, sys + +repo, FULL, outdir = sys.argv[1:] +R = "lean/consensus/Consensus/Replay/" +BASE = "f6d7d21c0" + + +def show(rev, name): + return subprocess.check_output(["git", "-C", repo, "show", f"{rev}:{R}{name}"], text=True) + + +full = {n: show(FULL, n) for n in ("Input.lean", "Interpreter.lean", "Reduction.lean")} +old = {n: show(BASE, n) for n in full} + + +def sub(text, a, b, count=1): + assert text.count(a) == count, (text.count(a), a[:80]) + return text.replace(a, b) + + +def between(text, start, end): + i = text.index(start) + j = text.index(end, i) + return text[i:j] + + +variants = {} + +# (a1) streaming: read the whole file and split it, instead of reading line by line. +t = full["Input.lean"] +t = sub(t, """ let handle ← IO.FS.Handle.mk path .read +""", """ let content ← IO.FS.readFile path + let lines := (content.splitOn "\\n").toArray + let lines := if content.endsWith "\\n" then lines.pop else lines + let mut cursor : Nat := 0 +""") +t = sub(t, """ let raw ← handle.getLine + if raw.isEmpty then + break +""", """ if cursor >= lines.size then + break + let raw := lines[cursor]! + cursor := cursor + 1 +""") +variants["no-streaming"] = {"Input.lean": t} + +# (a2) skipping non-ccf.cft lines before JSON parsing. +t = sub(full["Input.lean"], """ if tag != "ccf.cft" then + .skip + else if""", """ if tag != "ccf.cft" then + .fallback + else if""") +variants["no-tag-skip"] = {"Input.lean": t} + +# (a) whole scanner: every line takes the full JSON parse (implies no msg reuse, no snapshot skip). +t = sub(full["Input.lean"], """private def matchFluentdLine (raw : String) : FastLine := + if !byteEqAt raw 0""", """private def matchFluentdLine (raw : String) : FastLine := + if true || !byteEqAt raw 0""") +variants["no-scanner"] = {"Input.lean": t} + +# (b) reuse of the parsed msg for byte-identical consecutive events (implies no snapshot skip). +t = sub(full["Input.lean"], " if cachedRaw == msgRaw then", " if false && cachedRaw == msgRaw then") +variants["no-msg-reuse"] = {"Input.lean": t} + +# (c) per-pid buckets with qsort and per-node HashMap -> one global merge sort and per-node filter. +t = full["Input.lean"] +body = between(t, "private def buildStreamsFromBuckets", "/--\nOrder each process's records") +new_body = '''private def buildStreamsFromBuckets (buckets : Std.HashMap String (Array BucketEntry)) + : Except String (Array (Array Event) × List String) := do + let keyed : List (String × BucketEntry) := + buckets.toList.flatMap fun (pid, entries) => entries.toList.map (pid, ·) + let keyed := + keyed.mergeSort + fun (p, a) (q, b) => + p < q || (p == q && (a.m_ts < b.m_ts || (a.m_ts == b.m_ts && a.line <= b.line))) + let mut events : Array Event := #[] + let mut pids : Std.HashMap String String := {} + let mut declared : List String := [] + let mut parsedCache : Std.HashMap Nat ParsedMessage := {} + let mut previous : Option (String × Nat × String × Nat) := none + for (pid, entry) in keyed do + let location := s!"{entry.file}:{entry.line}" + if let some (lastPid, lastMts, earlierFile, earlierLine) := previous then + if lastPid == pid && lastMts == entry.m_ts then + throw + s!"{location}: m_ts {entry.m_ts} of pid '{pid}' repeats {earlierFile}:{earlierLine}" + previous := some (pid, entry.m_ts, entry.file, entry.line) + let parsed ← + match entry.stateId.bind (parsedCache[·]?) with + | some cached => pure cached + | none => + let parsed ← (parseMessage entry.message).mapError (s!"{location}: " ++ ·) + if let some id := entry.stateId then + parsedCache := parsedCache.insert id parsed + pure parsed + unless parsed.isCmd do + if let some other := pids[parsed.node]? then + unless other == pid do + throw + s!"{location}: node '{parsed.node}' is traced by pids '{other}' and '{pid}'" + pids := pids.insert parsed.node pid + let record : Record := + { file := entry.file, line := entry.line, value := Json.null } + events := + events.push + { + record + m_ts := entry.m_ts + ts := entry.ts + function := parsed.function + node := parsed.node + message := entry.message + state := parsed.state + stateId := entry.stateId + } + declared := parsed.node :: parsed.extraDeclared ++ declared + let streams := + pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node) + return (streams, declared.mergeSort.eraseDups) + +''' +variants["no-buckets"] = {"Input.lean": sub(t, body, new_body)} + +# (e) skip of an already-verified identical snapshot. +I = full["Interpreter.lean"] +variants["no-snapshot-skip"] = {"Interpreter.lean": sub( + I, " if stateId.isSome && cache.lastVerifiedId == stateId then", + " if false && stateId.isSome && cache.lastVerifiedId == stateId then")} + +# (d1) per-node cache: rebuild the one-pass summary at every observation (implies no snapshot skip). +no_cache = sub(I, """ : Except String ReplayState := do + let self ← header.nodeId node + if self < replay.obsCache.size then""", """ : Except String ReplayState := do + let self ← header.nodeId node + if false && self < replay.obsCache.size then""") +variants["no-obs-cache"] = {"Interpreter.lean": no_cache} + +# (d2) additionally derive the observed fields from the model definitions, as before the change. +start, end = "/-- Compare an action-boundary snapshot with the current model node. -/", "/-- Physical packet coordinates" +old_observe = between(old["Interpreter.lean"], start, end) +t = sub(no_cache, between(no_cache, start, "private def observeStateCached"), old_observe) +variants["no-obs-cache-no-one-pass"] = {"Interpreter.lean": t} + +# (f) node-id HashMap index. +variants["no-node-index"] = {"Interpreter.lean": sub(I, """ ({} : Std.HashMap String NodeID) + { header with nodeIds }""", """ ({} : Std.HashMap String NodeID) + if true then header else { header with nodeIds }""")} + +# (g) scheduler fast path, optional group recording and incremental counters. +loop_new = between(I, " let mut actions : Nat := 0\n let mut observations : Nat := 0\n for _ in [:total] do", "end Consensus.Replay") +loop_old = between(old["Interpreter.lean"], " for _ in [:total] do", "end Consensus.Replay") +loop_old = sub(loop_old, " modify (·.push group)\n", " if record || true then\n modify (·.push group)\n") +variants["no-sched-fast-path"] = {"Interpreter.lean": sub(I, loop_new, loop_old)} + +# empty send observation shortcut. +variants["no-empty-sends-shortcut"] = {"Interpreter.lean": sub(I, """ if sends.isEmpty && replay.queued.isEmpty then + return replay +""", "")} + +# (h) rule dispatch on the head event's function. +Rn, Ro = full["Reduction.lean"], old["Reduction.lean"] +variants["no-rule-dispatch"] = {"Reduction.lean": sub( + Rn, between(Rn, "def ruleStep", "end Consensus.Replay.Reducer"), + between(Ro, "def ruleStep", "end Consensus.Replay.Reducer"))} + +variants = { + name: {"Consensus/Replay/" + f: text for f, text in files.items()} + for name, files in variants.items() +} +variants["unoptimised"] = { + path: subprocess.check_output( + ["git", "-C", repo, "show", f"{BASE}:lean/consensus/{path}"], text=True + ) + for path in [ + "Consensus/Replay/Groups.lean", + "Consensus/Replay/Input.lean", + "Consensus/Replay/Interpreter.lean", + "Consensus/Replay/Reduction.lean", + "replay/ReplayMain.lean", + ] +} +variants["full"] = {} +for name, files in variants.items(): + d = pathlib.Path(outdir) / name + d.mkdir(parents=True, exist_ok=True) + for f, text in files.items(): + (d / f).parent.mkdir(parents=True, exist_ok=True) + (d / f).write_text(text) +print("\n".join(variants)) diff --git a/.github/workflows/replay-ablation.yml b/.github/workflows/replay-ablation.yml new file mode 100644 index 000000000000..9870c647e8fc --- /dev/null +++ b/.github/workflows/replay-ablation.yml @@ -0,0 +1,65 @@ +# Temporary: ablation timing of the consensus replayer optimisations. Remove before merge. +name: Replay ablation (temporary) + +on: + push: + branches: + - cjen1-msft-crispy-system + +permissions: + contents: read + actions: read + +jobs: + ablation: + name: "Consensus replay ablation" + runs-on: ubuntu-26.04 + timeout-minutes: 120 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Install Lean + uses: ./.github/actions/install-lean + + - name: Build variants + run: | + set -euo pipefail + nproc + python3 .github/replay-ablation/mkvariants.py . f799bc5eb "$RUNNER_TEMP/patches" + git show f6d7d21c0:tests/cft_trace_validation.py > "$RUNNER_TEMP/old_validation.py" + python3 .github/replay-ablation/ablation.py build \ + "$RUNNER_TEMP/patches" lean/consensus "$RUNNER_TEMP/bin" + + - name: Download e2e logs of a fixed run + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: logs-azurelinux-virtual-* + path: ${{ runner.temp }}/e2e-logs + run-id: 45581973686 + github-token: ${{ github.token }} + + - name: Time variants + run: | + set -euo pipefail + python3 .github/replay-ablation/ablation.py time "$RUNNER_TEMP/bin" \ + tests/cft_trace_validation.py "$RUNNER_TEMP/old_validation.py" \ + "$RUNNER_TEMP/e2e-logs" 5 "$RUNNER_TEMP/ablation.csv" + + - name: Report + if: ${{ !cancelled() }} + run: | + set -euo pipefail + cat "$RUNNER_TEMP/ablation.csv" + python3 .github/replay-ablation/ablation.py report "$RUNNER_TEMP/ablation.csv" \ + | tee -a "$GITHUB_STEP_SUMMARY" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: ${{ !cancelled() }} + with: + name: replay-ablation + path: ${{ runner.temp }}/ablation.csv From 3bac49a5ae19e3e9fe2ea49226a604db9ae5e077 Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 25 Nov 2026 17:03:59 +0000 Subject: [PATCH 3/5] Remove the temporary consensus replayer ablation job Reverts 87fd16bb3; its timings are in the PR description. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/replay-ablation/ablation.py | 97 ------------- .github/replay-ablation/mkvariants.py | 197 -------------------------- .github/workflows/replay-ablation.yml | 65 --------- 3 files changed, 359 deletions(-) delete mode 100644 .github/replay-ablation/ablation.py delete mode 100644 .github/replay-ablation/mkvariants.py delete mode 100644 .github/workflows/replay-ablation.yml diff --git a/.github/replay-ablation/ablation.py b/.github/replay-ablation/ablation.py deleted file mode 100644 index c75b2eec91ac..000000000000 --- a/.github/replay-ablation/ablation.py +++ /dev/null @@ -1,97 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the Apache 2.0 License. -"""Build and time ablation variants of the consensus replayer. - -usage: - ablation.py build PATCHES LEAN_CONSENSUS_DIR BINDIR - ablation.py time BINDIR VALIDATOR OLD_VALIDATOR CAPTURES ROUNDS OUT.csv - ablation.py report OUT.csv - -`time` runs the CI step (VALIDATOR BINARY CAPTURES) once per variant per round, with the -variants interleaved, and records wall time, CPU time and peak RSS of the step's process -tree, its exit status, and a hash of its output. -""" -import csv, hashlib, os, pathlib, shutil, statistics, subprocess, sys, tempfile, time - - -def build(patches, lean, bindir): - patches, lean, bindir = map(pathlib.Path, (patches, lean, bindir)) - bindir.mkdir(parents=True, exist_ok=True) - for variant in sorted(patches.iterdir()): - overlay = [p.relative_to(variant) for p in variant.rglob("*.lean")] - saved = {p: (lean / p).read_text() for p in overlay} - try: - for p in overlay: - (lean / p).write_text((variant / p).read_text()) - result = subprocess.run( - ["lake", "build", "--wfail", "consensus-replay"], - cwd=lean, capture_output=True, text=True, check=False, - ) - if result.returncode != 0: - sys.exit(f"{variant.name}:\n" + (result.stdout + result.stderr)[-4000:]) - shutil.copy(lean / ".lake/build/bin/consensus-replay", bindir / variant.name) - finally: - for p, text in saved.items(): - (lean / p).write_text(text) - print(f"built {variant.name}", flush=True) - - -def run(argv): - with tempfile.TemporaryFile() as out: - start = time.monotonic() - pid = os.fork() - if pid == 0: - os.dup2(out.fileno(), 1) - os.dup2(out.fileno(), 2) - os.execvp(argv[0], argv) - _, status, usage = os.wait4(pid, 0) - wall = time.monotonic() - start - out.seek(0) - text = out.read() - return ( - os.waitstatus_to_exitcode(status), - hashlib.sha256(text).hexdigest()[:12], - text.decode(errors="replace").strip().splitlines()[-1:], - wall, - usage.ru_utime + usage.ru_stime, - usage.ru_maxrss // 1024, - ) - - -def timeit(bindir, validator, old_validator, captures, rounds, out): - runs = [(b.name, validator, str(b)) for b in sorted(pathlib.Path(bindir).iterdir())] - runs.append(("no-largest-first", old_validator, str(pathlib.Path(bindir) / "full"))) - with open(out, "a", newline="") as fh: - writer = csv.writer(fh) - for rnd in range(int(rounds)): - for name, script, binary in runs: - code, digest, last, wall, cpu, rss = run(["python3", script, binary, captures]) - writer.writerow([rnd, name, code, digest, f"{wall:.2f}", f"{cpu:.2f}", rss]) - fh.flush() - print(rnd, name, code, digest, f"wall={wall:.1f}s cpu={cpu:.1f}s rss={rss}MB", last, flush=True) - - -def report(out): - rows = {} - for rnd, name, code, digest, wall, cpu, rss in csv.reader(open(out)): - rows.setdefault(name, []).append((int(code), digest, float(wall), float(cpu), int(rss))) - reference = {(code, digest) for code, digest, *_ in rows["full"]} - assert len(reference) == 1, reference - full_wall = statistics.median(r[2] for r in rows["full"]) - print("| Variant | Wall, median (range) / s | vs full | CPU, median / s | Peak RSS / MB | Output |") - print("| --- | --- | --- | --- | --- | --- |") - order = sorted(rows, key=lambda n: (n != "full", n != "unoptimised", -statistics.median(r[2] for r in rows[n]))) - for name in order: - rs = rows[name] - walls = [r[2] for r in rs] - same = {(r[0], r[1]) for r in rs} == reference - print( - f"| `{name}` | {statistics.median(walls):.1f} ({min(walls):.1f}-{max(walls):.1f}) " - f"| {statistics.median(walls) / full_wall:.2f}x | {statistics.median(r[3] for r in rs):.0f} " - f"| {max(r[4] for r in rs)} | {'same' if same else 'DIFFERS'} |" - ) - print(f"\n{len(rows['full'])} runs per variant") - - -if __name__ == "__main__": - {"build": build, "time": timeit, "report": report}[sys.argv[1]](*sys.argv[2:]) diff --git a/.github/replay-ablation/mkvariants.py b/.github/replay-ablation/mkvariants.py deleted file mode 100644 index 178c85b9bd3b..000000000000 --- a/.github/replay-ablation/mkvariants.py +++ /dev/null @@ -1,197 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the Apache 2.0 License. -"""Generate ablation variants of the consensus replayer. - -Each variant is the optimised replayer (FULL) with exactly one optimisation removed, as -files to overlay on lean/consensus. `unoptimised` is the replayer before the change. -usage: mkvariants.py REPO FULL_REV OUTDIR -""" -import pathlib, subprocess, sys - -repo, FULL, outdir = sys.argv[1:] -R = "lean/consensus/Consensus/Replay/" -BASE = "f6d7d21c0" - - -def show(rev, name): - return subprocess.check_output(["git", "-C", repo, "show", f"{rev}:{R}{name}"], text=True) - - -full = {n: show(FULL, n) for n in ("Input.lean", "Interpreter.lean", "Reduction.lean")} -old = {n: show(BASE, n) for n in full} - - -def sub(text, a, b, count=1): - assert text.count(a) == count, (text.count(a), a[:80]) - return text.replace(a, b) - - -def between(text, start, end): - i = text.index(start) - j = text.index(end, i) - return text[i:j] - - -variants = {} - -# (a1) streaming: read the whole file and split it, instead of reading line by line. -t = full["Input.lean"] -t = sub(t, """ let handle ← IO.FS.Handle.mk path .read -""", """ let content ← IO.FS.readFile path - let lines := (content.splitOn "\\n").toArray - let lines := if content.endsWith "\\n" then lines.pop else lines - let mut cursor : Nat := 0 -""") -t = sub(t, """ let raw ← handle.getLine - if raw.isEmpty then - break -""", """ if cursor >= lines.size then - break - let raw := lines[cursor]! - cursor := cursor + 1 -""") -variants["no-streaming"] = {"Input.lean": t} - -# (a2) skipping non-ccf.cft lines before JSON parsing. -t = sub(full["Input.lean"], """ if tag != "ccf.cft" then - .skip - else if""", """ if tag != "ccf.cft" then - .fallback - else if""") -variants["no-tag-skip"] = {"Input.lean": t} - -# (a) whole scanner: every line takes the full JSON parse (implies no msg reuse, no snapshot skip). -t = sub(full["Input.lean"], """private def matchFluentdLine (raw : String) : FastLine := - if !byteEqAt raw 0""", """private def matchFluentdLine (raw : String) : FastLine := - if true || !byteEqAt raw 0""") -variants["no-scanner"] = {"Input.lean": t} - -# (b) reuse of the parsed msg for byte-identical consecutive events (implies no snapshot skip). -t = sub(full["Input.lean"], " if cachedRaw == msgRaw then", " if false && cachedRaw == msgRaw then") -variants["no-msg-reuse"] = {"Input.lean": t} - -# (c) per-pid buckets with qsort and per-node HashMap -> one global merge sort and per-node filter. -t = full["Input.lean"] -body = between(t, "private def buildStreamsFromBuckets", "/--\nOrder each process's records") -new_body = '''private def buildStreamsFromBuckets (buckets : Std.HashMap String (Array BucketEntry)) - : Except String (Array (Array Event) × List String) := do - let keyed : List (String × BucketEntry) := - buckets.toList.flatMap fun (pid, entries) => entries.toList.map (pid, ·) - let keyed := - keyed.mergeSort - fun (p, a) (q, b) => - p < q || (p == q && (a.m_ts < b.m_ts || (a.m_ts == b.m_ts && a.line <= b.line))) - let mut events : Array Event := #[] - let mut pids : Std.HashMap String String := {} - let mut declared : List String := [] - let mut parsedCache : Std.HashMap Nat ParsedMessage := {} - let mut previous : Option (String × Nat × String × Nat) := none - for (pid, entry) in keyed do - let location := s!"{entry.file}:{entry.line}" - if let some (lastPid, lastMts, earlierFile, earlierLine) := previous then - if lastPid == pid && lastMts == entry.m_ts then - throw - s!"{location}: m_ts {entry.m_ts} of pid '{pid}' repeats {earlierFile}:{earlierLine}" - previous := some (pid, entry.m_ts, entry.file, entry.line) - let parsed ← - match entry.stateId.bind (parsedCache[·]?) with - | some cached => pure cached - | none => - let parsed ← (parseMessage entry.message).mapError (s!"{location}: " ++ ·) - if let some id := entry.stateId then - parsedCache := parsedCache.insert id parsed - pure parsed - unless parsed.isCmd do - if let some other := pids[parsed.node]? then - unless other == pid do - throw - s!"{location}: node '{parsed.node}' is traced by pids '{other}' and '{pid}'" - pids := pids.insert parsed.node pid - let record : Record := - { file := entry.file, line := entry.line, value := Json.null } - events := - events.push - { - record - m_ts := entry.m_ts - ts := entry.ts - function := parsed.function - node := parsed.node - message := entry.message - state := parsed.state - stateId := entry.stateId - } - declared := parsed.node :: parsed.extraDeclared ++ declared - let streams := - pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node) - return (streams, declared.mergeSort.eraseDups) - -''' -variants["no-buckets"] = {"Input.lean": sub(t, body, new_body)} - -# (e) skip of an already-verified identical snapshot. -I = full["Interpreter.lean"] -variants["no-snapshot-skip"] = {"Interpreter.lean": sub( - I, " if stateId.isSome && cache.lastVerifiedId == stateId then", - " if false && stateId.isSome && cache.lastVerifiedId == stateId then")} - -# (d1) per-node cache: rebuild the one-pass summary at every observation (implies no snapshot skip). -no_cache = sub(I, """ : Except String ReplayState := do - let self ← header.nodeId node - if self < replay.obsCache.size then""", """ : Except String ReplayState := do - let self ← header.nodeId node - if false && self < replay.obsCache.size then""") -variants["no-obs-cache"] = {"Interpreter.lean": no_cache} - -# (d2) additionally derive the observed fields from the model definitions, as before the change. -start, end = "/-- Compare an action-boundary snapshot with the current model node. -/", "/-- Physical packet coordinates" -old_observe = between(old["Interpreter.lean"], start, end) -t = sub(no_cache, between(no_cache, start, "private def observeStateCached"), old_observe) -variants["no-obs-cache-no-one-pass"] = {"Interpreter.lean": t} - -# (f) node-id HashMap index. -variants["no-node-index"] = {"Interpreter.lean": sub(I, """ ({} : Std.HashMap String NodeID) - { header with nodeIds }""", """ ({} : Std.HashMap String NodeID) - if true then header else { header with nodeIds }""")} - -# (g) scheduler fast path, optional group recording and incremental counters. -loop_new = between(I, " let mut actions : Nat := 0\n let mut observations : Nat := 0\n for _ in [:total] do", "end Consensus.Replay") -loop_old = between(old["Interpreter.lean"], " for _ in [:total] do", "end Consensus.Replay") -loop_old = sub(loop_old, " modify (·.push group)\n", " if record || true then\n modify (·.push group)\n") -variants["no-sched-fast-path"] = {"Interpreter.lean": sub(I, loop_new, loop_old)} - -# empty send observation shortcut. -variants["no-empty-sends-shortcut"] = {"Interpreter.lean": sub(I, """ if sends.isEmpty && replay.queued.isEmpty then - return replay -""", "")} - -# (h) rule dispatch on the head event's function. -Rn, Ro = full["Reduction.lean"], old["Reduction.lean"] -variants["no-rule-dispatch"] = {"Reduction.lean": sub( - Rn, between(Rn, "def ruleStep", "end Consensus.Replay.Reducer"), - between(Ro, "def ruleStep", "end Consensus.Replay.Reducer"))} - -variants = { - name: {"Consensus/Replay/" + f: text for f, text in files.items()} - for name, files in variants.items() -} -variants["unoptimised"] = { - path: subprocess.check_output( - ["git", "-C", repo, "show", f"{BASE}:lean/consensus/{path}"], text=True - ) - for path in [ - "Consensus/Replay/Groups.lean", - "Consensus/Replay/Input.lean", - "Consensus/Replay/Interpreter.lean", - "Consensus/Replay/Reduction.lean", - "replay/ReplayMain.lean", - ] -} -variants["full"] = {} -for name, files in variants.items(): - d = pathlib.Path(outdir) / name - d.mkdir(parents=True, exist_ok=True) - for f, text in files.items(): - (d / f).parent.mkdir(parents=True, exist_ok=True) - (d / f).write_text(text) -print("\n".join(variants)) diff --git a/.github/workflows/replay-ablation.yml b/.github/workflows/replay-ablation.yml deleted file mode 100644 index 9870c647e8fc..000000000000 --- a/.github/workflows/replay-ablation.yml +++ /dev/null @@ -1,65 +0,0 @@ -# Temporary: ablation timing of the consensus replayer optimisations. Remove before merge. -name: Replay ablation (temporary) - -on: - push: - branches: - - cjen1-msft-crispy-system - -permissions: - contents: read - actions: read - -jobs: - ablation: - name: "Consensus replay ablation" - runs-on: ubuntu-26.04 - timeout-minutes: 120 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - - - name: Install Lean - uses: ./.github/actions/install-lean - - - name: Build variants - run: | - set -euo pipefail - nproc - python3 .github/replay-ablation/mkvariants.py . f799bc5eb "$RUNNER_TEMP/patches" - git show f6d7d21c0:tests/cft_trace_validation.py > "$RUNNER_TEMP/old_validation.py" - python3 .github/replay-ablation/ablation.py build \ - "$RUNNER_TEMP/patches" lean/consensus "$RUNNER_TEMP/bin" - - - name: Download e2e logs of a fixed run - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: logs-azurelinux-virtual-* - path: ${{ runner.temp }}/e2e-logs - run-id: 45581973686 - github-token: ${{ github.token }} - - - name: Time variants - run: | - set -euo pipefail - python3 .github/replay-ablation/ablation.py time "$RUNNER_TEMP/bin" \ - tests/cft_trace_validation.py "$RUNNER_TEMP/old_validation.py" \ - "$RUNNER_TEMP/e2e-logs" 5 "$RUNNER_TEMP/ablation.csv" - - - name: Report - if: ${{ !cancelled() }} - run: | - set -euo pipefail - cat "$RUNNER_TEMP/ablation.csv" - python3 .github/replay-ablation/ablation.py report "$RUNNER_TEMP/ablation.csv" \ - | tee -a "$GITHUB_STEP_SUMMARY" - - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: ${{ !cancelled() }} - with: - name: replay-ablation - path: ${{ runner.temp }}/ablation.csv From dd15fe62b0587f326ed21206034f9b845b834f7a Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 25 Nov 2026 17:22:09 +0000 Subject: [PATCH 4/5] Temporary: time cumulative variants of the consensus replayer in CI To be removed once the numbers are in the PR description. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/replay-ablation/ablation.py | 105 ++++++++++++ .github/replay-ablation/mkvariants.py | 226 ++++++++++++++++++++++++++ .github/workflows/replay-ablation.yml | 65 ++++++++ 3 files changed, 396 insertions(+) create mode 100644 .github/replay-ablation/ablation.py create mode 100644 .github/replay-ablation/mkvariants.py create mode 100644 .github/workflows/replay-ablation.yml diff --git a/.github/replay-ablation/ablation.py b/.github/replay-ablation/ablation.py new file mode 100644 index 000000000000..700f100446aa --- /dev/null +++ b/.github/replay-ablation/ablation.py @@ -0,0 +1,105 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Build and time ablation variants of the consensus replayer. + +usage: + ablation.py build PATCHES LEAN_CONSENSUS_DIR BINDIR + ablation.py time BINDIR VALIDATOR OLD_VALIDATOR CAPTURES ROUNDS OUT.csv + ablation.py report OUT.csv + +Each variant uses the validator named by its VALIDATOR file (old: before the change). + +`time` runs the CI step (VALIDATOR BINARY CAPTURES) once per variant per round, with the +variants interleaved, and records wall time, CPU time and peak RSS of the step's process +tree, its exit status, and a hash of its output. +""" +import csv, hashlib, os, pathlib, shutil, statistics, subprocess, sys, tempfile, time + + +def build(patches, lean, bindir): + patches, lean, bindir = map(pathlib.Path, (patches, lean, bindir)) + bindir.mkdir(parents=True, exist_ok=True) + for variant in sorted(patches.iterdir()): + overlay = [p.relative_to(variant) for p in variant.rglob("*.lean")] + saved = {p: (lean / p).read_text() for p in overlay} + try: + for p in overlay: + (lean / p).write_text((variant / p).read_text()) + result = subprocess.run( + ["lake", "build", "--wfail", "consensus-replay"], + cwd=lean, capture_output=True, text=True, check=False, + ) + if result.returncode != 0: + sys.exit(f"{variant.name}:\n" + (result.stdout + result.stderr)[-4000:]) + shutil.copy(lean / ".lake/build/bin/consensus-replay", bindir / variant.name) + shutil.copy(variant / "VALIDATOR", bindir / (variant.name + ".validator")) + finally: + for p, text in saved.items(): + (lean / p).write_text(text) + print(f"built {variant.name}", flush=True) + + +def run(argv): + with tempfile.TemporaryFile() as out: + start = time.monotonic() + pid = os.fork() + if pid == 0: + os.dup2(out.fileno(), 1) + os.dup2(out.fileno(), 2) + os.execvp(argv[0], argv) + _, status, usage = os.wait4(pid, 0) + wall = time.monotonic() - start + out.seek(0) + text = out.read() + return ( + os.waitstatus_to_exitcode(status), + hashlib.sha256(text).hexdigest()[:12], + text.decode(errors="replace").strip().splitlines()[-1:], + wall, + usage.ru_utime + usage.ru_stime, + usage.ru_maxrss // 1024, + ) + + +def timeit(bindir, validator, old_validator, captures, rounds, out): + scripts = {"new": validator, "old": old_validator} + runs = [ + (b.name, scripts[b.with_name(b.name + ".validator").read_text()], str(b)) + for b in sorted(pathlib.Path(bindir).iterdir()) + if b.suffix != ".validator" + ] + with open(out, "a", newline="") as fh: + writer = csv.writer(fh) + for rnd in range(int(rounds)): + for name, script, binary in runs: + code, digest, last, wall, cpu, rss = run(["python3", script, binary, captures]) + writer.writerow([rnd, name, code, digest, f"{wall:.2f}", f"{cpu:.2f}", rss]) + fh.flush() + print(rnd, name, code, digest, f"wall={wall:.1f}s cpu={cpu:.1f}s rss={rss}MB", last, flush=True) + + +def report(out): + rows = {} + for rnd, name, code, digest, wall, cpu, rss in csv.reader(open(out)): + rows.setdefault(name, []).append((int(code), digest, float(wall), float(cpu), int(rss))) + names = sorted(rows) + outputs = {(r[0], r[1]) for rs in rows.values() for r in rs} + print("| Variant | Wall, median (range) / s | Gain over previous / s | Gain over original / s | CPU, median / s | Peak RSS / MB |") + print("| --- | --- | --- | --- | --- | --- |") + original = previous = None + for name in names: + rs = rows[name] + walls = [r[2] for r in rs] + wall = statistics.median(walls) + original = wall if original is None else original + step = "" if previous is None else f"{previous - wall:.1f}" + print( + f"| `{name}` | {wall:.1f} ({min(walls):.1f}-{max(walls):.1f}) | {step} " + f"| {original - wall:.1f} | {statistics.median(r[3] for r in rs):.0f} | {max(r[4] for r in rs)} |" + ) + previous = wall + print(f"\n{len(rows[names[0]])} runs per variant; distinct (exit status, output) pairs: {len(outputs)} {sorted(outputs)}") + + +if __name__ == "__main__": + {"build": build, "time": timeit, "report": report}[sys.argv[1]](*sys.argv[2:]) diff --git a/.github/replay-ablation/mkvariants.py b/.github/replay-ablation/mkvariants.py new file mode 100644 index 000000000000..2e982180f29e --- /dev/null +++ b/.github/replay-ablation/mkvariants.py @@ -0,0 +1,226 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the Apache 2.0 License. +"""Generate ablation variants of the consensus replayer. + +Cumulative variants: the replayer before the change (`00-original`), then the optimisations +added one at a time in ORDER, each variant including all earlier ones, ending at FULL. +Variant k is FULL with the optimisations after k removed, as files to overlay on +lean/consensus, plus a VALIDATOR file naming the tests/cft_trace_validation.py to use. +usage: mkvariants.py REPO FULL_REV OUTDIR +""" +import pathlib, subprocess, sys + +repo, FULL, outdir = sys.argv[1:] +R = "lean/consensus/Consensus/Replay/" +BASE = "f6d7d21c0" + + +def show(rev, name): + return subprocess.check_output(["git", "-C", repo, "show", f"{rev}:{R}{name}"], text=True) + + +full = {n: show(FULL, n) for n in ("Input.lean", "Interpreter.lean", "Reduction.lean")} +old = {n: show(BASE, n) for n in full} + + +def sub(text, a, b, count=1): + assert text.count(a) == count, (text.count(a), a[:80]) + return text.replace(a, b) + + +def between(text, start, end): + i = text.index(start) + j = text.index(end, i) + return text[i:j] + + +new_body = '''private def buildStreamsFromBuckets (buckets : Std.HashMap String (Array BucketEntry)) + : Except String (Array (Array Event) × List String) := do + let keyed : List (String × BucketEntry) := + buckets.toList.flatMap fun (pid, entries) => entries.toList.map (pid, ·) + let keyed := + keyed.mergeSort + fun (p, a) (q, b) => + p < q || (p == q && (a.m_ts < b.m_ts || (a.m_ts == b.m_ts && a.line <= b.line))) + let mut events : Array Event := #[] + let mut pids : Std.HashMap String String := {} + let mut declared : List String := [] + let mut parsedCache : Std.HashMap Nat ParsedMessage := {} + let mut previous : Option (String × Nat × String × Nat) := none + for (pid, entry) in keyed do + let location := s!"{entry.file}:{entry.line}" + if let some (lastPid, lastMts, earlierFile, earlierLine) := previous then + if lastPid == pid && lastMts == entry.m_ts then + throw + s!"{location}: m_ts {entry.m_ts} of pid '{pid}' repeats {earlierFile}:{earlierLine}" + previous := some (pid, entry.m_ts, entry.file, entry.line) + let parsed ← + match entry.stateId.bind (parsedCache[·]?) with + | some cached => pure cached + | none => + let parsed ← (parseMessage entry.message).mapError (s!"{location}: " ++ ·) + if let some id := entry.stateId then + parsedCache := parsedCache.insert id parsed + pure parsed + unless parsed.isCmd do + if let some other := pids[parsed.node]? then + unless other == pid do + throw + s!"{location}: node '{parsed.node}' is traced by pids '{other}' and '{pid}'" + pids := pids.insert parsed.node pid + let record : Record := + { file := entry.file, line := entry.line, value := Json.null } + events := + events.push + { + record + m_ts := entry.m_ts + ts := entry.ts + function := parsed.function + node := parsed.node + message := entry.message + state := parsed.state + stateId := entry.stateId + } + declared := parsed.node :: parsed.extraDeclared ++ declared + let streams := + pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node) + return (streams, declared.mergeSort.eraseDups) + +''' + +OBSERVE_START = "/-- Compare an action-boundary snapshot with the current model node. -/" + + +def rm_streaming(t): + t = sub(t, """ let handle ← IO.FS.Handle.mk path .read +""", """ let content ← IO.FS.readFile path + let lines := (content.splitOn "\\n").toArray + let lines := if content.endsWith "\\n" then lines.pop else lines + let mut cursor : Nat := 0 +""") + return sub(t, """ let raw ← handle.getLine + if raw.isEmpty then + break +""", """ if cursor >= lines.size then + break + let raw := lines[cursor]! + cursor := cursor + 1 +""") + + +def rm_tag_skip(t): + return sub(t, """ if tag != "ccf.cft" then + .skip + else if""", """ if tag != "ccf.cft" then + .fallback + else if""") + + +def rm_scanner(t): + return sub(t, """private def matchFluentdLine (raw : String) : FastLine := + if !byteEqAt raw 0""", """private def matchFluentdLine (raw : String) : FastLine := + if true || !byteEqAt raw 0""") + + +def rm_msg_reuse(t): + return sub(t, " if cachedRaw == msgRaw then", " if false && cachedRaw == msgRaw then") + + +def rm_buckets(t): + return sub(t, between(t, "private def buildStreamsFromBuckets", "/--\nOrder each process's records"), new_body) + + +def rm_snapshot_skip(t): + return sub(t, " if stateId.isSome && cache.lastVerifiedId == stateId then", + " if false && stateId.isSome && cache.lastVerifiedId == stateId then") + + +def rm_obs_cache(t): + return sub(t, """ : Except String ReplayState := do + let self ← header.nodeId node + if self < replay.obsCache.size then""", """ : Except String ReplayState := do + let self ← header.nodeId node + if false && self < replay.obsCache.size then""") + + +def rm_one_pass(t): + old_observe = between(old["Interpreter.lean"], OBSERVE_START, "/-- Physical packet coordinates") + return sub(t, between(t, OBSERVE_START, "private def observeStateCached"), old_observe) + + +def rm_node_index(t): + return sub(t, """ ({} : Std.HashMap String NodeID) + { header with nodeIds }""", """ ({} : Std.HashMap String NodeID) + if true then header else { header with nodeIds }""") + + +def rm_sched_fast_path(t): + loop_new = between(t, " let mut actions : Nat := 0\n let mut observations : Nat := 0\n for _ in [:total] do", "end Consensus.Replay") + loop_old = between(old["Interpreter.lean"], " for _ in [:total] do", "end Consensus.Replay") + loop_old = sub(loop_old, " modify (·.push group)\n", " if record || true then\n modify (·.push group)\n") + return sub(t, loop_new, loop_old) + + +def rm_empty_sends(t): + return sub(t, """ if sends.isEmpty && replay.queued.isEmpty then + return replay +""", "") + + +def rm_rule_dispatch(t): + return sub(t, between(t, "def ruleStep", "end Consensus.Replay.Reducer"), + between(old["Reduction.lean"], "def ruleStep", "end Consensus.Replay.Reducer")) + + +# (name, file, removal). A step's prerequisites come before it; otherwise largest gain first. +ORDER = [ + ("one-pass-summary", "Interpreter.lean", rm_one_pass), + ("obs-cache", "Interpreter.lean", rm_obs_cache), + ("line-scanner", "Input.lean", rm_scanner), + ("msg-reuse", "Input.lean", rm_msg_reuse), + ("snapshot-skip", "Interpreter.lean", rm_snapshot_skip), + ("rule-dispatch", "Reduction.lean", rm_rule_dispatch), + ("streaming", "Input.lean", rm_streaming), + ("sched-fast-path", "Interpreter.lean", rm_sched_fast_path), + ("largest-first", None, None), + ("buckets", "Input.lean", rm_buckets), + ("tag-skip", "Input.lean", rm_tag_skip), + ("empty-sends-shortcut", "Interpreter.lean", rm_empty_sends), + ("node-index", "Interpreter.lean", rm_node_index), +] + +out = pathlib.Path(outdir) + + +def write(name, files, validator): + d = out / name + for f, text in files.items(): + (d / f).parent.mkdir(parents=True, exist_ok=True) + (d / f).write_text(text) + d.mkdir(parents=True, exist_ok=True) + (d / "VALIDATOR").write_text(validator) + print(name, validator, sorted(files)) + + +write("00-original", { + path: subprocess.check_output(["git", "-C", repo, "show", f"{BASE}:lean/consensus/{path}"], text=True) + for path in [ + "Consensus/Replay/Groups.lean", + "Consensus/Replay/Input.lean", + "Consensus/Replay/Interpreter.lean", + "Consensus/Replay/Reduction.lean", + "replay/ReplayMain.lean", + ] +}, "old") +# k = 0 is FULL with every optimisation removed; k = len(ORDER) is FULL. +for k in range(len(ORDER) + 1): + texts = {} + validator = "old" + for i, (name, f, removal) in enumerate(ORDER): + if f is None: + validator = "new" if i < k else "old" + elif i >= k: + texts[f] = removal(texts.get(f, full[f])) + label = "all-removed" if k == 0 else "plus-" + ORDER[k - 1][0] + write(f"{k + 1:02d}-{label}", {"Consensus/Replay/" + f: t for f, t in texts.items()}, validator) diff --git a/.github/workflows/replay-ablation.yml b/.github/workflows/replay-ablation.yml new file mode 100644 index 000000000000..9870c647e8fc --- /dev/null +++ b/.github/workflows/replay-ablation.yml @@ -0,0 +1,65 @@ +# Temporary: ablation timing of the consensus replayer optimisations. Remove before merge. +name: Replay ablation (temporary) + +on: + push: + branches: + - cjen1-msft-crispy-system + +permissions: + contents: read + actions: read + +jobs: + ablation: + name: "Consensus replay ablation" + runs-on: ubuntu-26.04 + timeout-minutes: 120 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + + - name: Install Lean + uses: ./.github/actions/install-lean + + - name: Build variants + run: | + set -euo pipefail + nproc + python3 .github/replay-ablation/mkvariants.py . f799bc5eb "$RUNNER_TEMP/patches" + git show f6d7d21c0:tests/cft_trace_validation.py > "$RUNNER_TEMP/old_validation.py" + python3 .github/replay-ablation/ablation.py build \ + "$RUNNER_TEMP/patches" lean/consensus "$RUNNER_TEMP/bin" + + - name: Download e2e logs of a fixed run + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: logs-azurelinux-virtual-* + path: ${{ runner.temp }}/e2e-logs + run-id: 45581973686 + github-token: ${{ github.token }} + + - name: Time variants + run: | + set -euo pipefail + python3 .github/replay-ablation/ablation.py time "$RUNNER_TEMP/bin" \ + tests/cft_trace_validation.py "$RUNNER_TEMP/old_validation.py" \ + "$RUNNER_TEMP/e2e-logs" 5 "$RUNNER_TEMP/ablation.csv" + + - name: Report + if: ${{ !cancelled() }} + run: | + set -euo pipefail + cat "$RUNNER_TEMP/ablation.csv" + python3 .github/replay-ablation/ablation.py report "$RUNNER_TEMP/ablation.csv" \ + | tee -a "$GITHUB_STEP_SUMMARY" + + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: ${{ !cancelled() }} + with: + name: replay-ablation + path: ${{ runner.temp }}/ablation.csv From 84e807e703f1acd7926a149361f5e6a495bd05bb Mon Sep 17 00:00:00 2001 From: cjen1-msft Date: Wed, 25 Nov 2026 18:16:32 +0000 Subject: [PATCH 5/5] Remove the temporary consensus replayer ablation job Reverts dd15fe62b; its timings are in the PR description. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .github/replay-ablation/ablation.py | 105 ------------ .github/replay-ablation/mkvariants.py | 226 -------------------------- .github/workflows/replay-ablation.yml | 65 -------- 3 files changed, 396 deletions(-) delete mode 100644 .github/replay-ablation/ablation.py delete mode 100644 .github/replay-ablation/mkvariants.py delete mode 100644 .github/workflows/replay-ablation.yml diff --git a/.github/replay-ablation/ablation.py b/.github/replay-ablation/ablation.py deleted file mode 100644 index 700f100446aa..000000000000 --- a/.github/replay-ablation/ablation.py +++ /dev/null @@ -1,105 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the Apache 2.0 License. -"""Build and time ablation variants of the consensus replayer. - -usage: - ablation.py build PATCHES LEAN_CONSENSUS_DIR BINDIR - ablation.py time BINDIR VALIDATOR OLD_VALIDATOR CAPTURES ROUNDS OUT.csv - ablation.py report OUT.csv - -Each variant uses the validator named by its VALIDATOR file (old: before the change). - -`time` runs the CI step (VALIDATOR BINARY CAPTURES) once per variant per round, with the -variants interleaved, and records wall time, CPU time and peak RSS of the step's process -tree, its exit status, and a hash of its output. -""" -import csv, hashlib, os, pathlib, shutil, statistics, subprocess, sys, tempfile, time - - -def build(patches, lean, bindir): - patches, lean, bindir = map(pathlib.Path, (patches, lean, bindir)) - bindir.mkdir(parents=True, exist_ok=True) - for variant in sorted(patches.iterdir()): - overlay = [p.relative_to(variant) for p in variant.rglob("*.lean")] - saved = {p: (lean / p).read_text() for p in overlay} - try: - for p in overlay: - (lean / p).write_text((variant / p).read_text()) - result = subprocess.run( - ["lake", "build", "--wfail", "consensus-replay"], - cwd=lean, capture_output=True, text=True, check=False, - ) - if result.returncode != 0: - sys.exit(f"{variant.name}:\n" + (result.stdout + result.stderr)[-4000:]) - shutil.copy(lean / ".lake/build/bin/consensus-replay", bindir / variant.name) - shutil.copy(variant / "VALIDATOR", bindir / (variant.name + ".validator")) - finally: - for p, text in saved.items(): - (lean / p).write_text(text) - print(f"built {variant.name}", flush=True) - - -def run(argv): - with tempfile.TemporaryFile() as out: - start = time.monotonic() - pid = os.fork() - if pid == 0: - os.dup2(out.fileno(), 1) - os.dup2(out.fileno(), 2) - os.execvp(argv[0], argv) - _, status, usage = os.wait4(pid, 0) - wall = time.monotonic() - start - out.seek(0) - text = out.read() - return ( - os.waitstatus_to_exitcode(status), - hashlib.sha256(text).hexdigest()[:12], - text.decode(errors="replace").strip().splitlines()[-1:], - wall, - usage.ru_utime + usage.ru_stime, - usage.ru_maxrss // 1024, - ) - - -def timeit(bindir, validator, old_validator, captures, rounds, out): - scripts = {"new": validator, "old": old_validator} - runs = [ - (b.name, scripts[b.with_name(b.name + ".validator").read_text()], str(b)) - for b in sorted(pathlib.Path(bindir).iterdir()) - if b.suffix != ".validator" - ] - with open(out, "a", newline="") as fh: - writer = csv.writer(fh) - for rnd in range(int(rounds)): - for name, script, binary in runs: - code, digest, last, wall, cpu, rss = run(["python3", script, binary, captures]) - writer.writerow([rnd, name, code, digest, f"{wall:.2f}", f"{cpu:.2f}", rss]) - fh.flush() - print(rnd, name, code, digest, f"wall={wall:.1f}s cpu={cpu:.1f}s rss={rss}MB", last, flush=True) - - -def report(out): - rows = {} - for rnd, name, code, digest, wall, cpu, rss in csv.reader(open(out)): - rows.setdefault(name, []).append((int(code), digest, float(wall), float(cpu), int(rss))) - names = sorted(rows) - outputs = {(r[0], r[1]) for rs in rows.values() for r in rs} - print("| Variant | Wall, median (range) / s | Gain over previous / s | Gain over original / s | CPU, median / s | Peak RSS / MB |") - print("| --- | --- | --- | --- | --- | --- |") - original = previous = None - for name in names: - rs = rows[name] - walls = [r[2] for r in rs] - wall = statistics.median(walls) - original = wall if original is None else original - step = "" if previous is None else f"{previous - wall:.1f}" - print( - f"| `{name}` | {wall:.1f} ({min(walls):.1f}-{max(walls):.1f}) | {step} " - f"| {original - wall:.1f} | {statistics.median(r[3] for r in rs):.0f} | {max(r[4] for r in rs)} |" - ) - previous = wall - print(f"\n{len(rows[names[0]])} runs per variant; distinct (exit status, output) pairs: {len(outputs)} {sorted(outputs)}") - - -if __name__ == "__main__": - {"build": build, "time": timeit, "report": report}[sys.argv[1]](*sys.argv[2:]) diff --git a/.github/replay-ablation/mkvariants.py b/.github/replay-ablation/mkvariants.py deleted file mode 100644 index 2e982180f29e..000000000000 --- a/.github/replay-ablation/mkvariants.py +++ /dev/null @@ -1,226 +0,0 @@ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the Apache 2.0 License. -"""Generate ablation variants of the consensus replayer. - -Cumulative variants: the replayer before the change (`00-original`), then the optimisations -added one at a time in ORDER, each variant including all earlier ones, ending at FULL. -Variant k is FULL with the optimisations after k removed, as files to overlay on -lean/consensus, plus a VALIDATOR file naming the tests/cft_trace_validation.py to use. -usage: mkvariants.py REPO FULL_REV OUTDIR -""" -import pathlib, subprocess, sys - -repo, FULL, outdir = sys.argv[1:] -R = "lean/consensus/Consensus/Replay/" -BASE = "f6d7d21c0" - - -def show(rev, name): - return subprocess.check_output(["git", "-C", repo, "show", f"{rev}:{R}{name}"], text=True) - - -full = {n: show(FULL, n) for n in ("Input.lean", "Interpreter.lean", "Reduction.lean")} -old = {n: show(BASE, n) for n in full} - - -def sub(text, a, b, count=1): - assert text.count(a) == count, (text.count(a), a[:80]) - return text.replace(a, b) - - -def between(text, start, end): - i = text.index(start) - j = text.index(end, i) - return text[i:j] - - -new_body = '''private def buildStreamsFromBuckets (buckets : Std.HashMap String (Array BucketEntry)) - : Except String (Array (Array Event) × List String) := do - let keyed : List (String × BucketEntry) := - buckets.toList.flatMap fun (pid, entries) => entries.toList.map (pid, ·) - let keyed := - keyed.mergeSort - fun (p, a) (q, b) => - p < q || (p == q && (a.m_ts < b.m_ts || (a.m_ts == b.m_ts && a.line <= b.line))) - let mut events : Array Event := #[] - let mut pids : Std.HashMap String String := {} - let mut declared : List String := [] - let mut parsedCache : Std.HashMap Nat ParsedMessage := {} - let mut previous : Option (String × Nat × String × Nat) := none - for (pid, entry) in keyed do - let location := s!"{entry.file}:{entry.line}" - if let some (lastPid, lastMts, earlierFile, earlierLine) := previous then - if lastPid == pid && lastMts == entry.m_ts then - throw - s!"{location}: m_ts {entry.m_ts} of pid '{pid}' repeats {earlierFile}:{earlierLine}" - previous := some (pid, entry.m_ts, entry.file, entry.line) - let parsed ← - match entry.stateId.bind (parsedCache[·]?) with - | some cached => pure cached - | none => - let parsed ← (parseMessage entry.message).mapError (s!"{location}: " ++ ·) - if let some id := entry.stateId then - parsedCache := parsedCache.insert id parsed - pure parsed - unless parsed.isCmd do - if let some other := pids[parsed.node]? then - unless other == pid do - throw - s!"{location}: node '{parsed.node}' is traced by pids '{other}' and '{pid}'" - pids := pids.insert parsed.node pid - let record : Record := - { file := entry.file, line := entry.line, value := Json.null } - events := - events.push - { - record - m_ts := entry.m_ts - ts := entry.ts - function := parsed.function - node := parsed.node - message := entry.message - state := parsed.state - stateId := entry.stateId - } - declared := parsed.node :: parsed.extraDeclared ++ declared - let streams := - pids.keys.mergeSort.toArray.map fun node => events.filter (·.node == node) - return (streams, declared.mergeSort.eraseDups) - -''' - -OBSERVE_START = "/-- Compare an action-boundary snapshot with the current model node. -/" - - -def rm_streaming(t): - t = sub(t, """ let handle ← IO.FS.Handle.mk path .read -""", """ let content ← IO.FS.readFile path - let lines := (content.splitOn "\\n").toArray - let lines := if content.endsWith "\\n" then lines.pop else lines - let mut cursor : Nat := 0 -""") - return sub(t, """ let raw ← handle.getLine - if raw.isEmpty then - break -""", """ if cursor >= lines.size then - break - let raw := lines[cursor]! - cursor := cursor + 1 -""") - - -def rm_tag_skip(t): - return sub(t, """ if tag != "ccf.cft" then - .skip - else if""", """ if tag != "ccf.cft" then - .fallback - else if""") - - -def rm_scanner(t): - return sub(t, """private def matchFluentdLine (raw : String) : FastLine := - if !byteEqAt raw 0""", """private def matchFluentdLine (raw : String) : FastLine := - if true || !byteEqAt raw 0""") - - -def rm_msg_reuse(t): - return sub(t, " if cachedRaw == msgRaw then", " if false && cachedRaw == msgRaw then") - - -def rm_buckets(t): - return sub(t, between(t, "private def buildStreamsFromBuckets", "/--\nOrder each process's records"), new_body) - - -def rm_snapshot_skip(t): - return sub(t, " if stateId.isSome && cache.lastVerifiedId == stateId then", - " if false && stateId.isSome && cache.lastVerifiedId == stateId then") - - -def rm_obs_cache(t): - return sub(t, """ : Except String ReplayState := do - let self ← header.nodeId node - if self < replay.obsCache.size then""", """ : Except String ReplayState := do - let self ← header.nodeId node - if false && self < replay.obsCache.size then""") - - -def rm_one_pass(t): - old_observe = between(old["Interpreter.lean"], OBSERVE_START, "/-- Physical packet coordinates") - return sub(t, between(t, OBSERVE_START, "private def observeStateCached"), old_observe) - - -def rm_node_index(t): - return sub(t, """ ({} : Std.HashMap String NodeID) - { header with nodeIds }""", """ ({} : Std.HashMap String NodeID) - if true then header else { header with nodeIds }""") - - -def rm_sched_fast_path(t): - loop_new = between(t, " let mut actions : Nat := 0\n let mut observations : Nat := 0\n for _ in [:total] do", "end Consensus.Replay") - loop_old = between(old["Interpreter.lean"], " for _ in [:total] do", "end Consensus.Replay") - loop_old = sub(loop_old, " modify (·.push group)\n", " if record || true then\n modify (·.push group)\n") - return sub(t, loop_new, loop_old) - - -def rm_empty_sends(t): - return sub(t, """ if sends.isEmpty && replay.queued.isEmpty then - return replay -""", "") - - -def rm_rule_dispatch(t): - return sub(t, between(t, "def ruleStep", "end Consensus.Replay.Reducer"), - between(old["Reduction.lean"], "def ruleStep", "end Consensus.Replay.Reducer")) - - -# (name, file, removal). A step's prerequisites come before it; otherwise largest gain first. -ORDER = [ - ("one-pass-summary", "Interpreter.lean", rm_one_pass), - ("obs-cache", "Interpreter.lean", rm_obs_cache), - ("line-scanner", "Input.lean", rm_scanner), - ("msg-reuse", "Input.lean", rm_msg_reuse), - ("snapshot-skip", "Interpreter.lean", rm_snapshot_skip), - ("rule-dispatch", "Reduction.lean", rm_rule_dispatch), - ("streaming", "Input.lean", rm_streaming), - ("sched-fast-path", "Interpreter.lean", rm_sched_fast_path), - ("largest-first", None, None), - ("buckets", "Input.lean", rm_buckets), - ("tag-skip", "Input.lean", rm_tag_skip), - ("empty-sends-shortcut", "Interpreter.lean", rm_empty_sends), - ("node-index", "Interpreter.lean", rm_node_index), -] - -out = pathlib.Path(outdir) - - -def write(name, files, validator): - d = out / name - for f, text in files.items(): - (d / f).parent.mkdir(parents=True, exist_ok=True) - (d / f).write_text(text) - d.mkdir(parents=True, exist_ok=True) - (d / "VALIDATOR").write_text(validator) - print(name, validator, sorted(files)) - - -write("00-original", { - path: subprocess.check_output(["git", "-C", repo, "show", f"{BASE}:lean/consensus/{path}"], text=True) - for path in [ - "Consensus/Replay/Groups.lean", - "Consensus/Replay/Input.lean", - "Consensus/Replay/Interpreter.lean", - "Consensus/Replay/Reduction.lean", - "replay/ReplayMain.lean", - ] -}, "old") -# k = 0 is FULL with every optimisation removed; k = len(ORDER) is FULL. -for k in range(len(ORDER) + 1): - texts = {} - validator = "old" - for i, (name, f, removal) in enumerate(ORDER): - if f is None: - validator = "new" if i < k else "old" - elif i >= k: - texts[f] = removal(texts.get(f, full[f])) - label = "all-removed" if k == 0 else "plus-" + ORDER[k - 1][0] - write(f"{k + 1:02d}-{label}", {"Consensus/Replay/" + f: t for f, t in texts.items()}, validator) diff --git a/.github/workflows/replay-ablation.yml b/.github/workflows/replay-ablation.yml deleted file mode 100644 index 9870c647e8fc..000000000000 --- a/.github/workflows/replay-ablation.yml +++ /dev/null @@ -1,65 +0,0 @@ -# Temporary: ablation timing of the consensus replayer optimisations. Remove before merge. -name: Replay ablation (temporary) - -on: - push: - branches: - - cjen1-msft-crispy-system - -permissions: - contents: read - actions: read - -jobs: - ablation: - name: "Consensus replay ablation" - runs-on: ubuntu-26.04 - timeout-minutes: 120 - defaults: - run: - shell: bash - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 0 - - - name: Install Lean - uses: ./.github/actions/install-lean - - - name: Build variants - run: | - set -euo pipefail - nproc - python3 .github/replay-ablation/mkvariants.py . f799bc5eb "$RUNNER_TEMP/patches" - git show f6d7d21c0:tests/cft_trace_validation.py > "$RUNNER_TEMP/old_validation.py" - python3 .github/replay-ablation/ablation.py build \ - "$RUNNER_TEMP/patches" lean/consensus "$RUNNER_TEMP/bin" - - - name: Download e2e logs of a fixed run - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: logs-azurelinux-virtual-* - path: ${{ runner.temp }}/e2e-logs - run-id: 45581973686 - github-token: ${{ github.token }} - - - name: Time variants - run: | - set -euo pipefail - python3 .github/replay-ablation/ablation.py time "$RUNNER_TEMP/bin" \ - tests/cft_trace_validation.py "$RUNNER_TEMP/old_validation.py" \ - "$RUNNER_TEMP/e2e-logs" 5 "$RUNNER_TEMP/ablation.csv" - - - name: Report - if: ${{ !cancelled() }} - run: | - set -euo pipefail - cat "$RUNNER_TEMP/ablation.csv" - python3 .github/replay-ablation/ablation.py report "$RUNNER_TEMP/ablation.csv" \ - | tee -a "$GITHUB_STEP_SUMMARY" - - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - if: ${{ !cancelled() }} - with: - name: replay-ablation - path: ${{ runner.temp }}/ablation.csv