Skip to main content

rustcmdpev_core/
analysis.rs

1use crate::constants::{CTE_SCAN_NODE, DELTA_ERROR_THRESHOLD, OVER_LABEL, UNDER_LABEL};
2use crate::structure::data::explain::Explain;
3use crate::structure::data::plan::Plan;
4
5pub fn calculate_planner_estimate(plan: &mut Plan) {
6    plan.analysis_flags.planner_row_estimate_factor = 0.0;
7
8    if plan.estimates.plan_rows == plan.actuals.actual_rows {
9        return;
10    }
11
12    plan.analysis_flags.planner_row_estimate_direction = UNDER_LABEL.to_string();
13    if plan.estimates.plan_rows != 0 {
14        plan.analysis_flags.planner_row_estimate_factor =
15            plan.actuals.actual_rows as f64 / plan.estimates.plan_rows as f64;
16    }
17
18    if plan.analysis_flags.planner_row_estimate_factor < 1.0 {
19        plan.analysis_flags.planner_row_estimate_factor = 0.0;
20        plan.analysis_flags.planner_row_estimate_direction = OVER_LABEL.to_string();
21        if plan.actuals.actual_rows != 0 {
22            plan.analysis_flags.planner_row_estimate_factor =
23                plan.estimates.plan_rows as f64 / plan.actuals.actual_rows as f64;
24        }
25    }
26}
27
28pub fn calculate_actuals(explain: &mut Explain, plan: &mut Plan) {
29    plan.actuals.actual_duration = plan.actuals.actual_total_time;
30    plan.actuals.actual_cost = plan.estimates.total_cost;
31
32    for child_plan in &plan.plans {
33        if child_plan.identity.node_type != CTE_SCAN_NODE {
34            plan.actuals.actual_duration -= child_plan.actuals.actual_total_time;
35            plan.actuals.actual_cost -= child_plan.estimates.total_cost;
36        }
37    }
38
39    if plan.actuals.actual_cost < 0.0 {
40        plan.actuals.actual_cost = 0.0;
41    }
42
43    explain.total_cost += plan.actuals.actual_cost;
44    plan.actuals.actual_duration *= plan.actuals.actual_loops as f64;
45}
46
47pub fn calculate_maximums(explain: &mut Explain, plan: &Plan) {
48    if explain.max_rows < plan.actuals.actual_rows {
49        explain.max_rows = plan.actuals.actual_rows;
50    }
51    if explain.max_cost < plan.actuals.actual_cost {
52        explain.max_cost = plan.actuals.actual_cost;
53    }
54    if explain.max_duration < plan.actuals.actual_duration {
55        explain.max_duration = plan.actuals.actual_duration;
56    }
57}
58
59/// Outlier comparison thresholds extracted from the analyzed explain so the
60/// recursion does not need to re-borrow `Explain` while the plan tree is held
61/// mutably.
62#[derive(Debug, Clone, Copy)]
63struct OutlierMaxima {
64    max_cost: f64,
65    max_rows: u64,
66    max_duration: f64,
67}
68
69impl OutlierMaxima {
70    fn from(explain: &Explain) -> Self {
71        Self {
72            max_cost: explain.max_cost,
73            max_rows: explain.max_rows,
74            max_duration: explain.max_duration,
75        }
76    }
77}
78
79pub fn calculate_outlier_nodes(explain: &Explain, plan: &mut Plan) {
80    let maxima = OutlierMaxima::from(explain);
81    flag_outliers(maxima, plan);
82}
83
84fn flag_outliers(maxima: OutlierMaxima, plan: &mut Plan) {
85    plan.analysis_flags.costliest =
86        (plan.actuals.actual_cost - maxima.max_cost).abs() < DELTA_ERROR_THRESHOLD;
87    plan.analysis_flags.largest = plan.actuals.actual_rows == maxima.max_rows;
88    plan.analysis_flags.slowest =
89        (plan.actuals.actual_duration - maxima.max_duration).abs() < DELTA_ERROR_THRESHOLD;
90
91    for child_plan in &mut plan.plans {
92        flag_outliers(maxima, child_plan);
93    }
94}
95
96fn process_root(explain: &mut Explain) {
97    calculate_planner_estimate(&mut explain.plan);
98    let mut plan = std::mem::take(&mut explain.plan);
99    calculate_actuals(explain, &mut plan);
100    calculate_maximums(explain, &plan);
101    explain.plan = plan;
102}
103
104fn process_child_plans(explain: &mut Explain, plans: &mut [Plan]) {
105    for child_plan in plans.iter_mut() {
106        calculate_planner_estimate(child_plan);
107        calculate_actuals(explain, child_plan);
108        calculate_maximums(explain, child_plan);
109
110        if !child_plan.plans.is_empty() {
111            let mut nested = std::mem::take(&mut child_plan.plans);
112            process_child_plans(explain, &mut nested);
113            child_plan.plans = nested;
114        }
115    }
116}
117
118pub fn process_all(mut explain: Explain) -> Explain {
119    process_root(&mut explain);
120
121    if !explain.plan.plans.is_empty() {
122        let mut child_plans = std::mem::take(&mut explain.plan.plans);
123        process_child_plans(&mut explain, &mut child_plans);
124        explain.plan.plans = child_plans;
125    }
126
127    let maxima = OutlierMaxima::from(&explain);
128    flag_outliers(maxima, &mut explain.plan);
129    explain
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135    use crate::structure::data::actuals::PlanActuals;
136    use crate::structure::data::estimates::PlanEstimates;
137
138    fn leaf(node_type: &str, total_cost: f64, total_time: f64, rows: u64) -> Plan {
139        let mut plan = Plan::default();
140        plan.identity.node_type = node_type.to_string();
141        plan.estimates = PlanEstimates {
142            total_cost,
143            ..PlanEstimates::default()
144        };
145        plan.actuals = PlanActuals {
146            actual_total_time: total_time,
147            actual_rows: rows,
148            actual_loops: 1,
149            ..PlanActuals::default()
150        };
151        plan
152    }
153
154    #[test]
155    fn calculate_planner_estimate_does_not_clone_plan() {
156        let mut plan = leaf("Seq Scan", 10.0, 1.0, 0);
157        plan.estimates.plan_rows = 100;
158        plan.actuals.actual_rows = 5;
159        calculate_planner_estimate(&mut plan);
160        assert_eq!(plan.analysis_flags.planner_row_estimate_direction, "Over");
161        assert_eq!(plan.analysis_flags.planner_row_estimate_factor, 20.0);
162    }
163
164    #[test]
165    fn calculate_actuals_subtracts_non_cte_children_in_place() {
166        let mut explain = Explain::default();
167        let mut plan = leaf("Hash Join", 10.0, 5.0, 100);
168        plan.plans.push(leaf("Seq Scan", 4.0, 2.0, 50));
169        plan.plans.push(leaf("Seq Scan", 3.0, 1.0, 50));
170
171        calculate_actuals(&mut explain, &mut plan);
172
173        assert!((plan.actuals.actual_cost - 3.0).abs() < 1e-6);
174        assert!((plan.actuals.actual_duration - 2.0).abs() < 1e-6);
175    }
176
177    #[test]
178    fn calculate_outlier_nodes_recurses_via_mutable_reference() {
179        let explain = Explain {
180            max_cost: 5.0,
181            max_rows: 10,
182            max_duration: 2.0,
183            ..Explain::default()
184        };
185
186        let mut plan = leaf("Hash Join", 5.0, 2.0, 10);
187        plan.actuals.actual_cost = 5.0;
188        plan.actuals.actual_duration = 2.0;
189        let mut child = leaf("Seq Scan", 2.0, 1.0, 5);
190        child.actuals.actual_cost = 2.0;
191        child.actuals.actual_duration = 1.0;
192        plan.plans.push(child);
193
194        calculate_outlier_nodes(&explain, &mut plan);
195
196        assert!(plan.analysis_flags.costliest);
197        assert!(plan.analysis_flags.largest);
198        assert!(plan.analysis_flags.slowest);
199        assert!(!plan.plans[0].analysis_flags.costliest);
200        assert!(!plan.plans[0].analysis_flags.slowest);
201    }
202
203    #[test]
204    fn process_all_threads_through_without_per_node_clones() {
205        let mut root = leaf("Hash Join", 10.0, 5.0, 100);
206        root.plans.push(leaf("Seq Scan", 4.0, 2.0, 50));
207        root.plans.push(leaf("Seq Scan", 3.0, 1.0, 50));
208        let explain = Explain {
209            execution_time: 5.0,
210            plan: root,
211            ..Explain::default()
212        };
213
214        let processed = process_all(explain);
215
216        assert_eq!(processed.plan.plans.len(), 2);
217        assert!(processed.max_cost > 0.0);
218        assert!(processed.plan.analysis_flags.costliest || processed.plan.analysis_flags.slowest);
219    }
220}