Skip to main content

decl_lang/semantics/lifetime/
diagnostics.rs

1//! Scalar-only cycle-collector observations. Never retains a runtime owner.
2use serde::Serialize;
3use std::cell::{Cell, RefCell};
4
5pub const PHASE_NAMES: [&str; 6] = [
6    "seed",
7    "trace",
8    "root",
9    "mark",
10    "clear",
11    "scratch_and_graph_drop",
12];
13pub const NODE_KIND_NAMES: [&str; 19] = [
14    "env",
15    "rec",
16    "type",
17    "members",
18    "types",
19    "registry",
20    "roots",
21    "arr",
22    "map",
23    "object",
24    "pre_array",
25    "json_array",
26    "pre_value",
27    "closure",
28    "local",
29    "constant",
30    "namespace",
31    "exports",
32    "compute",
33];
34pub const GROWTH_NAMES: [&str; 8] = [
35    "nodes",
36    "ids",
37    "edges",
38    "edge_offsets",
39    "incoming",
40    "borrowed",
41    "nested_edges",
42    "queue",
43];
44
45/// Entry path that requested a cycle collection.
46#[derive(Clone, Copy, Debug, Default, Serialize)]
47#[serde(rename_all = "snake_case")]
48pub enum GcTrigger {
49    /// An explicit call to the public collection API.
50    #[default]
51    Explicit,
52    /// Release of the last registered Engine owner on this thread.
53    LastEngine,
54    /// Release of the command lifetime guard.
55    Command,
56}
57impl GcTrigger {
58    fn index(self) -> usize {
59        match self {
60            Self::Explicit => 0,
61            Self::LastEngine => 1,
62            Self::Command => 2,
63        }
64    }
65}
66
67/// CLOCK_MONOTONIC brackets CLOCK_PROCESS_CPUTIME_ID. Clock errors are explicit;
68/// a failed clock cannot silently become a zero-duration successful interval.
69#[derive(Clone, Copy, Default, Serialize)]
70pub struct Stamp {
71    pub monotonic_before_ns: Option<u64>,
72    pub process_cpu_ns: Option<u64>,
73    pub monotonic_after_ns: Option<u64>,
74    pub errno: [i32; 3],
75    pub allocation: crate::allocation_diagnostics::Snapshot,
76}
77fn clock(id: libc::clockid_t) -> (Option<u64>, i32) {
78    let mut ts = libc::timespec {
79        tv_sec: 0,
80        tv_nsec: 0,
81    };
82    // SAFETY: ts is a valid writable timespec. The two callers use supported
83    // POSIX clock identifiers and do not transfer ownership to the C function.
84    if unsafe { libc::clock_gettime(id, &mut ts) } != 0 {
85        return (
86            None,
87            std::io::Error::last_os_error().raw_os_error().unwrap_or(-1),
88        );
89    }
90    if ts.tv_sec < 0 || ts.tv_nsec < 0 || ts.tv_nsec >= 1_000_000_000 {
91        return (None, libc::EINVAL);
92    }
93    let ns = (ts.tv_sec as u64)
94        .checked_mul(1_000_000_000)
95        .and_then(|s| s.checked_add(ts.tv_nsec as u64));
96    (ns, if ns.is_some() { 0 } else { libc::EOVERFLOW })
97}
98pub(super) fn stamp() -> Stamp {
99    let (monotonic_before_ns, a) = clock(libc::CLOCK_MONOTONIC);
100    let (process_cpu_ns, b) = clock(libc::CLOCK_PROCESS_CPUTIME_ID);
101    let (monotonic_after_ns, c) = clock(libc::CLOCK_MONOTONIC);
102    Stamp {
103        monotonic_before_ns,
104        process_cpu_ns,
105        monotonic_after_ns,
106        errno: [a, b, c],
107        allocation: crate::allocation_diagnostics::snapshot(),
108    }
109}
110
111/// Raw value variants of unique Check descriptors inspected in one graph pass.
112/// This is a population census, not a count of equal values or cache hits.
113/// No raw value is evaluated, cloned, retained, or compared with another value.
114#[derive(Clone, Copy, Default, Serialize)]
115pub struct CheckRawWork {
116    pub small_int: usize,
117    pub big_int: usize,
118    pub float: usize,
119    pub string: usize,
120    pub boolean: usize,
121    pub null: usize,
122    pub absent: usize,
123    pub undefined: usize,
124    pub quantity: usize,
125    pub reference: usize,
126    pub record: usize,
127    pub array: usize,
128    pub map: usize,
129    pub range: usize,
130    pub closure: usize,
131    pub native: usize,
132    pub std_path: usize,
133    pub namespace: usize,
134    pub pattern: usize,
135    pub pre_object: usize,
136    pub pre_array: usize,
137    pub pre_value: usize,
138    pub json_object: usize,
139    pub json_array: usize,
140    pub segments: usize,
141}
142impl CheckRawWork {
143    pub(super) fn record(&mut self, raw: &super::Value) {
144        use super::{Num, Value};
145        let count = match raw {
146            Value::Int(Num::Small(_)) => &mut self.small_int,
147            Value::Int(Num::Big(_)) => &mut self.big_int,
148            Value::Float(_) => &mut self.float,
149            Value::Str(_) => &mut self.string,
150            Value::Bool(_) => &mut self.boolean,
151            Value::Null => &mut self.null,
152            Value::Absent => &mut self.absent,
153            Value::Undef => &mut self.undefined,
154            Value::Q(_) => &mut self.quantity,
155            Value::Ref(_) => &mut self.reference,
156            Value::Rec(_) => &mut self.record,
157            Value::Arr(_) => &mut self.array,
158            Value::Map(_) => &mut self.map,
159            Value::Range(_) => &mut self.range,
160            Value::Clo(_) => &mut self.closure,
161            Value::Nat(_) => &mut self.native,
162            Value::Std(_) => &mut self.std_path,
163            Value::NsRef(_) => &mut self.namespace,
164            Value::Pat(_) => &mut self.pattern,
165            Value::PreObj(_) => &mut self.pre_object,
166            Value::PreArr(_) => &mut self.pre_array,
167            Value::PreVal(_) => &mut self.pre_value,
168            Value::JObj(_) => &mut self.json_object,
169            Value::JArr(_) => &mut self.json_array,
170            Value::Segs(_) => &mut self.segments,
171        };
172        *count += 1;
173    }
174}
175
176#[derive(Clone, Copy, Default, Serialize)]
177pub struct ComputeWork {
178    /// Unique descriptor nodes in this pass, never slot-handle occurrences.
179    pub check: usize,
180    /// Disjoint subsets whose sum equals `check`; expired nodes are excluded.
181    pub check_raw: CheckRawWork,
182    pub default: usize,
183    pub derived: usize,
184    /// Subset of derived descriptors with an explicitly supplied value.
185    pub derived_supplied: usize,
186    pub bridge: usize,
187    /// Weak descriptor nodes that could no longer be inspected.
188    pub expired: usize,
189    /// Inline descriptor body only; excludes Rc headers and captured allocations.
190    pub body_size_bytes: usize,
191}
192
193#[derive(Clone, Copy, Default, Serialize)]
194pub struct Work {
195    pub add_attempts: usize,
196    pub duplicate_node_hits: usize,
197    pub node_kinds: [usize; 19],
198    /// Optional representation attribution; not an additional set of graph nodes.
199    pub compute: ComputeWork,
200    pub seed_nodes: usize,
201    pub traced_nodes: usize,
202    pub strong_edge_occurrences: usize,
203    pub borrowed_nodes: usize,
204    pub roots: usize,
205    pub external_roots: usize,
206    pub borrow_only_roots: usize,
207    pub queue_pushes: usize,
208    pub queue_pops: usize,
209    pub duplicate_queue_pops: usize,
210    pub queue_high_water: usize,
211    pub mark_edge_examinations: usize,
212    pub live_nodes: usize,
213    pub visited_garbage_nodes: usize,
214    pub nonempty_adjacencies: usize,
215    pub maximum_out_degree: usize,
216    pub nested_edge_capacity: usize,
217    pub capacity_growth_events: [usize; 8],
218}
219impl Work {
220    pub(super) fn queue_added(&mut self, added: usize, len: usize, before: usize, after: usize) {
221        self.queue_pushes += added;
222        self.queue_high_water = self.queue_high_water.max(len);
223        self.capacity_growth_events[7] += usize::from(after > before);
224    }
225}
226
227/// All capacities are element counts. Hash-map/set capacity is usable entries,
228/// deliberately not estimated allocator bytes. Vec payload bytes exclude their
229/// inline headers, allocator metadata, and all runtime objects being traced.
230#[derive(Clone, Copy, Default, Serialize)]
231pub struct Capacities {
232    pub nodes: usize,
233    pub ids: usize,
234    pub edges: usize,
235    pub edge_offsets: usize,
236    pub incoming: usize,
237    pub borrowed: usize,
238    pub nested_edge_elements: usize,
239    pub live: usize,
240    pub queue: usize,
241    pub vector_payload_capacity_bytes: usize,
242    pub node_size_bytes: usize,
243    pub edge_element_size_bytes: usize,
244}
245
246#[derive(Serialize)]
247pub struct Pass {
248    pub ordinal: usize,
249    pub start: Stamp,
250    pub phase_ends: [Option<Stamp>; 6],
251    pub tracked_weak_before: [usize; 3],
252    pub tracked_weak_after: [usize; 3],
253    pub tracked_weak_capacity_before: [usize; 3],
254    pub tracked_weak_capacity_after: [usize; 3],
255    pub work: Work,
256    pub capacities: Capacities,
257    pub tracked_tls_available: bool,
258}
259impl Pass {
260    pub(super) fn new(ordinal: usize) -> Self {
261        Self {
262            ordinal,
263            start: stamp(),
264            phase_ends: [None; 6],
265            tracked_weak_before: [0; 3],
266            tracked_weak_after: [0; 3],
267            tracked_weak_capacity_before: [0; 3],
268            tracked_weak_capacity_after: [0; 3],
269            work: Work::default(),
270            capacities: Capacities::default(),
271            tracked_tls_available: false,
272        }
273    }
274    pub(super) fn end(&mut self, phase: usize) {
275        self.phase_ends[phase] = Some(stamp());
276    }
277}
278
279#[derive(Serialize)]
280pub struct Call {
281    pub trigger: GcTrigger,
282    pub start: Stamp,
283    pub end: Option<Stamp>,
284    pub passes: Vec<Pass>,
285    pub visited_garbage_nodes: usize,
286    pub termination: &'static str,
287}
288impl Call {
289    pub(super) fn new(trigger: GcTrigger) -> Self {
290        Self {
291            trigger,
292            start: stamp(),
293            end: None,
294            passes: Vec::new(),
295            visited_garbage_nodes: 0,
296            termination: "not_finished",
297        }
298    }
299}
300
301/// Thread-local scalar observations drained after runtime owners are released.
302#[derive(Serialize)]
303pub struct GcDiagnostics {
304    /// Report schema; version 2 includes the shared Compute descriptor node kind.
305    pub schema_version: u32,
306    /// Ordered names of the six collection intervals.
307    pub phase_names: [&'static str; 6],
308    /// Node-tag names used to index each pass's per-kind counts.
309    pub node_kind_names: [&'static str; 19],
310    /// Container names used to index observed capacity-growth events.
311    pub growth_names: [&'static str; 8],
312    /// Trigger names used to index suppressed collection attempts.
313    pub trigger_names: [&'static str; 3],
314    /// Completed collection calls, including their passes and termination reason.
315    pub calls: Vec<Call>,
316    /// Reentrant or unavailable collection entries, counted by trigger.
317    pub suppressed_attempts: [usize; 3],
318}
319impl Default for GcDiagnostics {
320    fn default() -> Self {
321        Self {
322            schema_version: 2,
323            phase_names: PHASE_NAMES,
324            node_kind_names: NODE_KIND_NAMES,
325            growth_names: GROWTH_NAMES,
326            trigger_names: ["explicit", "last_engine", "command"],
327            calls: Vec::new(),
328            suppressed_attempts: [0; 3],
329        }
330    }
331}
332thread_local! {
333    static REPORT: RefCell<GcDiagnostics> = RefCell::new(GcDiagnostics::default());
334    static NEXT_TRIGGER: Cell<GcTrigger> = const { Cell::new(GcTrigger::Explicit) };
335}
336pub(super) fn set_next_trigger(trigger: GcTrigger) {
337    let _ = NEXT_TRIGGER.try_with(|v| v.set(trigger));
338}
339pub(super) fn take_trigger() -> GcTrigger {
340    NEXT_TRIGGER
341        .try_with(|v| v.replace(GcTrigger::Explicit))
342        .unwrap_or_default()
343}
344pub(super) fn suppressed(trigger: GcTrigger) {
345    let _ = REPORT.try_with(|v| v.borrow_mut().suppressed_attempts[trigger.index()] += 1);
346}
347pub(super) fn finish(mut call: Call, visited: usize) {
348    call.visited_garbage_nodes = visited;
349    call.end = Some(stamp());
350    // No report borrow spans tracing, clearing, Graph drop, or user owners' Drop.
351    let _ = REPORT.try_with(|v| v.borrow_mut().calls.push(call));
352}
353
354/// Drain scalar observations on this thread. Call after all measured owners and
355/// guards have dropped; draining earlier excludes their later collection calls.
356/// The returned Vec owns no Engine, Value, Type, Node, or weak runtime handle.
357pub fn take_gc_diagnostics() -> GcDiagnostics {
358    REPORT
359        .try_with(|v| std::mem::take(&mut *v.borrow_mut()))
360        .unwrap_or_default()
361}