1use serde::Serialize;
14use std::cell::RefCell;
15
16macro_rules! event_stages {
17 ($($variant:ident = $id:literal => $label:literal),+ $(,)?) => {
18 #[derive(Clone, Copy)]
20 #[repr(u32)]
21 pub enum EventStage {
22 $(#[doc = $label] $variant = $id,)+
23 }
24 pub const EVENT_STAGES: &[(u32, &str)] = &[$(($id, $label),)+];
26 };
27}
28event_stages! {
29 EvaluateSetup = 100 => "evaluate.setup",
30 RoundEngineSetup = 200 => "round.engine_setup",
31 RoundBind = 201 => "round.bind",
32 RoundForceRootsInitial = 202 => "round.force_roots_initial",
33 RoundSettle = 203 => "round.settle",
34 RoundEditsFinish = 204 => "round.edits_finish",
35 RoundEdgeKeyAndCycle = 205 => "round.edge_key_and_cycle",
36 RoundAdvance = 206 => "round.advance",
37 RoundRetainedTransfer = 207 => "round.retained_round_transfer",
38 RoundCompleteDropPrevious = 208 => "round.complete_drop_previous_and_identity_sweep",
39 RoundFallbackFreezeReset = 209 => "round.fallback_freeze_reset",
40 SettleTakeSnapshot = 300 => "settle.take_snapshot",
41 SettleDeferredSnapshot = 301 => "settle.deferred_snapshot",
42 SettleForceDeferredSlots = 302 => "settle.force_deferred_slots",
43 SettleBindDeferredRoots = 303 => "settle.bind_deferred_roots",
44 SettleForceRoots = 304 => "settle.force_roots",
45 SettleLiveEdges = 305 => "settle.live_edges",
46 SettleCompareEdges = 306 => "settle.compare_edges",
47 AdvanceClassify = 400 => "advance.classify",
48 AdvanceFreeze = 401 => "advance.freeze",
49 AdvanceRevisionReset = 402 => "advance.revision_reset",
50 RootDispatch = 500 => "root.dispatch",
51 RootSourceEval = 501 => "root.source_eval",
52 RootTypeBind = 502 => "root.recursive_bind",
53 RootDispatchReturn = 503 => "root.dispatch_return",
54 RootPublishOrDefer = 504 => "root.publish_or_handle",
55 RootScopeRelease = 505 => "root.scope_release",
56}
57
58#[derive(Clone, Copy, Serialize)]
63pub struct Stamp {
64 pub wall_ns: u64,
66 pub cpu_ns: u64,
68 pub sampled_until_ns: u64,
70 pub allocation: crate::allocation_diagnostics::Snapshot,
72 pub prefix_paths: crate::semantics::PrefixPathDiagnostics,
74 pub traffic: crate::retention_diagnostics::TrafficSnapshot,
76}
77fn clock_ns(id: libc::clockid_t) -> u64 {
78 let mut ts = libc::timespec {
79 tv_sec: 0,
80 tv_nsec: 0,
81 };
82 assert_eq!(unsafe { libc::clock_gettime(id, &mut ts) }, 0);
84 ts.tv_sec as u64 * 1_000_000_000 + ts.tv_nsec as u64
85}
86impl Stamp {
87 fn now() -> Self {
88 let wall_ns = clock_ns(libc::CLOCK_MONOTONIC);
89 let cpu_ns = clock_ns(libc::CLOCK_PROCESS_CPUTIME_ID);
90 let sampled_until_ns = clock_ns(libc::CLOCK_MONOTONIC);
91 Self {
92 wall_ns,
93 cpu_ns,
94 sampled_until_ns,
95 allocation: crate::allocation_diagnostics::snapshot(),
96 prefix_paths: crate::semantics::prefix_path_diagnostics(),
97 traffic: crate::retention_diagnostics::traffic_snapshot(),
98 }
99 }
100}
101#[derive(Serialize)]
106pub struct Stage {
107 pub name: &'static str,
109 pub start: Stamp,
111 pub end: Stamp,
113 pub wall_ns: u64,
115 pub cpu_ns: u64,
117}
118#[derive(Serialize)]
123pub struct Span {
124 pub kind: &'static str,
126 pub ordinal: usize,
128 pub start: Stamp,
130 pub stages: Vec<Stage>,
132 previous: Stamp,
133 #[serde(skip)]
134 event_scope: Option<crate::phase_events::EventScope>,
135}
136thread_local! { static SPANS: RefCell<Vec<Span>> = const { RefCell::new(Vec::new()) }; }
137impl Span {
138 pub fn new(kind: &'static str, ordinal: usize) -> Self {
143 let start = Stamp::now();
144 Self {
145 kind,
146 ordinal,
147 start,
148 stages: Vec::new(),
149 previous: start,
150 event_scope: None,
151 }
152 }
153 pub fn enter(&mut self, stage: EventStage) {
157 match &self.event_scope {
158 Some(scope) => scope.transition(stage as u32),
159 None => {
160 self.event_scope = Some(crate::phase_events::EventScope::begin(
161 stage as u32,
162 self.ordinal as u64,
163 crate::phase_events::RootIdentity::NONE,
164 ));
165 }
166 }
167 }
168 pub fn mark(&mut self, name: &'static str) {
174 let end = Stamp::now();
175 self.stages.push(Stage {
176 name,
177 start: self.previous,
178 end,
179 wall_ns: end.wall_ns - self.previous.wall_ns,
180 cpu_ns: end.cpu_ns - self.previous.cpu_ns,
181 });
182 self.previous = end;
183 }
184 pub fn finish(self) {
189 if let Some(scope) = &self.event_scope {
190 use crate::phase_events::Outcome;
191 scope.finish(match self.kind {
192 "advance_rejected" => Outcome::Rejected,
193 "advance_unwound" => Outcome::Unwound,
194 _ => Outcome::Ok,
195 });
196 }
197 SPANS.with(|s| s.borrow_mut().push(self));
198 }
199}
200
201pub(crate) struct AdvanceSpan {
205 span: Option<Span>,
206 active: &'static str,
207 accepted: bool,
208}
209impl AdvanceSpan {
210 pub(crate) fn new(ordinal: usize) -> Self {
211 let mut span = Span::new("advance_rejected", ordinal);
212 span.enter(EventStage::AdvanceClassify);
213 Self {
214 span: Some(span),
215 active: "classify",
216 accepted: false,
217 }
218 }
219 pub(crate) fn classified(&mut self) {
220 self.span.as_mut().unwrap().mark("classify");
221 self.span.as_mut().unwrap().enter(EventStage::AdvanceFreeze);
222 self.active = "freeze";
223 }
224 pub(crate) fn frozen(&mut self) {
225 self.span.as_mut().unwrap().mark("freeze");
226 self.span
227 .as_mut()
228 .unwrap()
229 .enter(EventStage::AdvanceRevisionReset);
230 self.active = "revision_reset";
231 }
232 pub(crate) fn accepted(&mut self) {
233 self.accepted = true;
234 }
235}
236impl Drop for AdvanceSpan {
237 fn drop(&mut self) {
238 let mut span = self.span.take().unwrap();
239 span.kind = if std::thread::panicking() {
240 "advance_unwound"
241 } else if self.accepted {
242 "advance"
243 } else {
244 "advance_rejected"
245 };
246 span.mark(self.active);
247 span.finish();
248 }
249}
250
251pub fn take_evaluation_diagnostics() -> Vec<Span> {
257 SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()))
258}