|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use std::any::Any; |
| 19 | +use std::collections::VecDeque; |
| 20 | +use std::ops::Deref; |
| 21 | +use std::sync::{Arc, LazyLock}; |
| 22 | + |
| 23 | +use datafusion_common::{HashMap, HashSet}; |
| 24 | +use datafusion_common_runtime::{set_join_set_tracer, JoinSetTracer}; |
| 25 | +use futures::future::BoxFuture; |
| 26 | +use tokio::sync::{Mutex, MutexGuard}; |
| 27 | + |
| 28 | +/// Initializes the global join set tracer with the asserting tracer. |
| 29 | +/// Call this function before spawning any tasks that should be traced. |
| 30 | +pub fn init_asserting_tracer() { |
| 31 | + set_join_set_tracer(ASSERTING_TRACER.deref()) |
| 32 | + .expect("Failed to initialize asserting tracer"); |
| 33 | +} |
| 34 | + |
| 35 | +/// Verifies that the current task has a traceable ancestry back to "root". |
| 36 | +/// |
| 37 | +/// The function performs a breadth-first search (BFS) in the global spawn graph: |
| 38 | +/// - It starts at the current task and follows parent links. |
| 39 | +/// - If it reaches the "root" task, the ancestry is valid. |
| 40 | +/// - If a task is missing from the graph, it panics. |
| 41 | +/// |
| 42 | +/// Note: Tokio task IDs are unique only while a task is active. |
| 43 | +/// Once a task completes, its ID may be reused. |
| 44 | +pub async fn assert_traceability() { |
| 45 | + // Acquire the spawn graph lock. |
| 46 | + let spawn_graph = acquire_spawn_graph().await; |
| 47 | + |
| 48 | + // Start BFS with the current task. |
| 49 | + let mut tasks_to_check = VecDeque::from(vec![current_task()]); |
| 50 | + |
| 51 | + while let Some(task_id) = tasks_to_check.pop_front() { |
| 52 | + if task_id == "root" { |
| 53 | + // Ancestry reached the root. |
| 54 | + continue; |
| 55 | + } |
| 56 | + // Obtain parent tasks, panicking if the task is not present. |
| 57 | + let parents = spawn_graph |
| 58 | + .get(&task_id) |
| 59 | + .expect("Task ID not found in spawn graph"); |
| 60 | + // Queue each parent for checking. |
| 61 | + for parent in parents { |
| 62 | + tasks_to_check.push_back(parent.clone()); |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +/// Tracer that maintains a graph of task ancestry for tracing purposes. |
| 68 | +/// |
| 69 | +/// For each task, it records a set of parent task IDs to ensure that every |
| 70 | +/// asynchronous task can be traced back to "root". |
| 71 | +struct AssertingTracer { |
| 72 | + /// An asynchronous map from task IDs to their parent task IDs. |
| 73 | + spawn_graph: Arc<Mutex<HashMap<String, HashSet<String>>>>, |
| 74 | +} |
| 75 | + |
| 76 | +/// Lazily initialized global instance of `AssertingTracer`. |
| 77 | +static ASSERTING_TRACER: LazyLock<AssertingTracer> = LazyLock::new(AssertingTracer::new); |
| 78 | + |
| 79 | +impl AssertingTracer { |
| 80 | + /// Creates a new `AssertingTracer` with an empty spawn graph. |
| 81 | + fn new() -> Self { |
| 82 | + Self { |
| 83 | + spawn_graph: Arc::default(), |
| 84 | + } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +/// Returns the current task's ID as a string, or "root" if unavailable. |
| 89 | +/// |
| 90 | +/// Tokio guarantees task IDs are unique only among active tasks, |
| 91 | +/// so completed tasks may have their IDs reused. |
| 92 | +fn current_task() -> String { |
| 93 | + tokio::task::try_id() |
| 94 | + .map(|id| format!("{id}")) |
| 95 | + .unwrap_or_else(|| "root".to_string()) |
| 96 | +} |
| 97 | + |
| 98 | +/// Asynchronously locks and returns the spawn graph. |
| 99 | +/// |
| 100 | +/// The returned guard allows inspection or modification of task ancestry. |
| 101 | +async fn acquire_spawn_graph<'a>() -> MutexGuard<'a, HashMap<String, HashSet<String>>> { |
| 102 | + ASSERTING_TRACER.spawn_graph.lock().await |
| 103 | +} |
| 104 | + |
| 105 | +/// Registers the current task as a child of `parent_id` in the spawn graph. |
| 106 | +async fn register_task(parent_id: String) { |
| 107 | + acquire_spawn_graph() |
| 108 | + .await |
| 109 | + .entry(current_task()) |
| 110 | + .or_insert_with(HashSet::new) |
| 111 | + .insert(parent_id); |
| 112 | +} |
| 113 | + |
| 114 | +impl JoinSetTracer for AssertingTracer { |
| 115 | + /// Wraps an asynchronous future to record its parent task before execution. |
| 116 | + fn trace_future( |
| 117 | + &self, |
| 118 | + fut: BoxFuture<'static, Box<dyn Any + Send>>, |
| 119 | + ) -> BoxFuture<'static, Box<dyn Any + Send>> { |
| 120 | + // Capture the parent task ID. |
| 121 | + let parent_id = current_task(); |
| 122 | + Box::pin(async move { |
| 123 | + // Register the parent-child relationship. |
| 124 | + register_task(parent_id).await; |
| 125 | + // Execute the wrapped future. |
| 126 | + fut.await |
| 127 | + }) |
| 128 | + } |
| 129 | + |
| 130 | + /// Wraps a blocking closure to record its parent task before execution. |
| 131 | + fn trace_block( |
| 132 | + &self, |
| 133 | + f: Box<dyn FnOnce() -> Box<dyn Any + Send> + Send>, |
| 134 | + ) -> Box<dyn FnOnce() -> Box<dyn Any + Send> + Send> { |
| 135 | + let parent_id = current_task(); |
| 136 | + Box::new(move || { |
| 137 | + // Synchronously record the task relationship. |
| 138 | + futures::executor::block_on(register_task(parent_id)); |
| 139 | + f() |
| 140 | + }) |
| 141 | + } |
| 142 | +} |
0 commit comments