hotpath 0.33.2

One profiler for CPU, time, memory, SQL, and async code - quickly find and debug performance bottlenecks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! Instrumented Future wrapper that tracks lifecycle events.

use crate::output_on::format_debug_truncated;

use crate::functions::AsyncAllocBridge;
use crate::lib_on::futures::{
    ensure_futures_state, get_or_create_future_id, send_future_event, FutureEvent, PollResult,
    FUTURE_CALL_ID_COUNTER,
};
use pin_project_lite::pin_project;
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::task::{Context, Poll};

use crate::instant::Instant;

#[cfg(feature = "hotpath-alloc")]
#[inline]
fn measure_poll_alloc<R>(poll_fn: impl FnOnce() -> R) -> (R, Option<u64>, Option<u64>) {
    crate::functions::alloc::guard::push_alloc_stack();

    let result = poll_fn();

    let (bytes, count) = crate::functions::alloc::guard::pop_alloc_stack();

    (result, Some(bytes), Some(count))
}

#[cfg(not(feature = "hotpath-alloc"))]
#[inline]
fn measure_poll_alloc<R>(poll_fn: impl FnOnce() -> R) -> (R, Option<u64>, Option<u64>) {
    (poll_fn(), None, None)
}

pin_project! {
    /// A wrapper around a future that tracks lifecycle events.
    ///
    /// Created via the `future!` macro, this wrapper tracks:
    /// - Creation
    /// - Each poll call with result (Pending/Ready) and duration
    /// - Memory allocations per poll (when `hotpath-alloc` feature is enabled)
    /// - Drop (cancellation if not completed)
    ///
    /// This variant does NOT require `Debug` on the output type.
    /// Use `InstrumentedFutureLog` (via `future!(expr, log = true)`) to log the output value.
    pub struct InstrumentedFuture<F: Future> {
        #[pin]
        inner: F,
        future_id: u32,
        call_id: u32,
        completed: bool,
        visible: bool,
        timed: bool,
        alloc_bridge: Option<Arc<AsyncAllocBridge>>,
        // Function name registered on the thread-local caller stack for
        // exactly the duration of each inner poll (SQL/HTTP source
        // attribution). Set for measured async function bodies, None for
        // `future!` expression wrappers.
        caller_scope: Option<&'static str>,
    }

    impl<F: Future> PinnedDrop for InstrumentedFuture<F> {
        fn drop(this: Pin<&mut Self>) {
            if this.visible && !this.completed {
                send_future_event(FutureEvent::Cancelled {
                    future_id: this.future_id,
                    call_id: this.call_id,
                });
            }
        }
    }
}

#[cfg_attr(feature = "hotpath-meta", hotpath_meta::measure_all)]
impl<F: Future> InstrumentedFuture<F> {
    pub(crate) fn new(
        inner: F,
        location: &'static str,
        label: Option<String>,
        alloc_bridge: Option<Arc<AsyncAllocBridge>>,
        visible: bool,
        caller_scope: Option<&'static str>,
    ) -> Self {
        let _suspend = crate::lib_on::SuspendAllocTracking::new();

        // Per-call sampling decision: either every poll of this call is timed or
        // none are, so per-call poll stats are exact rather than extrapolated.
        let (future_id, call_id, timed) = if visible {
            ensure_futures_state();
            let (future_id, is_new) = get_or_create_future_id(location);
            let call_id = FUTURE_CALL_ID_COUNTER.fetch_add(1, Ordering::Relaxed);

            if is_new {
                send_future_event(FutureEvent::Created {
                    future_id,
                    source: location,
                    display_label: label,
                });
            }

            send_future_event(FutureEvent::CallCreated { future_id, call_id });
            (
                future_id,
                call_id,
                crate::lib_on::sampling::futures_should_time(),
            )
        } else {
            (0, 0, false)
        };

        drop(_suspend);

        Self {
            inner,
            future_id,
            call_id,
            completed: false,
            visible,
            timed,
            alloc_bridge,
            caller_scope,
        }
    }
}

