Skip to main content

decl_lang/
root_binding_diagnostics.rs

1//! Feature-only root-binding boundaries, stored separately from evaluation spans.
2//!
3//! These records own bounded name text and scalar diagnostics, never runtime
4//! values, scopes, engines or callbacks. A [`RootAttempt`] is the first local in
5//! `bind_root`; its final boundary consequently follows later local destruction.
6//! Function arguments and the attempt's own report storage are released later.
7//! Name copying happens before the local span starts, but inside its parent.
8//!
9//! Like evaluation spans, the counters and clocks are process-wide and include
10//! nested work. A cumulative requested peak is not a phase-local peak or RSS.
11//! Recording allocates, and parent/child intervals must not be summed together.
12//!
13//! When a phase-event sink is installed, a scalar EventScope shares the local
14//! span's ordinal. The local starting stamp precedes the event entry; each mark
15//! precedes its next-stage event, and the final mark precedes the ending event.
16//! Their clocks therefore bracket different diagnostic recording overhead.
17//! Root records retain neither the EventScope nor the event sink.
18
19use crate::evaluation_diagnostics::{EventStage, Span};
20use crate::phase_events::{EventScope, Outcome as EventOutcome, RootIdentity, RootKind};
21use serde::Serialize;
22use std::cell::{Cell, RefCell};
23
24/// Maximum retained UTF-8 bytes of a root's diagnostic name.
25pub const ROOT_NAME_LIMIT: usize = 256;
26
27/// Source supplied to `bind_root`, without retaining the source itself.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
29#[serde(rename_all = "snake_case")]
30pub enum SourceKind {
31    /// Evaluate a source expression before binding.
32    Expr,
33    /// Bind a supplied document value.
34    Doc,
35}
36
37/// Result of dispatch, or the final reason an attempt did not return normally.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "snake_case")]
40pub enum Outcome {
41    /// Dispatch returned a bound value, possibly through reuse.
42    Bound,
43    /// Dispatch requested later settlement.
44    Defer,
45    /// Dispatch returned an evaluation diagnostic.
46    EvalError,
47    /// Dispatch was tainted by an earlier failure.
48    Taint,
49    /// Retained-round selection omitted this root.
50    Skipped,
51    /// The attempt guard was released during unwinding.
52    Unwound,
53    /// The body did not record a completed handler action.
54    Incomplete,
55}
56
57/// Action actually taken by the root result handler.
58///
59/// In particular, queueing is recorded directly, not inferred from the initial
60/// phase: a native callback can change that phase before the result is handled.
61#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
62#[serde(rename_all = "snake_case")]
63pub enum Completion {
64    /// The value was installed in the environment.
65    Published,
66    /// A deferred source was saved for a later attempt.
67    DeferredQueued,
68    /// A deferred result required no further queue entry.
69    DeferIgnored,
70    /// An evaluation diagnostic was reported.
71    EvalError,
72    /// Taint required no additional diagnostic.
73    Taint,
74    /// The root was skipped before dispatch.
75    Skipped,
76}
77
78/// One root attempt, submitted in completion order to this thread's buffer.
79#[derive(Serialize)]
80pub struct RootRecord {
81    /// UTF-8 root name prefix bounded by [`ROOT_NAME_LIMIT`].
82    pub root_name: String,
83    /// Byte length of the original name before capping.
84    pub root_name_original_bytes: usize,
85    /// Whether the stored name omits an original suffix.
86    pub root_name_truncated: bool,
87    /// Engine phase at entry; callbacks may change the phase later.
88    pub initial_phase: u8,
89    /// Origin of the source supplied to this attempt.
90    pub source_kind: SourceKind,
91    /// Number of actual producer calls; zero includes a successful Edits reuse.
92    pub producer_calls: usize,
93    /// Source evaluation returned successfully, rather than deferring or failing.
94    pub source_successes: usize,
95    /// Recursive binding returned a Result, including an error Result.
96    pub binding_returns: usize,
97    /// Result observed immediately after dispatch; absent for skip or unwind.
98    pub dispatch_outcome: Option<Outcome>,
99    /// Handler action, absent if it did not finish normally.
100    pub completion: Option<Completion>,
101    /// Final outcome; unwind overrides any earlier dispatch result.
102    pub outcome: Outcome,
103    /// Active interval when normal body completion was interrupted.
104    pub interrupted_stage: Option<&'static str>,
105    /// Local span only: it is never submitted to evaluation's global span list.
106    pub span: Span,
107}
108
109struct State {
110    record: RootRecord,
111    active: &'static str,
112    events: EventScope,
113}
114
115thread_local! {
116    static ROOTS: RefCell<Vec<RootRecord>> = const { RefCell::new(Vec::new()) };
117    static NEXT_ORDINAL: Cell<usize> = const { Cell::new(0) };
118}
119
120/// First-local guard for one root binding, including early return and unwind.
121///
122/// All methods release their internal borrow before returning to the caller.
123/// No borrow is held across expression evaluation, binding or native callbacks.
124pub struct RootAttempt {
125    state: RefCell<Option<State>>,
126}
127
128impl RootAttempt {
129    /// Begin an attempt with bounded name metadata and no runtime owners.
130    /// Its local clock starts before the optional event entry is published.
131    pub fn new(name: &str, initial_phase: u8, source_kind: SourceKind) -> Self {
132        let mut end = name.len().min(ROOT_NAME_LIMIT);
133        while !name.is_char_boundary(end) {
134            end -= 1;
135        }
136        let root_name = name[..end].to_owned();
137        let ordinal = NEXT_ORDINAL
138            .try_with(|next| {
139                let ordinal = next.get();
140                next.set(ordinal.saturating_add(1));
141                ordinal
142            })
143            .unwrap_or(usize::MAX);
144        let identity = RootIdentity::new(
145            name,
146            match source_kind {
147                SourceKind::Expr => RootKind::Expression,
148                SourceKind::Doc => RootKind::Document,
149            },
150        );
151        Self {
152            state: RefCell::new(Some(State {
153                record: RootRecord {
154                    root_name,
155                    root_name_original_bytes: name.len(),
156                    root_name_truncated: end != name.len(),
157                    initial_phase,
158                    source_kind,
159                    producer_calls: 0,
160                    source_successes: 0,
161                    binding_returns: 0,
162                    dispatch_outcome: None,
163                    completion: None,
164                    outcome: Outcome::Incomplete,
165                    interrupted_stage: None,
166                    span: Span::new("root_bind", ordinal),
167                },
168                active: "dispatch",
169                events: EventScope::begin(
170                    EventStage::RootDispatch as u32,
171                    ordinal as u64,
172                    identity,
173                ),
174            })),
175        }
176    }
177
178    /// Immediately before source evaluation or document cloning in the producer.
179    pub fn source_started(&self) {
180        let mut state = self.state.borrow_mut();
181        let state = state.as_mut().unwrap();
182        state.record.span.mark(state.active);
183        state.record.producer_calls += 1;
184        state.active = "source_eval";
185        state.events.transition(EventStage::RootSourceEval as u32);
186    }
187
188    /// After successful source evaluation, before recursive type binding.
189    pub fn source_evaluated(&self) {
190        let mut state = self.state.borrow_mut();
191        let state = state.as_mut().unwrap();
192        state.record.span.mark(state.active);
193        state.record.source_successes += 1;
194        state.active = "recursive_bind";
195        state.events.transition(EventStage::RootTypeBind as u32);
196    }
197
198    /// After recursive binding returns either a value or an error.
199    pub fn binding_returned(&self) {
200        let mut state = self.state.borrow_mut();
201        let state = state.as_mut().unwrap();
202        state.record.span.mark(state.active);
203        state.record.binding_returns += 1;
204        state.active = "dispatch_return";
205        state
206            .events
207            .transition(EventStage::RootDispatchReturn as u32);
208    }
209
210    /// After step/Edits dispatch returns, before the existing result handler.
211    /// Call with Bound, Defer, EvalError or Taint; this does not infer producer work.
212    pub fn dispatch_returned(&self, outcome: Outcome) {
213        let mut state = self.state.borrow_mut();
214        let state = state.as_mut().unwrap();
215        state.record.span.mark(state.active);
216        state.record.dispatch_outcome = Some(outcome);
217        state.active = "publish_or_handle";
218        state
219            .events
220            .transition(EventStage::RootPublishOrDefer as u32);
221    }
222
223    /// After the result handler's actual publication, queue, report or taint action.
224    pub fn body_returned(&self, completion: Completion) {
225        let mut state = self.state.borrow_mut();
226        let state = state.as_mut().unwrap();
227        state.record.span.mark(state.active);
228        state.record.completion = Some(completion);
229        state.active = "scope_release";
230        state.events.transition(EventStage::RootScopeRelease as u32);
231    }
232
233    /// The retained round skipped this root before dispatch or source production.
234    pub fn skipped(&self) {
235        let mut state = self.state.borrow_mut();
236        let state = state.as_mut().unwrap();
237        state.record.span.mark(state.active);
238        state.record.completion = Some(Completion::Skipped);
239        state.active = "scope_release";
240        state.events.transition(EventStage::RootScopeRelease as u32);
241    }
242}
243
244impl Drop for RootAttempt {
245    fn drop(&mut self) {
246        let Some(mut state) = self.state.get_mut().take() else {
247            return;
248        };
249        let unwound = std::thread::panicking();
250        state.record.span.mark(state.active);
251        state.record.outcome = if unwound {
252            Outcome::Unwound
253        } else if state.record.completion == Some(Completion::Skipped) {
254            Outcome::Skipped
255        } else if state.record.completion.is_some() {
256            state.record.dispatch_outcome.unwrap_or(Outcome::Incomplete)
257        } else {
258            Outcome::Incomplete
259        };
260        if unwound || state.record.completion.is_none() {
261            state.record.interrupted_stage = Some(state.active);
262        }
263        state.events.finish(match state.record.outcome {
264            Outcome::Bound | Outcome::Skipped => EventOutcome::Ok,
265            Outcome::Defer => EventOutcome::Defer,
266            Outcome::EvalError => EventOutcome::Eval,
267            Outcome::Taint => EventOutcome::Taint,
268            Outcome::Unwound => EventOutcome::Unwound,
269            Outcome::Incomplete => EventOutcome::Incomplete,
270        });
271        // During TLS destruction this optional diagnostic buffer may be gone.
272        // No runtime owners are held by the record being discarded in that case.
273        let _ = ROOTS.try_with(|roots| roots.borrow_mut().push(state.record));
274    }
275}
276
277/// Drain completed root records without touching evaluation spans or live guards.
278/// Ordinals and process counters are not reset. Records retain no runtime owners.
279pub fn take_root_binding_diagnostics() -> Vec<RootRecord> {
280    ROOTS.with(|roots| std::mem::take(&mut *roots.borrow_mut()))
281}
282
283#[cfg(test)]
284#[path = "../tests/private/root_binding_diagnostics_test.rs"]
285mod tests;