Skip to main content

cfd_craft/
profiling.rs

1//! Opt-in wall-time accounting at solver phase boundaries.
2//!
3//! Inclusive phases nest; only exclusive times can be added. One collector can
4//! be shared by callers on different threads, with a separate stack per thread.
5//! No lock or clock read is required inside a numerical cell/PCG iteration.
6//!
7//! Enable it with [`Control::with_profiling`](crate::solver::Control::with_profiling)
8//! and read the [`Profile`] with
9//! [`Control::profile`](crate::solver::Control::profile) after the solve.
10//! The CLI's `profile` command writes the same record into its
11//! `cfd-craft.native-profile/0.1` envelope; its JSON schema is the
12//! `phase_profile_schema` of `cfd-craft describe`. See the
13//! [profiling guide](https://github.com/dietmarwo/CFD-craft/blob/main/docs/developer/profiling.md).
14//!
15//! ```
16//! # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
17//! #   "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
18//! #   "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
19//! #   "flow": {"kind": "laminar", "initial_velocity_m_s": [1.0, 0.0, 0.0],
20//! #            "viscosity_m2_s": 0.1},
21//! #   "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
22//! #     "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
23//! #     "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
24//! #     "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
25//! #   "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 3,
26//! #     "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
27//! #   "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
28//! use cfd_craft::{case::Case, solver::{self, Control}};
29//!
30//! let case: Case = serde_json::from_str(json).unwrap();
31//! let control = Control::new(30.0).with_profiling();
32//! let result = solver::run(&case, &control, None)?;
33//! let profile = control.profile()?.expect("profiling enabled");
34//! assert_eq!(profile.phases["step"].calls, 3);
35//! // Exclusive times add up; inclusive times nest and must not be summed.
36//! let total: f64 = profile.phases.values().map(|p| p.exclusive_s).sum();
37//! assert!((total - profile.accounted_exclusive_s).abs() < 1e-12);
38//! // Attempted pressure work covers at least the retained iterations.
39//! assert!(profile.phases["pressure_solve"].work_units >= result.summary.pressure_iterations as u64);
40//! # Ok::<(), String>(())
41//! ```
42use crate::Result;
43use schemars::JsonSchema;
44use serde::{Deserialize, Serialize};
45use std::{
46    collections::{BTreeMap, HashMap},
47    marker::PhantomData,
48    rc::Rc,
49    sync::{Arc, Mutex},
50    thread::{self, ThreadId},
51    time::{Duration, Instant},
52};
53
54/// A measured solver phase. Its snake_case name (for example
55/// `pressure_solve`) is the key in [`Profile::phases`]. Phases nest: an
56/// enclosing phase's inclusive time contains its subphases.
57#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, JsonSchema)]
58#[serde(rename_all = "snake_case")]
59pub enum Phase {
60    /// One whole [`solver::run`](crate::solver::run) call.
61    SolverRun,
62    /// Semantic case checks at the start of a run.
63    CaseValidation,
64    /// Building the grid.
65    GridSetup,
66    /// Source densities and receptor weights.
67    InputSetup,
68    /// Initial or restart state, its validation and hash.
69    StateSetup,
70    /// Choosing the next time step, including the eddy-viscosity check.
71    Timestep,
72    /// One transactional step with its momentum, pressure, turbulence and
73    /// scalar subphases.
74    Step,
75    /// Evaluating the momentum right-hand side.
76    MomentumRhs,
77    /// Inexact implicit momentum-correction solves; work units are inner iterations.
78    MomentumSolve,
79    /// Forming the momentum update (and assembling implicit matrices) before
80    /// the projection.
81    VelocityUpdate,
82    /// A pressure projection, including its solve.
83    PressureProjection,
84    /// A pressure PCG solve; work units are attempted iterations.
85    PressureSolve,
86    /// Building the cached IC(0) factor; occurs only when it is built.
87    PressureFactorSetup,
88    /// Building the multigrid hierarchy; occurs only when it is (re)built.
89    PressureMultigridSetup,
90    /// Gathering the compact operator of one pressure solve.
91    PressureOperatorSetup,
92    /// A k-epsilon update: in each `neutral_rans` step, and once after the
93    /// initial projection.
94    Turbulence,
95    /// Inexact implicit k and ε correction solves; work units are inner iterations.
96    TurbulenceSolve,
97    /// Transport of one constituent within a step.
98    ScalarTransport,
99    /// Checking the candidate state before it is committed.
100    StateValidation,
101    /// Appending a monitor row.
102    Monitor,
103    /// Recomputing the numerical checks.
104    Assessment,
105    /// Writing the run archive (CLI).
106    ArchiveWrite,
107}
108
109/// Accumulated time and work of one phase over all its calls.
110#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
111#[serde(deny_unknown_fields)]
112pub struct PhaseTiming {
113    /// Number of finished spans of this phase.
114    pub calls: u64,
115    /// Wall seconds including nested phases. Do not add these up.
116    pub inclusive_s: f64,
117    /// Wall seconds excluding nested phases; these add up to
118    /// `accounted_exclusive_s`.
119    pub exclusive_s: f64,
120    /// Attempted inner iterations: PCG for pressure_solve, the implicit
121    /// correction solves for momentum_solve and turbulence_solve; zero for other phases.
122    pub work_units: u64,
123    /// Operator products: the compact pressure products plus the independent
124    /// true-residual products of pressure_solve, and one (CG) or two
125    /// (BiCGStab) per inner iteration of the implicit solves.
126    pub operator_applications: u64,
127    /// Applications of the selected preconditioner.
128    pub preconditioner_applications: u64,
129    /// Independent face-by-face residual recomputations of pressure_solve.
130    pub true_residual_checks: u64,
131    /// Multilevel work of pressure_solve with the multigrid preconditioner;
132    /// omitted otherwise.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub multigrid: Option<crate::multigrid::MultigridWork>,
135}
136
137/// A phase profile (schema `cfd-craft.phase-profile/0.1`): wall time and
138/// work per solver phase. Only exclusive times may be added. Work includes
139/// failed attempts, so it can exceed the counters of the retained state.
140#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
141#[serde(deny_unknown_fields)]
142pub struct Profile {
143    /// Always `cfd-craft.phase-profile/0.1`.
144    pub schema_version: String,
145    /// Wall seconds since the control was created, at the snapshot.
146    pub elapsed_s: f64,
147    /// Sum of the exclusive seconds of all phases.
148    pub accounted_exclusive_s: f64,
149    /// Elapsed minus exclusive phases for a single serial invocation. Parallel
150    /// callers may have aggregate phase time exceeding elapsed wall time.
151    pub unattributed_s: f64,
152    /// Timing of each phase that ran, keyed by its snake_case phase name.
153    pub phases: BTreeMap<String, PhaseTiming>,
154}
155
156#[derive(Default)]
157struct Frame {
158    id: u64,
159    children: Duration,
160}
161#[derive(Default)]
162struct Data {
163    phases: BTreeMap<String, PhaseTiming>,
164    stacks: HashMap<ThreadId, Vec<Frame>>,
165    next_id: u64,
166    invalid_nesting: bool,
167}
168#[derive(Clone, Default)]
169pub(crate) struct Collector(Arc<Mutex<Data>>);
170
171impl Collector {
172    pub(crate) fn span(&self, phase: Phase) -> Span {
173        let thread = thread::current().id();
174        let mut data = self.0.lock().unwrap_or_else(|e| e.into_inner());
175        let id = data.next_id;
176        data.next_id += 1;
177        data.stacks.entry(thread).or_default().push(Frame {
178            id,
179            ..Frame::default()
180        });
181        Span {
182            active: Some((self.clone(), phase, thread, id, Instant::now())),
183            work_units: 0,
184            operator_applications: 0,
185            preconditioner_applications: 0,
186            true_residual_checks: 0,
187            multigrid: None,
188            // A span must finish on the thread whose phase stack it entered.
189            _same_thread: PhantomData,
190        }
191    }
192    pub(crate) fn snapshot(&self, elapsed_s: f64) -> Result<Profile> {
193        let data = self.0.lock().unwrap_or_else(|e| e.into_inner());
194        if data.invalid_nesting {
195            return Err("CFD-B003 profile.nesting: spans must finish in nested order".into());
196        }
197        if data.stacks.values().any(|s| !s.is_empty()) {
198            return Err("CFD-B003 profile.active: finish all phase spans before snapshot".into());
199        }
200        let phases = data.phases.clone();
201        let accounted_exclusive_s = phases.values().map(|p| p.exclusive_s).sum::<f64>();
202        Ok(Profile {
203            schema_version: "cfd-craft.phase-profile/0.1".into(),
204            elapsed_s,
205            accounted_exclusive_s,
206            unattributed_s: elapsed_s - accounted_exclusive_s,
207            phases,
208        })
209    }
210}
211
212/// A scoped timer; disabled spans do not read a clock or acquire a lock.
213/// Dropping on an error path retains the attempted phase and its work.
214///
215/// Created by [`Control::span`](crate::solver::Control::span). A span is not
216/// `Send`: it must finish on the thread that started it.
217pub struct Span {
218    active: Option<(Collector, Phase, ThreadId, u64, Instant)>,
219    pub(crate) work_units: u64,
220    pub(crate) operator_applications: u64,
221    pub(crate) preconditioner_applications: u64,
222    pub(crate) true_residual_checks: u64,
223    pub(crate) multigrid: Option<crate::multigrid::MultigridWork>,
224    _same_thread: PhantomData<Rc<()>>,
225}
226impl Span {
227    pub(crate) fn disabled() -> Self {
228        Self {
229            active: None,
230            work_units: 0,
231            operator_applications: 0,
232            preconditioner_applications: 0,
233            true_residual_checks: 0,
234            multigrid: None,
235            _same_thread: PhantomData,
236        }
237    }
238}
239impl Drop for Span {
240    fn drop(&mut self) {
241        let Some((collector, phase, thread, id, began)) = &self.active else {
242            return;
243        };
244        let elapsed = began.elapsed();
245        let mut data = collector.0.lock().unwrap_or_else(|e| e.into_inner());
246        if data.stacks.get(thread).and_then(|s| s.last()).map(|f| f.id) != Some(*id) {
247            data.invalid_nesting = true;
248            if let Some(stack) = data.stacks.get_mut(thread) {
249                stack.retain(|f| f.id != *id);
250            }
251            return;
252        }
253        let stack = data.stacks.get_mut(thread).expect("phase thread stack");
254        let frame = stack.pop().expect("phase span stack");
255        if let Some(parent) = stack.last_mut() {
256            parent.children += elapsed;
257        }
258        if stack.is_empty() {
259            data.stacks.remove(thread);
260        }
261        let key = serde_json::to_value(phase)
262            .expect("phase name")
263            .as_str()
264            .expect("phase string")
265            .to_string();
266        let timing = data.phases.entry(key).or_default();
267        timing.calls += 1;
268        timing.inclusive_s += elapsed.as_secs_f64();
269        timing.exclusive_s += elapsed.saturating_sub(frame.children).as_secs_f64();
270        timing.work_units += self.work_units;
271        timing.operator_applications += self.operator_applications;
272        timing.preconditioner_applications += self.preconditioner_applications;
273        timing.true_residual_checks += self.true_residual_checks;
274        if let Some(work) = &self.multigrid {
275            timing
276                .multigrid
277                .get_or_insert_with(Default::default)
278                .merge(work);
279        }
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use super::*;
286    #[test]
287    fn out_of_order_spans_are_rejected_instead_of_publishing_bad_accounting() {
288        let c = Collector::default();
289        let outer = c.span(Phase::SolverRun);
290        let inner = c.span(Phase::Step);
291        drop(outer);
292        drop(inner);
293        assert!(c.snapshot(1.0).unwrap_err().contains("profile.nesting"));
294    }
295    #[test]
296    fn nested_time_is_counted_once_and_active_snapshots_are_rejected() {
297        let collector = Collector::default();
298        let start = Instant::now();
299        {
300            let _outer = collector.span(Phase::SolverRun);
301            let mut inner = collector.span(Phase::PressureSolve);
302            inner.work_units = 7;
303            assert!(
304                collector
305                    .snapshot(0.0)
306                    .unwrap_err()
307                    .contains("profile.active")
308            );
309        }
310        let p = collector.snapshot(start.elapsed().as_secs_f64()).unwrap();
311        let outer = &p.phases["solver_run"];
312        let inner = &p.phases["pressure_solve"];
313        assert_eq!(inner.calls, 1);
314        assert_eq!(inner.work_units, 7);
315        assert!((outer.exclusive_s + inner.inclusive_s - outer.inclusive_s).abs() < 1e-12);
316        assert!(p.unattributed_s >= 0.0);
317    }
318    #[test]
319    fn thread_stacks_do_not_mix() {
320        let collector = Collector::default();
321        std::thread::scope(|s| {
322            for _ in 0..2 {
323                let c = collector.clone();
324                s.spawn(move || {
325                    let _outer = c.span(Phase::SolverRun);
326                    let _inner = c.span(Phase::Step);
327                });
328            }
329        });
330        let p = collector.snapshot(0.0).unwrap();
331        assert_eq!(p.phases["solver_run"].calls, 2);
332        assert_eq!(p.phases["step"].calls, 2);
333        assert!((p.accounted_exclusive_s - p.phases["solver_run"].inclusive_s).abs() < 1e-12);
334    }
335}