Skip to main content

micromegas_analytics/
call_tree.rs

1use crate::arrow_properties::serialize_property_set_to_jsonb;
2use crate::metadata::{StreamMetadata, get_thread_name_from_stream_metadata};
3use crate::properties::jsonb_dictionary::JsonbDictionary;
4use crate::properties::property_set::PropertySet;
5use crate::scope::BorrowedScopeDesc;
6use crate::scope::ScopeDesc;
7use crate::scope::ScopeHashMap;
8use crate::thread_block_processor::ThreadBlockProcessor;
9use crate::thread_block_processor::parse_thread_block;
10use crate::time::ConvertTicks;
11use anyhow::Result;
12use micromegas_telemetry::blob_storage::BlobStorage;
13use micromegas_telemetry::types::block::BlockMetadata;
14use micromegas_tracing::prelude::*;
15use std::sync::Arc;
16
17/// Maximum nesting depth of a call tree. Far above real instrumented call depth, so it only
18/// rejects malformed or hostile blocks, which a few bytes per unmatched begin event can make
19/// arbitrarily deep.
20pub const MAX_CALL_TREE_DEPTH: usize = 4096;
21
22/// A node in a call tree, representing a single scope instance.
23#[derive(Debug)]
24pub struct CallTreeNode {
25    /// The unique identifier of the scope instance.
26    pub id: Option<i64>,
27    /// The hash of the scope description.
28    pub hash: u32,
29    /// The start time of the scope instance in nanoseconds.
30    pub begin: i64, //absolute nanoseconds
31    /// The end time of the scope instance in nanoseconds.
32    pub end: i64,
33    /// The children of this node in the call tree.
34    pub children: Vec<CallTreeNode>,
35    /// Index into `CallTree::property_sets` of the properties on the span's end event; 0 is the
36    /// empty set.
37    pub properties: i32,
38}
39
40impl Drop for CallTreeNode {
41    // The derived drop recurses once per level and overflows the stack on deep chains.
42    fn drop(&mut self) {
43        let mut pending = std::mem::take(&mut self.children);
44        while let Some(mut node) = pending.pop() {
45            pending.append(&mut node.children);
46        }
47    }
48}
49
50/// A call tree, representing the execution of a single thread.
51#[derive(Debug)]
52pub struct CallTree {
53    /// A map from scope hash to scope description.
54    pub scopes: ScopeHashMap,
55    /// The root node of the call tree.
56    // the root node corresponds to the thread and has a span equal to the query range
57    pub call_tree_root: Option<CallTreeNode>,
58    /// The JSONB property sets that the nodes refer to.
59    pub property_sets: JsonbDictionary,
60}
61
62/// A builder for creating a `CallTree` from a stream of thread events.
63pub struct CallTreeBuilder {
64    begin_range_ns: i64,
65    end_range_ns: i64,
66    limit: Option<i64>,
67    nb_spans: i64,
68    stack: Vec<CallTreeNode>,
69    // Root wrapping deepens the tree without growing `stack`, so the stack length alone does
70    // not bound the depth.
71    tree_depth: usize,
72    scopes: ScopeHashMap,
73    property_sets: JsonbDictionary,
74    convert_ticks: ConvertTicks,
75    root_hash: u32,
76}
77
78impl CallTreeBuilder {
79    pub fn new(
80        begin_range_ns: i64,
81        end_range_ns: i64,
82        limit: Option<i64>,
83        convert_ticks: ConvertTicks,
84        thread_name: String,
85    ) -> Self {
86        let thread_scope_desc = ScopeDesc::new(
87            Arc::new(thread_name),
88            Arc::new("".to_owned()),
89            Arc::new("".to_owned()),
90            0,
91        );
92        let mut scopes = ScopeHashMap::new();
93        let root_hash = thread_scope_desc.hash;
94        scopes.insert(root_hash, thread_scope_desc);
95        Self {
96            begin_range_ns,
97            end_range_ns,
98            limit,
99            nb_spans: 0,
100            stack: Vec::new(),
101            tree_depth: 0,
102            scopes,
103            property_sets: JsonbDictionary::new(),
104            convert_ticks,
105            root_hash,
106        }
107    }
108
109    #[span_fn]
110    pub fn finish(mut self) -> CallTree {
111        if self.stack.is_empty() {
112            return CallTree {
113                scopes: self.scopes,
114                call_tree_root: None,
115                property_sets: self.property_sets,
116            };
117        }
118        while self.stack.len() > 1 {
119            let top = self.stack.pop().unwrap();
120            let last_index = self.stack.len() - 1;
121            let parent = &mut self.stack[last_index];
122            parent.children.push(top);
123        }
124        assert_eq!(1, self.stack.len());
125        CallTree {
126            scopes: self.scopes,
127            call_tree_root: self.stack.pop(),
128            property_sets: self.property_sets,
129        }
130    }
131
132    fn add_child_to_top(&mut self, block_id: &str, node: CallTreeNode) -> Result<()> {
133        if let Some(mut top) = self.stack.pop() {
134            top.children.push(node);
135            self.stack.push(top);
136        } else {
137            let wrapped_depth = self.tree_depth.max(1);
138            if wrapped_depth >= MAX_CALL_TREE_DEPTH {
139                anyhow::bail!("call tree depth exceeds {MAX_CALL_TREE_DEPTH} in block {block_id}");
140            }
141            self.tree_depth = wrapped_depth + 1;
142            let new_root = CallTreeNode {
143                id: None,
144                hash: self.root_hash,
145                begin: self.begin_range_ns,
146                end: self.end_range_ns,
147                children: vec![node],
148                properties: 0,
149            };
150            self.stack.push(new_root);
151            self.nb_spans += 1;
152        }
153        Ok(())
154    }
155
156    fn intern_properties(&mut self, properties: &PropertySet<'_>) -> Result<i32> {
157        let mut is_empty = true;
158        properties.for_each_property(|_, _| {
159            is_empty = false;
160            Ok(())
161        })?;
162        if is_empty {
163            return Ok(0);
164        }
165        let jsonb = serialize_property_set_to_jsonb(properties)?;
166        Ok(self.property_sets.intern(&jsonb))
167    }
168
169    fn record_scope_desc(&mut self, scope_desc: BorrowedScopeDesc<'_>) {
170        // Own the scope strings only on first encounter (once per distinct scope),
171        // not per event — the borrowed scope comes from the per-block arena.
172        self.scopes
173            .entry(scope_desc.hash)
174            .or_insert_with(|| scope_desc.to_owned());
175    }
176}
177
178impl ThreadBlockProcessor for CallTreeBuilder {
179    fn on_begin_thread_scope(
180        &mut self,
181        block_id: &str,
182        event_id: i64,
183        scope: BorrowedScopeDesc<'_>,
184        ts: i64,
185    ) -> Result<bool> {
186        if self.limit.is_some() && self.nb_spans >= self.limit.unwrap() {
187            return Ok(false);
188        }
189        let time = self.convert_ticks.ticks_to_nanoseconds(ts);
190        if time < self.begin_range_ns {
191            return Ok(true);
192        }
193        if time > self.end_range_ns {
194            return Ok(false);
195        }
196        if self.stack.len() >= MAX_CALL_TREE_DEPTH {
197            anyhow::bail!("call tree depth exceeds {MAX_CALL_TREE_DEPTH} in block {block_id}");
198        }
199        let hash = scope.hash;
200        self.record_scope_desc(scope);
201        let node = CallTreeNode {
202            id: Some(event_id),
203            hash,
204            begin: time,
205            end: self.end_range_ns,
206            children: Vec::new(),
207            properties: 0,
208        };
209        self.stack.push(node);
210        self.tree_depth = self.tree_depth.max(self.stack.len());
211        self.nb_spans += 1;
212        Ok(true) // continue even if we reached the limit to allow the opportunity to close than span
213    }
214
215    fn on_end_thread_scope(
216        &mut self,
217        block_id: &str,
218        event_id: i64,
219        scope: BorrowedScopeDesc<'_>,
220        ts: i64,
221        properties: PropertySet<'_>,
222    ) -> Result<bool> {
223        let time = self.convert_ticks.ticks_to_nanoseconds(ts);
224        if time < self.begin_range_ns {
225            return Ok(true);
226        }
227        if time > self.end_range_ns {
228            return Ok(false);
229        }
230        let hash = scope.hash;
231        self.record_scope_desc(scope);
232        let properties = self.intern_properties(&properties)?;
233        if let Some(mut old_top) = self.stack.pop() {
234            if old_top.hash == hash {
235                old_top.end = time;
236                old_top.properties = properties;
237                self.add_child_to_top(block_id, old_top)?;
238            } else if old_top.hash == self.root_hash {
239                old_top.id = Some(event_id);
240                old_top.hash = hash;
241                old_top.end = time;
242                old_top.properties = properties;
243                self.add_child_to_top(block_id, old_top)?;
244            } else {
245                let ending_name = self.scopes.get(&hash).map_or("?", |s| s.name.as_str());
246                let open_name = self
247                    .scopes
248                    .get(&old_top.hash)
249                    .map_or("?", |s| s.name.as_str());
250                anyhow::bail!(
251                    "top scope mismatch in block {block_id}: closing '{ending_name}' but '{open_name}' is open"
252                );
253            }
254        } else {
255            if self.limit.is_some() && self.nb_spans >= self.limit.unwrap() {
256                return Ok(false);
257            }
258            let node = CallTreeNode {
259                id: Some(event_id),
260                hash,
261                begin: self.begin_range_ns,
262                end: time,
263                children: Vec::new(),
264                properties,
265            };
266            self.add_child_to_top(block_id, node)?;
267        }
268        Ok(true)
269    }
270}
271
272/// Creates a call tree from a set of thread event blocks.
273#[allow(clippy::cast_precision_loss)]
274#[span_fn]
275pub async fn make_call_tree(
276    blocks: &[BlockMetadata],
277    begin_range_ns: i64,
278    end_range_ns: i64,
279    limit: Option<i64>,
280    blob_storage: Arc<BlobStorage>,
281    convert_ticks: ConvertTicks,
282    stream: &StreamMetadata,
283) -> Result<CallTree> {
284    let mut builder = CallTreeBuilder::new(
285        begin_range_ns,
286        end_range_ns,
287        limit,
288        convert_ticks,
289        get_thread_name_from_stream_metadata(stream)?,
290    );
291    for block in blocks {
292        parse_thread_block(
293            blob_storage.clone(),
294            stream,
295            block.block_id,
296            block.object_offset,
297            &mut builder,
298        )
299        .await?;
300    }
301    Ok(builder.finish())
302}