stackler 0.1.0

A lightweight, always-on stack telemetry library that requires no instrumentation.
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
#![cfg(feature = "std")]

//! NOTE: these tests share the process-wide registry and reset it, so they MUST
//! run single-threaded (`-- --test-threads 1`); parallel runs are flaky.

use std::hint::black_box;

use stackler::Stack;

/// Uses a known amount of stack in a frame of its own.
///
/// `#[inline(never)]` is not decoration: a watermark can only describe frames
/// created after the painting, and an inlined callee has no frame of its own.
#[inline(never)]
#[allow(dead_code)] // only some feature combinations exercise it
fn burn_stack(bytes: usize) {
    let mut frame = [0u8; 64 * 1024];
    black_box(&mut frame[..bytes]);
}

#[test]
fn discovers_its_own_stack() {
    let stack = Stack::current().expect("stack bounds are discoverable on this platform");

    assert!(stack.size() > 0);
    assert!(stack.contains(stackler::sp()));
    assert_eq!(stack.base() - stack.limit(), stack.size());

    // A single stack pointer partitions the stack exactly; two separate reads
    // would land in two different frames.
    let sp = stackler::sp();
    assert_eq!(
        stack.depth_at(sp).unwrap() + stack.headroom_at(sp).unwrap(),
        stack.size()
    );
    assert!(stack.depth().unwrap() > 0);
    assert!(stack.headroom().unwrap() > 0);
}

#[test]
fn bounds_are_validated() {
    assert!(Stack::from_bounds(0x2000, 0x1000).is_none()); // inverted
    assert!(Stack::from_bounds(0x1000, 0x1000).is_none()); // empty
    assert!(Stack::from_limit_and_size(0x1000, 0).is_none()); // empty
    assert!(Stack::from_limit_and_size(usize::MAX, 2).is_none()); // wraps

    let stack = Stack::from_limit_and_size(0x1000, 0x1000).unwrap();
    assert_eq!(stack.base(), 0x2000);
    assert_eq!(stack.size(), 0x1000);
    assert!(stack.contains(0x1000));
    assert!(!stack.contains(0x2000)); // one past the end
    assert_eq!(stack.depth_at(0x1800), Some(0x800));
    assert_eq!(stack.depth_at(0x800), None); // not ours
}

#[test]
fn depth_grows_with_recursion() {
    #[inline(never)]
    fn recurse(remaining: usize, depths: &mut Vec<usize>) {
        let mut frame = [0u8; 1024];
        black_box(&mut frame);

        depths.push(stackler::depth().expect("this thread is tracked"));
        if remaining > 0 {
            recurse(remaining - 1, depths);
        }
    }

    let mut depths = Vec::new();
    recurse(8, &mut depths);

    for step in depths.windows(2) {
        assert!(step[1] > step[0], "{depths:?}");
    }
    assert!(
        depths.last().unwrap() - depths.first().unwrap() >= 8 * 1024,
        "{depths:?}"
    );
}

#[test]
fn headroom_shrinks_as_depth_grows() {
    let (depth, headroom) = (stackler::depth().unwrap(), stackler::headroom().unwrap());

    #[inline(never)]
    fn deeper() -> (usize, usize) {
        let mut frame = [0u8; 4096];
        black_box(&mut frame);
        (stackler::depth().unwrap(), stackler::headroom().unwrap())
    }

    let (deep_depth, deep_headroom) = deeper();
    assert!(deep_depth > depth);
    assert!(deep_headroom < headroom);
    // Both readings partition the same stack.
    assert_eq!(depth + headroom, deep_depth + deep_headroom);
}

#[test]
fn guard_answers_and_counts() {
    stackler::reset();

    assert!(stackler::has_headroom(1024));
    assert_eq!(stackler::stats().guard_trip_count, 0);

    // No stack has this much left.
    assert!(!stackler::has_headroom(usize::MAX));
    assert_eq!(stackler::stats().guard_trip_count, 1);

    assert!(!stackler::has_headroom(usize::MAX));
    assert_eq!(stackler::stats().guard_trip_count, 2);
}