struct CallerScopeGuard(bool);

impl CallerScopeGuard {
    #[inline]
    fn enter(caller_scope: Option<&'static str>) -> Self {
        if let Some(scope) = caller_scope {
            crate::lib_on::caller_stack::push_caller(scope);
        }
        Self(caller_scope.is_some())
    }
}

impl Drop for CallerScopeGuard {
    #[inline]
    fn drop(&mut self) {
        if self.0 {
            crate::lib_on::caller_stack::pop_caller();
        }
    }
}

// Bounded on the wrapped future, so wrapping keeps `Debug` wherever it had it.
impl<F: Future + std::fmt::Debug> std::fmt::Debug for InstrumentedFuture<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InstrumentedFuture")
            .field("inner", &self.inner)
            .field("id", &self.future_id)
            .finish_non_exhaustive()
    }
}

impl<F: Future> Future for InstrumentedFuture<F> {
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let visible = *this.visible;

        // Don't instrument future unless visible, only collect alloc data
        if !visible {
            let (result, poll_alloc_bytes, poll_alloc_count) = measure_poll_alloc(|| {
                let _caller_scope = CallerScopeGuard::enter(*this.caller_scope);
                this.inner.poll(cx)
            });
            if let (Some(bytes), Some(count), Some(bridge)) = (
                poll_alloc_bytes,
                poll_alloc_count,
                this.alloc_bridge.as_ref(),
            ) {
                bridge.add(bytes, count);
            }
            if result.is_ready() {
                *this.completed = true;
            }
            return result;
        }

        let future_id = *this.future_id;
        let call_id = *this.call_id;

        let start = (*this.timed).then(Instant::now);
        let (result, poll_alloc_bytes, poll_alloc_count) = measure_poll_alloc(|| {
            let _caller_scope = CallerScopeGuard::enter(*this.caller_scope);
            this.inner.poll(cx)
        });
        let poll_duration_ns =
            start.map(|start| Instant::now().duration_since(start).as_nanos() as u64);
        if let (Some(bytes), Some(count), Some(bridge)) = (
            poll_alloc_bytes,
            poll_alloc_count,
            this.alloc_bridge.as_ref(),
        ) {
            bridge.add(bytes, count);
        }

        let poll_result = match &result {
            Poll::Pending => PollResult::Pending,
            Poll::Ready(_) => {
                *this.completed = true;
                PollResult::Ready
            }
        };

        {
            let _suspend = crate::lib_on::SuspendAllocTracking::new();
            send_future_event(FutureEvent::Polled {
                future_id,
                call_id,
                result: poll_result,
                poll_duration_ns,
                poll_alloc_bytes,
                poll_alloc_count,
            });

            if *this.completed {
                send_future_event(FutureEvent::Completed {
                    future_id,
                    call_id,
                    log_message: None,
                });
            }
        }

        result
    }
}

pin_project! {
    /// A wrapper around a future that tracks lifecycle events including the output value.
    ///
    /// Created via the `future!(expr, log = true)` macro, this wrapper tracks:
    /// - Creation
    /// - Each poll call with result (Pending/Ready with Debug output) and duration
    /// - Memory allocations per poll (when `hotpath-alloc` feature is enabled)
    /// - Drop (cancellation if not completed)
    ///
    /// This variant requires `Debug` on the output type to log the value.
    pub struct InstrumentedFutureLog<F: Future> {
        #[pin]
        inner: F,
        future_id: u32,
        call_id: u32,
        completed: bool,
        visible: bool,
        timed: bool,
        alloc_bridge: Option<Arc<AsyncAllocBridge>>,
        // See `InstrumentedFuture::caller_scope`.
        caller_scope: Option<&'static str>,
    }

    impl<F: Future> PinnedDrop for InstrumentedFutureLog<F> {
        fn drop(this: Pin<&mut Self>) {
            if this.visible && !this.completed {
                send_future_event(FutureEvent::Cancelled {
                    future_id: this.future_id,
                    call_id: this.call_id,
                });
            }
        }
    }
}

