uqa_execution/query/diagnostics/
scope.rs1use super::{CapturedDiagnostics, DiagnosticsScope, InvocationDiagnostics};
10use std::{cell::RefCell, marker::PhantomData, rc::Rc, sync::Arc};
11use uqa_core::io_usage::{IOContext, IOOptions, IOScope};
12use uqa_core::memory::Budgeted;
13use uqa_storage::{read_control::StorageReadControl, StorageBackendResult};
14
15type Binding = Arc<Budgeted<InvocationBinding>>;
16
17#[derive(Default)]
18struct SessionIdentity {
19 next_instance: std::sync::atomic::AtomicU64,
20 io_timing: Arc<std::sync::atomic::AtomicBool>,
21}
22
23thread_local! {
24 static CURRENT: RefCell<Option<Binding>> = const { RefCell::new(None) };
25 static REQUEST: RefCell<Option<InvocationRequest>> = const { RefCell::new(None) };
26}
27
28struct InvocationBinding {
29 identity: Arc<SessionIdentity>,
30 collector: CapturedDiagnostics,
31 previous: Option<Binding>,
32}
33
34#[derive(Clone)]
36pub struct InvocationRequest {
37 identity: Arc<SessionIdentity>,
38 collector: Option<CapturedDiagnostics>,
39 control: Option<StorageReadControl>,
40 io: IOContext,
41}
42
43pub struct RequestScope {
44 previous: Option<InvocationRequest>,
45 io: IOScope,
46 _thread: PhantomData<Rc<()>>,
47}
48
49impl RequestScope {
50 pub fn replace(&self, request: Option<InvocationRequest>) {
51 self.io.replace(
52 &request
53 .as_ref()
54 .map_or_else(IOContext::default, |request| request.io.clone()),
55 );
56 REQUEST.with(|current| {
57 *current.borrow_mut() = request;
58 });
59 }
60}
61
62impl Drop for RequestScope {
63 fn drop(&mut self) {
64 REQUEST.with(|current| current.borrow_mut().clone_from(&self.previous));
65 }
66}
67
68#[derive(Default)]
69pub struct QueryDiagnostics {
70 identity: Arc<SessionIdentity>,
71 inherited: Option<CapturedDiagnostics>,
72 retained_control: Option<StorageReadControl>,
73 inherited_io: IOContext,
74}
75
76impl QueryDiagnostics {
77 pub fn new(io_timing: Arc<std::sync::atomic::AtomicBool>) -> Self {
79 Self {
80 identity: Arc::new(SessionIdentity {
81 io_timing,
82 next_instance: std::sync::atomic::AtomicU64::new(0),
83 }),
84 inherited: None,
85 retained_control: None,
86 inherited_io: IOContext::default(),
87 }
88 }
89
90 pub fn io_timing(&self) -> bool {
91 self.identity
92 .io_timing
93 .load(std::sync::atomic::Ordering::Acquire)
94 }
95
96 pub fn io_context(&self) -> IOContext {
98 let collector = self.capture();
99 let Some(root) = collector
100 .as_ref()
101 .and_then(|collector| collector.io.as_ref())
102 else {
103 return IOContext::default();
104 };
105 let current = IOContext::current();
106 if current
107 .observation()
108 .is_some_and(|current| current.is_within(root))
109 {
110 return current;
111 }
112 if let Some(request) = REQUEST
113 .with(|request| {
114 request
115 .borrow()
116 .as_ref()
117 .filter(|request| Arc::ptr_eq(&request.identity, &self.identity))
118 .map(|request| request.io.clone())
119 })
120 .filter(|context| context.observation().is_some_and(|io| io.is_within(root)))
121 {
122 return request;
123 }
124 if self
125 .inherited_io
126 .observation()
127 .is_some_and(|io| io.is_within(root))
128 {
129 return self.inherited_io.clone();
130 }
131 IOContext::new(Some(root.clone()))
132 }
133
134 pub fn capture(&self) -> Option<CapturedDiagnostics> {
135 CURRENT.with(|current| {
136 let current = current.borrow();
137 let mut binding = current.as_ref();
138 while let Some(selected) = binding {
139 if Arc::ptr_eq(&selected.identity, &self.identity) {
140 return selected
141 .collector
142 .is_active()
143 .then(|| Arc::clone(&selected.collector));
144 }
145 binding = selected.previous.as_ref();
146 }
147 REQUEST.with(|request| {
148 if let Some(request) = request
149 .borrow()
150 .as_ref()
151 .filter(|request| Arc::ptr_eq(&request.identity, &self.identity))
152 {
153 return request
154 .collector
155 .clone()
156 .filter(|collector| collector.is_active());
157 }
158 self.inherited
159 .clone()
160 .filter(|collector| collector.is_active())
161 })
162 })
163 }
164
165 pub fn bind_current(&self) -> StorageBackendResult<Option<CapturedScope>> {
167 if REQUEST.with(|request| {
169 request
170 .borrow()
171 .as_ref()
172 .is_some_and(|request| Arc::ptr_eq(&request.identity, &self.identity))
173 }) {
174 return Ok(None);
175 }
176 self.capture()
177 .as_ref()
178 .map(|collector| self.bind(collector))
179 .transpose()
180 }
181
182 pub fn request(&self) -> InvocationRequest {
183 let collector = self.capture();
184 let control = collector
185 .as_ref()
186 .map(|collector| collector.control().clone())
187 .or_else(|| self.retained_control.clone());
188 InvocationRequest {
189 identity: Arc::clone(&self.identity),
190 collector,
191 control,
192 io: self.io_context(),
193 }
194 }
195
196 pub fn request_with_control(&self, control: StorageReadControl) -> InvocationRequest {
198 InvocationRequest {
199 identity: Arc::clone(&self.identity),
200 collector: self.capture(),
201 control: Some(control),
202 io: self.io_context(),
203 }
204 }
205
206 pub fn request_scope(request: Option<InvocationRequest>) -> RequestScope {
207 let io = request
208 .as_ref()
209 .map_or_else(IOContext::default, |request| request.io.clone())
210 .enter();
211 let previous = REQUEST.with(|current| current.replace(request));
212 RequestScope {
213 previous,
214 io,
215 _thread: PhantomData,
216 }
217 }
218
219 pub fn fork(&self) -> Self {
221 Self {
222 identity: Arc::clone(&self.identity),
223 inherited: self.capture(),
224 retained_control: self.retained_control.clone(),
225 inherited_io: self.io_context(),
226 }
227 }
228
229 pub fn fork_with_control(&self, control: StorageReadControl) -> Self {
231 Self {
232 identity: Arc::clone(&self.identity),
233 inherited: self.capture(),
234 retained_control: Some(control),
235 inherited_io: self.io_context(),
236 }
237 }
238
239 pub fn enter(&self, control: StorageReadControl) -> StorageBackendResult<DiagnosticsScope> {
240 self.enter_with_options(control, None, IOOptions::default())
241 }
242
243 pub fn enter_measured(
244 &self,
245 control: StorageReadControl,
246 timing: bool,
247 io: IOOptions,
248 ) -> StorageBackendResult<DiagnosticsScope> {
249 self.enter_with_options(control, Some(timing), io)
250 }
251
252 pub(super) fn request_control(&self) -> Option<StorageReadControl> {
253 REQUEST.with(|request| {
254 request
255 .borrow()
256 .as_ref()
257 .filter(|request| Arc::ptr_eq(&request.identity, &self.identity))
258 .and_then(|request| request.control.clone())
259 })
260 }
261
262 pub(super) fn allocate_instance(&self) -> Result<u64, uqa_sql::SQLError> {
263 use std::sync::atomic::Ordering::Relaxed;
264 self.identity
265 .next_instance
266 .fetch_update(Relaxed, Relaxed, |next| next.checked_add(1))
267 .map_err(|_| {
268 uqa_sql::SQLError::Internal("native execution instance identities exhausted".into())
269 })
270 }
271
272 pub fn enter_with_options(
274 &self,
275 control: StorageReadControl,
276 timing: Option<bool>,
277 io: IOOptions,
278 ) -> StorageBackendResult<DiagnosticsScope> {
279 let collector = InvocationDiagnostics::new(
280 control,
281 self.capture(),
282 timing,
283 io,
284 Arc::clone(&self.identity.io_timing),
285 )?;
286 let binding = self.bind(&collector)?;
287 Ok(DiagnosticsScope {
288 _binding: binding,
289 collector,
290 })
291 }
292
293 pub fn bind(&self, collector: &CapturedDiagnostics) -> StorageBackendResult<CapturedScope> {
295 collector.control().check()?;
296 CURRENT.with(|current| {
297 let value = InvocationBinding {
298 identity: Arc::clone(&self.identity),
299 collector: Arc::clone(collector),
300 previous: current.borrow().clone(),
301 };
302 let binding = Budgeted::new(value, collector.control().memory().empty_reservation())
303 .into_shared()?;
304 *current.borrow_mut() = Some(Arc::clone(&binding));
305 Ok(CapturedScope {
306 binding,
307 _io: self.io_context().enter(),
308 _thread: PhantomData,
309 })
310 })
311 }
312}
313
314pub struct CapturedScope {
316 binding: Binding,
317 _io: IOScope,
318 _thread: PhantomData<Rc<()>>,
319}
320
321impl Drop for CapturedScope {
322 fn drop(&mut self) {
323 CURRENT.with(|current| {
324 let mut current = current.borrow_mut();
325 debug_assert!(current
326 .as_ref()
327 .is_some_and(|active| Arc::ptr_eq(active, &self.binding)));
328 current.clone_from(&self.binding.previous);
329 });
330 }
331}