#[test]
fn sampling_feeds_the_aggregates() {
    stackler::reset();

    let sampled = stackler::sample().expect("this thread is tracked");
    let stats = stackler::stats();

    assert_eq!(stats.sample_count, 1);
    assert_eq!(stats.sample_sum, sampled as u64);
    assert_eq!(stats.sample_avg, Some(sampled));
    assert!(stats.peak_max >= sampled);
    assert!(stats.threads_live >= 1);
    assert!(stats.reserved_sum >= stats.peak_sum);
    assert_eq!(stats.untracked, 0);

    // A deeper sample raises the peak.
    #[inline(never)]
    fn sample_deeper() -> usize {
        let mut frame = [0u8; 8192];
        black_box(&mut frame);
        stackler::sample().unwrap()
    }

    let deeper = sample_deeper();
    assert!(deeper > sampled);

    let stats = stackler::stats();
    assert_eq!(stats.sample_count, 2);
    assert!(stats.peak_max >= deeper);
}

#[test]
fn stats_subtraction() {
    stackler::reset();

    let before = stackler::stats();
    stackler::sample();
    let after = stackler::stats();

    let diff = &after - &before;
    assert_eq!(diff.sample_count, 1);

    // Gauges are carried over rather than subtracted.
    assert_eq!(diff.threads_live, after.threads_live);
    assert_eq!(diff.reserved_sum, after.reserved_sum);

    // Subtracting a newer snapshot from an older one saturates instead of
    // wrapping.
    let weird = &before - &after;
    assert_eq!(weird.sample_count, 0);
}

#[test]
fn measure_diffs_counters() {
    stackler::reset();
    stackler::sample();

    let (result, stats) = stackler::measure(|| {
        stackler::sample();
        stackler::sample();
        42
    });

    assert_eq!(result, 42);
    assert_eq!(stats.sample_count, 2);
}

#[test]
fn threads_come_and_go() {
    stackler::reset();
    stackler::attach();

    let before = stackler::stats();

    std::thread::spawn(|| {
        stackler::sample().expect("a spawned thread is tracked too");
        let mine = stackler::current_stack().unwrap();
        assert!(mine.contains(stackler::sp()));
    })
    .join()
    .unwrap();

    let after = stackler::stats();
    assert_eq!(after.threads_seen, before.threads_seen + 1);
    // The slot is handed back when the thread exits, but what it recorded is not
    // lost.
    assert_eq!(after.threads_live, before.threads_live);
    assert!(after.sample_count > before.sample_count);
}

#[test]
fn thread_snapshots_describe_this_thread() {
    stackler::attach();
    stackler::sample();

    let me = stackler::sp();
    let mine = stackler::threads()
        .into_iter()
        .find(|thread| thread.stack().is_some_and(|stack| stack.contains(me)))
        .expect("this thread appears in the registry");

    assert_eq!(mine.size, mine.base - mine.limit);
    assert!(mine.depth_last > 0);
    assert!(mine.peak >= mine.depth_last);
    assert!(mine.sample_count >= 1);
    assert!(mine.utilization().unwrap() > 0.0);
}

#[test]
#[cfg(feature = "watermark")]
fn measure_peak_sees_a_deep_frame() {
    let (_, peak) = stackler::measure_peak(|| burn_stack(32 * 1024));
    let peak = peak.expect("this thread's stack can be painted");

    assert!(!peak.is_saturated(), "{peak:?}");
    assert!(peak.bytes() >= 32 * 1024, "{peak:?}");
    // The reading is of the operation, not of the whole stack.
    assert!(peak.bytes() < 96 * 1024, "{peak:?}");
}

#[test]
#[cfg(feature = "watermark")]
fn measure_peak_of_a_shallow_operation_is_quiet() {
    let (result, peak) = stackler::measure_peak(|| 42);
    assert_eq!(result, 42);

    let peak = peak.unwrap();
    assert!(peak.bytes() < 4096, "{peak:?}");
}