#[cfg_attr(feature = "hotpath-meta", hotpath_meta::measure_all)]
impl<F: Future> InstrumentedFutureLog<F> {
    pub(crate) fn new(
        inner: F,
        location: &'static str,
        label: Option<String>,
        alloc_bridge: Option<Arc<AsyncAllocBridge>>,
        visible: bool,
        caller_scope: Option<&'static str>,
    ) -> Self {
        let _suspend = crate::lib_on::SuspendAllocTracking::new();

        // Per-call sampling decision: either every poll of this call is timed or
        // none are, so per-call poll stats are exact rather than extrapolated.
        let (future_id, call_id, timed) = if visible {
            ensure_futures_state();
            let (future_id, is_new) = get_or_create_future_id(location);
            let call_id = FUTURE_CALL_ID_COUNTER.fetch_add(1, Ordering::Relaxed);

            if is_new {
                send_future_event(FutureEvent::Created {
                    future_id,
                    source: location,
                    display_label: label,
                });
            }

            send_future_event(FutureEvent::CallCreated { future_id, call_id });
            (
                future_id,
                call_id,
                crate::lib_on::sampling::futures_should_time(),
            )
        } else {
            (0, 0, false)
        };

        drop(_suspend);

        Self {
            inner,
            future_id,
            call_id,
            completed: false,
            visible,
            timed,
            alloc_bridge,
            caller_scope,
        }
    }
}

impl<F: Future + std::fmt::Debug> std::fmt::Debug for InstrumentedFutureLog<F> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InstrumentedFutureLog")
            .field("inner", &self.inner)
            .field("id", &self.future_id)
            .finish_non_exhaustive()
    }
}

impl<F: Future> Future for InstrumentedFutureLog<F>
where
    F::Output: std::fmt::Debug,
{
    type Output = F::Output;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.project();
        let visible = *this.visible;

        if !visible {
            let (result, poll_alloc_bytes, poll_alloc_count) = measure_poll_alloc(|| {
                let _caller_scope = CallerScopeGuard::enter(*this.caller_scope);
                this.inner.poll(cx)
            });
            if let (Some(bytes), Some(count), Some(bridge)) = (
                poll_alloc_bytes,
                poll_alloc_count,
                this.alloc_bridge.as_ref(),
            ) {
                bridge.add(bytes, count);
            }
            if result.is_ready() {
                *this.completed = true;
            }
            return result;
        }

        let future_id = *this.future_id;
        let call_id = *this.call_id;

        let start = (*this.timed).then(Instant::now);
        let (result, poll_alloc_bytes, poll_alloc_count) = measure_poll_alloc(|| {
            let _caller_scope = CallerScopeGuard::enter(*this.caller_scope);
            this.inner.poll(cx)
        });
        let poll_duration_ns =
            start.map(|start| Instant::now().duration_since(start).as_nanos() as u64);
        if let (Some(bytes), Some(count), Some(bridge)) = (
            poll_alloc_bytes,
            poll_alloc_count,
            this.alloc_bridge.as_ref(),
        ) {
            bridge.add(bytes, count);
        }

        let (poll_result, log_message) = match &result {
            Poll::Pending => (PollResult::Pending, None),
            Poll::Ready(value) => {
                *this.completed = true;
                (PollResult::Ready, Some(format_debug_truncated(value)))
            }
        };

        {
            let _suspend = crate::lib_on::SuspendAllocTracking::new();
            send_future_event(FutureEvent::Polled {
                future_id,
                call_id,
                result: poll_result,
                poll_duration_ns,
                poll_alloc_bytes,
                poll_alloc_count,
            });

            if *this.completed {
                send_future_event(FutureEvent::Completed {
                    future_id,
                    call_id,
                    log_message,
                });
            }
        }

        result
    }
}