Skip to main content

decl_lang/
evaluation_diagnostics.rs

1//! Scalar-only, separately compiled evaluation phase diagnostics.
2//!
3//! The optional `runtime-diagnostics` feature requires libc `clock_gettime` with
4//! `CLOCK_MONOTONIC` and `CLOCK_PROCESS_CPUTIME_ID` on its target. These hooks are
5//! excluded from feature-empty native builds. The optional backend's Windows
6//! portability has not been established; this module supplies no alternate clock.
7//!
8//! Completed spans are stored on the calling thread without runtime owners.
9//! Their clocks and allocation counters cover the whole process, however, so
10//! concurrent threads can contribute to CPU and allocation observations.
11//! Recording span vectors itself allocates; nested intervals and their parent
12//! intervals must not be added together as independent costs.
13use serde::Serialize;
14use std::cell::RefCell;
15
16macro_rules! event_stages {
17    ($($variant:ident = $id:literal => $label:literal),+ $(,)?) => {
18        /// Explicit operation entry IDs for the optional bounded event stream.
19        #[derive(Clone, Copy)]
20        #[repr(u32)]
21        pub enum EventStage {
22            $(#[doc = $label] $variant = $id,)+
23        }
24        /// Dictionary for this build's event IDs; save it with the binary stream.
25        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/// Ordered clock reads followed by a process-wide requested-allocation snapshot.
59///
60/// The two monotonic reads bracket the CPU read only. The allocation ledger is
61/// read afterwards and is neither clock-bracketed nor an atomic transaction.
62#[derive(Clone, Copy, Serialize)]
63pub struct Stamp {
64    /// Opening `CLOCK_MONOTONIC` reading in nanoseconds, with no civil-time epoch.
65    pub wall_ns: u64,
66    /// `CLOCK_PROCESS_CPUTIME_ID` nanoseconds consumed by all process threads.
67    pub cpu_ns: u64,
68    /// Closing `CLOCK_MONOTONIC` reading after the CPU clock read.
69    pub sampled_until_ns: u64,
70    /// Cumulative ledger read after `sampled_until_ns`; not a phase-local peak.
71    pub allocation: crate::allocation_diagnostics::Snapshot,
72    /// Thread-local prefix traffic sampled after the clock and allocation reads.
73    pub prefix_paths: crate::semantics::PrefixPathDiagnostics,
74    /// Existing constructor/cache counters, copied without allocating.
75    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    // SAFETY: valid clock ID and initialized writable timespec, no pointers escape.
83    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/// One interval between a span's previous boundary and its next explicit mark.
102///
103/// Durations use the opening clock samples at both boundaries. They include
104/// nested runtime work and any recording overhead after the previous boundary.
105#[derive(Serialize)]
106pub struct Stage {
107    /// Caller-provided label for the interval ending at this mark.
108    pub name: &'static str,
109    /// Previous mark boundary, or the span start for the first interval.
110    pub start: Stamp,
111    /// Boundary captured before this stage is appended to the report vector.
112    pub end: Stamp,
113    /// Difference between `end.wall_ns` and `start.wall_ns`.
114    pub wall_ns: u64,
115    /// Difference between process-wide `end.cpu_ns` and `start.cpu_ns`.
116    pub cpu_ns: u64,
117}
118/// Caller-labeled sequence of explicit evaluation boundaries.
119///
120/// A span is submitted to thread-local storage only by [`Span::finish`]. Dropping
121/// it without finishing discards its report; finishing adds no implicit boundary.
122#[derive(Serialize)]
123pub struct Span {
124    /// Caller-provided category, such as setup, a round, or settlement.
125    pub kind: &'static str,
126    /// Caller-provided index; this type imposes no numbering convention.
127    pub ordinal: usize,
128    /// Clock and allocation readings captured when the span was constructed.
129    pub start: Stamp,
130    /// Intervals recorded in mark order; a span may contain no marks.
131    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    /// Capture the starting boundary and create an empty, unsubmitted span.
139    ///
140    /// Clock-query failure panics. The category and ordinal are retained as
141    /// metadata only; no engine, scope or evaluated value is retained.
142    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    /// Publish entry before the named operation. Marks instead label completed
154    /// intervals and must never be interpreted as an operation's start.
155    /// An installed sink adds bounded diagnostic I/O; without one this is inert.
156    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    /// Capture a boundary and append the interval since the preceding boundary.
169    ///
170    /// Appending may grow the stage vector after the captured endpoint; that
171    /// recording work falls inside a later interval if another mark follows.
172    /// Clock-query failure panics before appending a stage.
173    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    /// Submit this span to the current thread's report buffer in finish order.
185    ///
186    /// This may grow the buffer but takes no final sample. Work after the last
187    /// mark, including submission, has no additional interval in this span.
188    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
201/// Advance-only partition, submitted after the advance function's runtime
202/// locals have dropped. It owns scalar diagnostics, never an Engine or Value.
203/// Early returns and unwinding retain a partial prefix without claiming reuse.
204pub(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
251/// Drain completed spans from the calling thread in their submission order.
252///
253/// Other threads' buffers and unfinished spans are unaffected. Reports own
254/// scalar metadata and their vectors, with no engine or evaluated-value owners.
255/// Draining does not reset the process-wide clocks or allocation counters.
256pub fn take_evaluation_diagnostics() -> Vec<Span> {
257    SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()))
258}