#[test]
#[cfg(feature = "watermark")]
fn measure_peak_saturates_instead_of_lying() {
    // A painted region of one page cannot describe anything deeper than a page.
    stackler::Stackler::new().paint_depth(4096).install();

    let (_, peak) = stackler::measure_peak(|| burn_stack(32 * 1024));
    let peak = peak.expect("this thread's stack can be painted");
    assert!(peak.is_saturated(), "{peak:?}");

    stackler::Stackler::new().install();
}

#[test]
#[cfg(feature = "watermark")]
fn watermark_outlives_the_operation() {
    // Nothing is measured while the work happens: the answer is read out of the
    // stack afterwards.
    stackler::repaint().expect("this thread's stack can be painted");
    burn_stack(24 * 1024);

    let peak = stackler::peak().expect("a painted thread has a watermark");
    assert!(peak.bytes() >= 24 * 1024, "{peak:?}");

    // And it is monotonic: a shallower excursion cannot lower it.
    burn_stack(1024);
    let again = stackler::peak().unwrap();
    assert!(again.bytes() >= peak.bytes());
}

#[test]
#[cfg(feature = "watermark")]
fn polling_reads_the_watermark_of_another_thread() {
    use std::sync::mpsc;

    stackler::reset();

    let (deep_tx, deep_rx) = mpsc::channel();
    let (done_tx, done_rx) = mpsc::channel();

    let worker = std::thread::spawn(move || {
        stackler::attach();
        burn_stack(48 * 1024);
        // Announce the excursion, then stay alive: the point is that this thread
        // does not report anything itself.
        deep_tx.send(()).unwrap();
        done_rx.recv().unwrap();
    });

    deep_rx.recv().unwrap();

    stackler::poll_all();
    let deepest = stackler::threads()
        .into_iter()
        .map(|thread| thread.peak)
        .max()
        .unwrap_or(0);
    assert!(deepest >= 48 * 1024, "{deepest}");

    done_tx.send(()).unwrap();
    worker.join().unwrap();

    // The exiting thread's peak survives it.
    assert!(stackler::stats().peak_max >= 48 * 1024);
}

#[test]
#[cfg(feature = "watermark")]
fn painting_is_bounded_by_the_stack() {
    let stack = Stack::current().unwrap();

    // SAFETY: this is the calling thread's own stack, and nothing below the
    // stack pointer of ordinary Rust code is live.
    let paint = unsafe { stack.paint(usize::MAX) }.expect("a whole stack can be painted");

    assert!(paint.bytes() <= stack.size());
    assert!(paint.lo() >= stack.limit());
    assert!(paint.hi() < stack.base());
    assert!(paint.hi() < stackler::sp());
    assert_eq!(paint.bytes() % size_of::<usize>(), 0);

    assert_eq!(
        stackler::Paint::from_bounds(paint.lo(), paint.hi()),
        Some(paint)
    );
    assert!(stackler::Paint::from_bounds(paint.hi(), paint.lo()).is_none()); // inverted
    assert!(stackler::Paint::from_bounds(paint.lo() + 1, paint.hi()).is_none()); // misaligned
}

#[test]
#[cfg(feature = "histograms")]
fn histogram_quantile() {
    use stackler::Histogram;

    // an empty histogram returns None
    let empty = Histogram::default();
    assert!(empty.is_empty());
    assert_eq!(empty.total(), 0);
    assert_eq!(empty.quantile(0.5), None);

    // out-of-range q returns None
    let mut buckets = [0u64; 64];
    buckets[5] = 10; // bucket 5 = [32, 64)
    let histogram = Histogram::from_buckets(buckets);
    assert_eq!(histogram.quantile(-0.1), None);
    assert_eq!(histogram.quantile(1.1), None);

    // all values in one bucket: the quantile is somewhere in [32, 64)
    let q50 = histogram.quantile(0.5).unwrap();
    assert!((32..64).contains(&q50));

    // monotonicity
    let q10 = histogram.quantile(0.1).unwrap();
    let q90 = histogram.quantile(0.9).unwrap();
    assert!(q10 <= q50 && q50 <= q90);
}

