Skip to main content

uqa_execution/query/diagnostics/
scope.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Session identities isolate nested calls; worker bindings explicitly inherit their captured invocation.
8
9use super::{CapturedDiagnostics, DiagnosticsScope, VectorDiagnostics};
10use std::{cell::RefCell, marker::PhantomData, rc::Rc, sync::Arc};
11use uqa_core::memory::Budgeted;
12use uqa_storage::{read_control::StorageReadControl, StorageBackendResult};
13
14type Binding = Arc<Budgeted<InvocationBinding>>;
15
16thread_local! {
17    static CURRENT: RefCell<Option<Binding>> = const { RefCell::new(None) };
18    static REQUEST: RefCell<Option<InvocationRequest>> = const { RefCell::new(None) };
19}
20
21struct InvocationBinding {
22    identity: Arc<()>,
23    collector: CapturedDiagnostics,
24    previous: Option<Binding>,
25}
26
27/// A suspended worker receives the caller's scope on every step, including explicit absence.
28#[derive(Clone)]
29pub struct InvocationRequest {
30    identity: Arc<()>,
31    collector: Option<CapturedDiagnostics>,
32}
33
34pub struct RequestScope {
35    previous: Option<InvocationRequest>,
36    _thread: PhantomData<Rc<()>>,
37}
38
39impl RequestScope {
40    pub fn replace(&self, request: Option<InvocationRequest>) {
41        REQUEST.with(|current| {
42            *current.borrow_mut() = request;
43        });
44    }
45}
46
47impl Drop for RequestScope {
48    fn drop(&mut self) {
49        REQUEST.with(|current| current.borrow_mut().clone_from(&self.previous));
50    }
51}
52
53#[derive(Default)]
54pub struct QueryDiagnostics {
55    identity: Arc<()>,
56    inherited: Option<CapturedDiagnostics>,
57}
58
59impl QueryDiagnostics {
60    pub fn capture(&self) -> Option<CapturedDiagnostics> {
61        CURRENT.with(|current| {
62            let current = current.borrow();
63            let mut binding = current.as_ref();
64            while let Some(selected) = binding {
65                if Arc::ptr_eq(&selected.identity, &self.identity) {
66                    return selected
67                        .collector
68                        .is_active()
69                        .then(|| Arc::clone(&selected.collector));
70                }
71                binding = selected.previous.as_ref();
72            }
73            REQUEST.with(|request| {
74                if let Some(request) = request
75                    .borrow()
76                    .as_ref()
77                    .filter(|request| Arc::ptr_eq(&request.identity, &self.identity))
78                {
79                    return request
80                        .collector
81                        .clone()
82                        .filter(|collector| collector.is_active());
83                }
84                self.inherited
85                    .clone()
86                    .filter(|collector| collector.is_active())
87            })
88        })
89    }
90
91    /// Bind inherited worker state before executing expressions or host callbacks.
92    pub fn bind_current(&self) -> StorageBackendResult<Option<CapturedScope>> {
93        // A streaming query can span several FETCH invocations. Its request binding remains live until the next request; pinning it here would attribute later work to an earlier caller.
94        if REQUEST.with(|request| {
95            request
96                .borrow()
97                .as_ref()
98                .is_some_and(|request| Arc::ptr_eq(&request.identity, &self.identity))
99        }) {
100            return Ok(None);
101        }
102        self.capture()
103            .as_ref()
104            .map(|collector| self.bind(collector))
105            .transpose()
106    }
107
108    pub fn request(&self) -> InvocationRequest {
109        InvocationRequest {
110            identity: Arc::clone(&self.identity),
111            collector: self.capture(),
112        }
113    }
114
115    pub fn request_scope(request: Option<InvocationRequest>) -> RequestScope {
116        let previous = REQUEST.with(|current| current.replace(request));
117        RequestScope {
118            previous,
119            _thread: PhantomData,
120        }
121    }
122
123    /// Keep session identity while giving the existing read worker an immutable inherited scope.
124    pub fn fork(&self) -> Self {
125        Self {
126            identity: Arc::clone(&self.identity),
127            inherited: self.capture(),
128        }
129    }
130
131    pub fn enter(&self, control: StorageReadControl) -> StorageBackendResult<DiagnosticsScope> {
132        let collector = VectorDiagnostics::new(control, self.capture())?;
133        let binding = self.bind(&collector)?;
134        Ok(DiagnosticsScope {
135            _binding: binding,
136            collector,
137        })
138    }
139
140    /// Install the driver's fixed capture on the executing thread before invoking any callbacks.
141    pub fn bind(&self, collector: &CapturedDiagnostics) -> StorageBackendResult<CapturedScope> {
142        collector.control().check()?;
143        CURRENT.with(|current| {
144            let value = InvocationBinding {
145                identity: Arc::clone(&self.identity),
146                collector: Arc::clone(collector),
147                previous: current.borrow().clone(),
148            };
149            let binding = Budgeted::new(value, collector.control().memory().empty_reservation())
150                .into_shared()?;
151            *current.borrow_mut() = Some(Arc::clone(&binding));
152            Ok(CapturedScope {
153                binding,
154                _thread: PhantomData,
155            })
156        })
157    }
158}
159
160/// A dynamic binding must be restored on the thread that entered it.
161pub struct CapturedScope {
162    binding: Binding,
163    _thread: PhantomData<Rc<()>>,
164}
165
166impl Drop for CapturedScope {
167    fn drop(&mut self) {
168        CURRENT.with(|current| {
169            let mut current = current.borrow_mut();
170            debug_assert!(current
171                .as_ref()
172                .is_some_and(|active| Arc::ptr_eq(active, &self.binding)));
173            current.clone_from(&self.binding.previous);
174        });
175    }
176}