Skip to main content

fallow_types/
pipeline_spans.rs

1//! The `--performance` span tree and the process-level clock.
2//!
3//! The flat stage fields of [`PipelineTimings`](crate::trace::PipelineTimings)
4//! come from separate clocks. Some stages run before the `total_ms` clock
5//! starts, and duplication can run at the same time as the dead-code pass. A
6//! reader who adds the flat fields gets a number larger than `total_ms` and
7//! cannot tell why. The span tree states the structure: which span contains
8//! which, and which spans overlap their siblings.
9
10use serde::Serialize;
11
12use crate::trace::PipelineTimings;
13
14/// Process-level spans around the analysis pipeline.
15///
16/// The pipeline stages cover only part of a command. These spans cover the
17/// rest: argument parsing, the thread pool, config loading, git, the work after
18/// the analysis and the report output. `wall_ms` is the time from process start
19/// to this report, so `wall_ms` minus the sum of the other spans is time that
20/// no span measured.
21#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
22#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
23pub struct ProcessTimings {
24    /// Time from process start to this report.
25    pub wall_ms: f64,
26    /// Time from process start until the command starts: argument parsing,
27    /// logging setup and the thread pool.
28    pub startup_ms: f64,
29    /// The part of `startup_ms` that builds the worker thread pool.
30    pub thread_pool_ms: f64,
31    /// Config loading and validation for the command. The config load
32    /// discovers the workspaces, so `workspaces_ms` is a part of this span.
33    pub config_ms: f64,
34    /// Git calls outside the pipeline, for example `--changed-since`.
35    pub git_ms: f64,
36    /// The analysis call. The pipeline stage fields other than
37    /// `workspaces_ms` are parts of this span.
38    pub analysis_ms: f64,
39    /// Work after the analysis and before the output: scope filters, rules,
40    /// baselines and gates.
41    pub post_analysis_ms: f64,
42    /// Report serialization and write.
43    pub output_ms: f64,
44}
45
46/// One node of the `--performance` span tree.
47#[derive(Debug, Clone, PartialEq, Serialize)]
48#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
49pub struct PipelineSpan {
50    /// Stable span name. Each name occurs at most once in a tree.
51    pub name: &'static str,
52    /// Name of the span that contains this span. `None` for a root span.
53    pub parent: Option<&'static str>,
54    /// Wall-clock milliseconds of this span.
55    pub ms: f64,
56    /// True when the span runs at the same time as its siblings. Its time
57    /// then overlaps theirs and does not add to the parent.
58    pub concurrent: bool,
59}
60
61/// Inputs for [`pipeline_span_tree`].
62#[derive(Debug, Clone, Copy)]
63pub struct SpanTreeInput<'a> {
64    /// The pipeline stage timings.
65    pub timings: &'a PipelineTimings,
66    /// The process-level spans, when the caller measured them.
67    pub process: Option<&'a ProcessTimings>,
68    /// True when duplication ran at the same time as the dead-code pass.
69    pub duplication_concurrent: bool,
70}
71
72struct TreeBuilder {
73    spans: Vec<PipelineSpan>,
74}
75
76impl TreeBuilder {
77    fn push(&mut self, name: &'static str, parent: Option<&'static str>, ms: f64) {
78        self.spans.push(PipelineSpan {
79            name,
80            parent,
81            ms,
82            concurrent: false,
83        });
84    }
85}
86
87/// Build the span tree for one `--performance` report.
88///
89/// Spans come in pipeline order, and a parent always comes before its
90/// children. With process spans, `process` is the only root, `workspaces`
91/// sits under `config`, and the other pipeline stages sit under `analysis`.
92/// The config load discovers the workspaces before the analysis starts.
93/// Without process spans, the pipeline stages are the roots.
94#[must_use]
95pub fn pipeline_span_tree(input: SpanTreeInput<'_>) -> Vec<PipelineSpan> {
96    let t = input.timings;
97    let mut tree = TreeBuilder {
98        spans: Vec::with_capacity(32),
99    };
100
101    let (config_parent, analysis_parent) = input.process.map_or((None, None), |process| {
102        tree.push("process", None, process.wall_ms);
103        tree.push("startup", Some("process"), process.startup_ms);
104        tree.push("thread_pool", Some("startup"), process.thread_pool_ms);
105        tree.push("config", Some("process"), process.config_ms);
106        tree.push("git", Some("process"), process.git_ms);
107        tree.push("analysis", Some("process"), process.analysis_ms);
108        (Some("config"), Some("analysis"))
109    });
110
111    tree.push("workspaces", config_parent, t.workspaces_ms);
112    tree.push("discover_files", analysis_parent, t.discover_files_ms);
113    tree.push("parse_extract", analysis_parent, t.parse_extract_ms);
114    tree.push(
115        "parse_cache_load",
116        Some("parse_extract"),
117        t.parse_cache_load_ms,
118    );
119    tree.push("cache_update", analysis_parent, t.cache_update_ms);
120    tree.push("pipeline", analysis_parent, t.total_ms);
121    tree.push("plugins", Some("pipeline"), t.plugins_ms);
122    tree.push("script_analysis", Some("pipeline"), t.script_analysis_ms);
123    push_entry_point_spans(&mut tree, t);
124    tree.push("resolve_imports", Some("pipeline"), t.resolve_imports_ms);
125    tree.push("build_graph", Some("pipeline"), t.build_graph_ms);
126    tree.push("analyze", Some("pipeline"), t.analyze_ms);
127
128    if let Some(duplication_ms) = t.duplication_ms {
129        let parent = input.process.map(|_| "process");
130        tree.spans.push(PipelineSpan {
131            name: "duplication",
132            parent,
133            ms: duplication_ms,
134            concurrent: input.duplication_concurrent,
135        });
136    }
137
138    if let Some(process) = input.process {
139        tree.push("post_analysis", Some("process"), process.post_analysis_ms);
140        tree.push("output", Some("process"), process.output_ms);
141    }
142
143    tree.spans
144}
145
146fn push_entry_point_spans(tree: &mut TreeBuilder, t: &PipelineTimings) {
147    let spans = t.entry_point_spans;
148    tree.push("entry_points", Some("pipeline"), t.entry_points_ms);
149    tree.push("entry_points_root", Some("entry_points"), spans.root_ms);
150    tree.push(
151        "entry_points_workspaces",
152        Some("entry_points"),
153        spans.workspaces_ms,
154    );
155    tree.push("plugin_globs", Some("entry_points"), spans.plugins_ms);
156    tree.push(
157        "plugin_glob_compile",
158        Some("plugin_globs"),
159        spans.plugin_glob_build_ms,
160    );
161    tree.push(
162        "plugin_glob_match",
163        Some("plugin_globs"),
164        spans.plugin_glob_match_ms,
165    );
166    tree.push(
167        "entry_points_infrastructure",
168        Some("entry_points"),
169        spans.infrastructure_ms,
170    );
171    tree.push(
172        "entry_points_dynamic",
173        Some("entry_points"),
174        spans.dynamic_ms,
175    );
176    tree.push("entry_points_dedup", Some("entry_points"), spans.dedup_ms);
177}
178
179#[cfg(test)]
180mod tests {
181    use rustc_hash::FxHashSet;
182
183    use super::*;
184    use crate::trace::{EntryPointSpans, PipelineCounters};
185
186    fn timings(duplication_ms: Option<f64>) -> PipelineTimings {
187        PipelineTimings {
188            discover_files_ms: 8.0,
189            file_count: 10,
190            workspaces_ms: 1.0,
191            workspace_count: 0,
192            plugins_ms: 2.0,
193            script_analysis_ms: 0.5,
194            parse_extract_ms: 18.0,
195            parse_cpu_ms: 30.0,
196            parse_cache_load_ms: 3.0,
197            module_count: 10,
198            cache_hits: 0,
199            cache_misses: 10,
200            cache_rejection: None,
201            graph_cache_rejection: None,
202            cache_update_ms: 2.0,
203            entry_points_ms: 3.0,
204            entry_point_spans: EntryPointSpans::default(),
205            entry_point_count: 1,
206            resolve_imports_ms: 8.0,
207            build_graph_ms: 2.0,
208            analyze_ms: 10.0,
209            duplication_ms,
210            total_ms: 35.0,
211            counters: PipelineCounters::default(),
212        }
213    }
214
215    fn parent_of<'a>(tree: &'a [PipelineSpan], name: &str) -> Option<&'a str> {
216        tree.iter()
217            .find(|span| span.name == name)
218            .unwrap_or_else(|| panic!("span {name} missing from {tree:#?}"))
219            .parent
220    }
221
222    /// Every parent is a span of the tree, it comes before its children, and
223    /// no name occurs twice.
224    fn assert_well_formed(tree: &[PipelineSpan]) {
225        let mut seen: FxHashSet<&str> = FxHashSet::default();
226        for span in tree {
227            if let Some(parent) = span.parent {
228                assert!(
229                    seen.contains(parent),
230                    "{} names parent {parent} before it",
231                    span.name
232                );
233            }
234            assert!(seen.insert(span.name), "duplicate span {}", span.name);
235        }
236    }
237
238    #[test]
239    fn stages_before_the_total_clock_are_siblings_of_the_pipeline() {
240        let tree = pipeline_span_tree(SpanTreeInput {
241            timings: &timings(None),
242            process: None,
243            duplication_concurrent: false,
244        });
245        assert_well_formed(&tree);
246        for root in [
247            "workspaces",
248            "discover_files",
249            "parse_extract",
250            "cache_update",
251            "pipeline",
252        ] {
253            assert_eq!(parent_of(&tree, root), None, "{root}");
254        }
255        for stage in [
256            "plugins",
257            "script_analysis",
258            "entry_points",
259            "resolve_imports",
260            "build_graph",
261            "analyze",
262        ] {
263            assert_eq!(parent_of(&tree, stage), Some("pipeline"), "{stage}");
264        }
265        assert_eq!(parent_of(&tree, "parse_cache_load"), Some("parse_extract"));
266        assert_eq!(parent_of(&tree, "plugin_glob_match"), Some("plugin_globs"));
267        assert!(tree.iter().all(|span| !span.concurrent));
268        assert!(tree.iter().all(|span| span.name != "duplication"));
269    }
270
271    #[test]
272    fn process_spans_put_the_pipeline_under_the_analysis_span() {
273        let process = ProcessTimings {
274            wall_ms: 55.0,
275            startup_ms: 4.0,
276            thread_pool_ms: 1.0,
277            config_ms: 2.0,
278            git_ms: 0.0,
279            analysis_ms: 40.0,
280            post_analysis_ms: 1.0,
281            output_ms: 3.0,
282        };
283        let tree = pipeline_span_tree(SpanTreeInput {
284            timings: &timings(Some(12.0)),
285            process: Some(&process),
286            duplication_concurrent: true,
287        });
288        assert_well_formed(&tree);
289        assert_eq!(tree[0].name, "process");
290        assert_eq!(tree.iter().filter(|span| span.parent.is_none()).count(), 1);
291        assert_eq!(parent_of(&tree, "thread_pool"), Some("startup"));
292        assert_eq!(parent_of(&tree, "workspaces"), Some("config"));
293        assert_eq!(parent_of(&tree, "discover_files"), Some("analysis"));
294        assert_eq!(parent_of(&tree, "parse_extract"), Some("analysis"));
295        assert_eq!(parent_of(&tree, "pipeline"), Some("analysis"));
296        assert_eq!(parent_of(&tree, "output"), Some("process"));
297        let duplication = tree
298            .iter()
299            .find(|span| span.name == "duplication")
300            .expect("duplication span");
301        assert_eq!(duplication.parent, Some("process"));
302        assert!(duplication.concurrent);
303    }
304
305    /// Combined mode reports no process spans. The duplication span is then
306    /// a root, and it keeps the concurrency that the caller gives.
307    #[test]
308    fn duplication_without_process_spans_is_a_root_with_its_concurrency() {
309        for concurrent in [true, false] {
310            let tree = pipeline_span_tree(SpanTreeInput {
311                timings: &timings(Some(12.0)),
312                process: None,
313                duplication_concurrent: concurrent,
314            });
315            assert_well_formed(&tree);
316            let duplication = tree
317                .iter()
318                .find(|span| span.name == "duplication")
319                .expect("duplication span");
320            assert_eq!(duplication.parent, None);
321            assert_eq!(duplication.concurrent, concurrent);
322            assert!(tree.iter().all(|span| span.name != "output"));
323        }
324    }
325}