#[test]
#[cfg(feature = "histograms")]
fn depth_histogram_tracks_samples() {
    stackler::reset();

    let depth = stackler::sample().unwrap();
    let histogram = stackler::stats().depth_histogram;

    assert_eq!(histogram.total(), 1);
    let quantile = histogram.quantile(1.0).unwrap();
    // The observation lands in the power-of-two bucket containing it.
    assert!(quantile <= depth && depth < quantile.next_power_of_two().max(2) * 2);
}

#[test]
#[cfg(feature = "histograms")]
fn histogram_outlives_the_threads_it_describes() {
    // Depth distributions are kept per thread, so a thread's observations have to
    // survive being folded into the process totals when it exits.
    stackler::reset();
    let before = stackler::stats();
    assert_eq!(before.depth_histogram.total(), before.sample_count);

    std::thread::spawn(|| {
        for _ in 0..10 {
            stackler::sample().expect("tracked");
        }
    })
    .join()
    .unwrap();

    let after = stackler::stats();
    assert_eq!(after.sample_count, before.sample_count + 10);
    assert_eq!(
        after.depth_histogram.total(),
        after.sample_count,
        "every observation is in exactly one bucket, whether its thread is alive or not"
    );

    // And a live thread's observations land in the same aggregate.
    stackler::sample();
    let after = stackler::stats();
    assert_eq!(after.depth_histogram.total(), after.sample_count);
}

#[test]
#[cfg(all(feature = "histograms", feature = "serde"))]
fn serde_roundtrip() {
    use stackler::Histogram;

    let mut buckets = [0u64; 64];
    buckets[3] = 7;
    buckets[63] = 1; // exercise the top bucket
    let histogram = Histogram::from_buckets(buckets);

    let json = serde_json::to_string(&histogram).unwrap();
    let restored: Histogram = serde_json::from_str(&json).unwrap();
    assert_eq!(histogram.buckets(), restored.buckets());

    stackler::sample();
    let stats = stackler::stats();
    let json = serde_json::to_string(&stats).unwrap();
    let restored: stackler::Stats = serde_json::from_str(&json).unwrap();
    assert_eq!(stats.sample_count, restored.sample_count);
    assert_eq!(stats.peak_max, restored.peak_max);
}

#[test]
#[cfg(feature = "fmt")]
fn display_impls() {
    stackler::attach();
    stackler::sample();
    burn_stack(16 * 1024);
    stackler::sample();

    println!("{}", stackler::stats());
    stackler::for_each_thread(|thread| println!("{thread}"));

    #[cfg(feature = "watermark")]
    {
        let peak = stackler::peak().unwrap();
        println!("peak: {peak}");
        assert!(!format!("{}", stackler::Peak::AtLeast(1024)).is_empty());
    }
}

#[test]
#[cfg(feature = "sampler")]
fn background_sampler_keeps_peaks_fresh() {
    use std::time::Duration;

    stackler::reset();
    stackler::attach();

    let sampler = stackler::sampler::spawn(Duration::from_millis(5)).unwrap();

    burn_stack(40 * 1024);

    // Wait for the sampler to notice, without asserting on timing.
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while stackler::stats().peak_max < 40 * 1024 {
        assert!(
            std::time::Instant::now() < deadline,
            "the sampler never ran"
        );
        std::thread::sleep(Duration::from_millis(5));
    }

    sampler.stop();
}

#[test]
#[cfg(feature = "hook_pthread")]
fn interposed_pthread_create_registers_a_thread() {
    stackler::reset();
    stackler::attach();

    let before = stackler::stats().threads_seen;

    // The spawned thread never calls into stackler, and is registered anyway.
    let seen_from_inside = std::thread::spawn(|| stackler::stats().threads_seen)
        .join()
        .unwrap();

    assert_eq!(seen_from_inside, before + 1);
}