captrack 0.1.0

Capacity telemetry for Rust collections — call-site macros that record peak capacity, with zero overhead when disabled.
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
// Tests for `CapInspect` — consumption-point transparent inspection (Phase L).
//
// These tests verify:
//   1. `cap_inspect_at` records a capacity sample (NOT a creation).
//   2. Peak-after-grow: calling cap_inspect after many pushes captures peak cap.
//   3. Smoke test: all 14 types compile with cap_inspect_at (telemetry-on).
//   4. Off-feature path: cap_inspect_at is a no-op (no panics, no registry hits).
//
// # Key constraint
//
// `file!()`, `line!()`, `column!()` expand to the source location of the macro
// call, so `record_creation` and `cap_inspect_at` called on different source
// lines produce different (file, line, col) keys.  To use the same key for
// both calls, we must capture the triple into variables first and reuse them.

#[cfg(feature = "telemetry")]
mod telemetry_on {
    use crate::cap_inspect::CapInspect;
    use crate::registry;
    use std::sync::atomic::Ordering;

    /// Helper: read all samples for entries matching `name`, return max.
    fn max_sample_for(name: &str) -> Option<usize> {
        let mut max_val: Option<usize> = None;
        registry::registry().scan(|_, stats| {
            if stats.name == name {
                // Reservoir::snapshot() is non-destructive — no push-back needed.
                let samples = stats.samples.snapshot();
                if let Some(&m) = samples.iter().max() {
                    max_val = Some(max_val.map_or(m, |prev| prev.max(m)));
                }
            }
        });
        max_val
    }

    /// Helper: count creation_count for entries matching `name`.
    fn creation_count_for(name: &str) -> u64 {
        let mut total = 0u64;
        registry::registry().scan(|_, stats| {
            if stats.name == name {
                total += stats.creation_count.load(Ordering::Relaxed);
            }
        });
        total
    }

    /// Helper: count total_observed for entries matching `name`.
    fn total_observed_for(name: &str) -> u64 {
        let mut total = 0u64;
        registry::registry().scan(|_, stats| {
            if stats.name == name {
                total += stats.samples.total_observed();
            }
        });
        total
    }

    /// `cap_inspect_at` on a `Vec` records a capacity sample at the consumption
    /// point.  `creation_count` is NOT incremented by `cap_inspect_at` — the
    /// construction site must call `record_creation` / `record_initial` first.
    #[test]
    fn cap_inspect_records_at_consumption_point() {
        let name = "test:cap_inspect_records_at_consumption_point";
        // Capture the construction-site coordinates.  Both record_creation and
        // cap_inspect_at must use the same (file, line, col) key.
        let loc: (&'static str, u32, u32) = (file!(), line!(), column!());
        // Pre-register the construction site so the sample is not an orphan.
        // In real usage this is done by wrap_from / with_capacity_named.
        registry::record_creation(name, loc.0, loc.1, loc.2);
        let creation_after_ctor = creation_count_for(name);
        let observed_before = total_observed_for(name);

        let mut v: Vec<u32> = Vec::with_capacity(8);
        v.push(1);
        v.push(2);

        // Simulate a consumption point (e.g. return from a function).
        // cap_inspect_at should add a sample but NOT increment creation_count.
        CapInspect::cap_inspect_at(&v, name, loc.0, loc.1, loc.2);

        // creation_count unchanged by cap_inspect_at.
        assert_eq!(
            creation_count_for(name),
            creation_after_ctor,
            "cap_inspect_at must not increment creation_count"
        );
        // One more observation recorded.
        assert_eq!(
            total_observed_for(name),
            observed_before + 1,
            "cap_inspect_at must record exactly one sample"
        );
        let recorded = max_sample_for(name);
        assert_eq!(
            recorded,
            Some(v.capacity()),
            "recorded sample should equal Vec capacity at the inspection point"
        );
    }

    /// Cap is captured AFTER grow — calling cap_inspect after many pushes
    /// records the peak (post-grow) capacity, not the original allocation.
    #[test]
    fn cap_inspect_records_peak_after_grow() {
        let name = "test:cap_inspect_records_peak_after_grow";
        // Capture location first, then register.
        let loc: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name, loc.0, loc.1, loc.2);

        // Start with a small cap, then push enough to trigger reallocations.
        let mut v: Vec<u32> = Vec::with_capacity(1);
        for i in 0..64u32 {
            v.push(i);
        }
        // At this point v.capacity() >= 64 (likely 64 or 128 depending on growth factor).
        let cap_at_inspect = v.capacity();
        assert!(
            cap_at_inspect >= 64,
            "Vec should have grown: cap={cap_at_inspect}"
        );

        CapInspect::cap_inspect_at(&v, name, loc.0, loc.1, loc.2);

        let recorded = max_sample_for(name);
        assert_eq!(
            recorded,
            Some(cap_at_inspect),
            "should record post-grow capacity {cap_at_inspect}, got {recorded:?}"
        );
    }

    /// Smoke test: all 14 supported types call cap_inspect_at without panicking.
    ///
    /// Each type's call-site is pre-registered via `record_creation` so the
    /// sample is not an orphan.  `cap_inspect_at` must record samples but must
    /// NOT change creation_count.
    #[test]
    fn cap_inspect_works_for_each_type() {
        let name_prefix = "test:cap_inspect_works_for_each_type";

        // For each type we: capture loc, register the site, construct the type,
        // call cap_inspect_at with the same loc.  Because file!/line!/column!
        // expand to the macro invocation site we must interleave capture and use
        // carefully so the loc triple is the same for both calls.

        // Vec<u8>
        let name_vec = &*Box::leak(format!("{name_prefix}:vec").into_boxed_str());
        let loc_vec: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_vec, loc_vec.0, loc_vec.1, loc_vec.2);
        let v: Vec<u8> = Vec::with_capacity(4);
        CapInspect::cap_inspect_at(&v, name_vec, loc_vec.0, loc_vec.1, loc_vec.2);

        // VecDeque<u8>
        let name_vd = &*Box::leak(format!("{name_prefix}:vecdeque").into_boxed_str());
        let loc_vd: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_vd, loc_vd.0, loc_vd.1, loc_vd.2);
        let vd: std::collections::VecDeque<u8> = std::collections::VecDeque::with_capacity(4);
        CapInspect::cap_inspect_at(&vd, name_vd, loc_vd.0, loc_vd.1, loc_vd.2);

        // HashMap
        let name_hm = &*Box::leak(format!("{name_prefix}:hashmap").into_boxed_str());
        let loc_hm: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_hm, loc_hm.0, loc_hm.1, loc_hm.2);
        let hm: std::collections::HashMap<u32, u32> = std::collections::HashMap::with_capacity(4);
        CapInspect::cap_inspect_at(&hm, name_hm, loc_hm.0, loc_hm.1, loc_hm.2);

        // HashSet
        let name_hs = &*Box::leak(format!("{name_prefix}:hashset").into_boxed_str());
        let loc_hs: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_hs, loc_hs.0, loc_hs.1, loc_hs.2);
        let hs: std::collections::HashSet<u32> = std::collections::HashSet::with_capacity(4);
        CapInspect::cap_inspect_at(&hs, name_hs, loc_hs.0, loc_hs.1, loc_hs.2);

        // BTreeMap (uses len())
        let name_btm = &*Box::leak(format!("{name_prefix}:btreemap").into_boxed_str());
        let loc_btm: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_btm, loc_btm.0, loc_btm.1, loc_btm.2);
        let btm: std::collections::BTreeMap<u32, u32> = std::collections::BTreeMap::new();
        CapInspect::cap_inspect_at(&btm, name_btm, loc_btm.0, loc_btm.1, loc_btm.2);

        // BTreeSet (uses len())
        let name_bts = &*Box::leak(format!("{name_prefix}:btreeset").into_boxed_str());
        let loc_bts: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_bts, loc_bts.0, loc_bts.1, loc_bts.2);
        let bts: std::collections::BTreeSet<u32> = std::collections::BTreeSet::new();
        CapInspect::cap_inspect_at(&bts, name_bts, loc_bts.0, loc_bts.1, loc_bts.2);

        // BytesMut
        let name_bm = &*Box::leak(format!("{name_prefix}:bytesmut").into_boxed_str());
        let loc_bm: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_bm, loc_bm.0, loc_bm.1, loc_bm.2);
        let bm = ::bytes::BytesMut::with_capacity(4);
        CapInspect::cap_inspect_at(&bm, name_bm, loc_bm.0, loc_bm.1, loc_bm.2);

        // IndexMap
        let name_im = &*Box::leak(format!("{name_prefix}:indexmap").into_boxed_str());
        let loc_im: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_im, loc_im.0, loc_im.1, loc_im.2);
        let im: ::indexmap::IndexMap<u32, u32> = ::indexmap::IndexMap::with_capacity(4);
        CapInspect::cap_inspect_at(&im, name_im, loc_im.0, loc_im.1, loc_im.2);

        // IndexSet
        let name_is = &*Box::leak(format!("{name_prefix}:indexset").into_boxed_str());
        let loc_is: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_is, loc_is.0, loc_is.1, loc_is.2);
        let is_: ::indexmap::IndexSet<u32> = ::indexmap::IndexSet::with_capacity(4);
        CapInspect::cap_inspect_at(&is_, name_is, loc_is.0, loc_is.1, loc_is.2);

        // DashMap
        let name_dm = &*Box::leak(format!("{name_prefix}:dashmap").into_boxed_str());
        let loc_dm: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_dm, loc_dm.0, loc_dm.1, loc_dm.2);
        let dm: ::dashmap::DashMap<u32, u32> = ::dashmap::DashMap::with_capacity(4);
        CapInspect::cap_inspect_at(&dm, name_dm, loc_dm.0, loc_dm.1, loc_dm.2);

        // scc::HashMap
        let name_scchm = &*Box::leak(format!("{name_prefix}:scc_hashmap").into_boxed_str());
        let loc_scchm: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_scchm, loc_scchm.0, loc_scchm.1, loc_scchm.2);
        let scchm: ::scc::HashMap<u32, u32> = ::scc::HashMap::with_capacity(4);
        CapInspect::cap_inspect_at(&scchm, name_scchm, loc_scchm.0, loc_scchm.1, loc_scchm.2);

        // scc::HashSet
        let name_scchs = &*Box::leak(format!("{name_prefix}:scc_hashset").into_boxed_str());
        let loc_scchs: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_scchs, loc_scchs.0, loc_scchs.1, loc_scchs.2);
        let scchs: ::scc::HashSet<u32> = ::scc::HashSet::with_capacity(4);
        CapInspect::cap_inspect_at(&scchs, name_scchs, loc_scchs.0, loc_scchs.1, loc_scchs.2);

        // scc::TreeIndex (uses len())
        let name_tree = &*Box::leak(format!("{name_prefix}:scc_tree").into_boxed_str());
        let loc_tree: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_tree, loc_tree.0, loc_tree.1, loc_tree.2);
        let tree: ::scc::TreeIndex<u32, u32> = ::scc::TreeIndex::new();
        CapInspect::cap_inspect_at(&tree, name_tree, loc_tree.0, loc_tree.1, loc_tree.2);

        // SmallVec
        let name_sv = &*Box::leak(format!("{name_prefix}:smallvec").into_boxed_str());
        let loc_sv: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name_sv, loc_sv.0, loc_sv.1, loc_sv.2);
        let sv: ::smallvec::SmallVec<[u8; 8]> = ::smallvec::SmallVec::with_capacity(8);
        CapInspect::cap_inspect_at(&sv, name_sv, loc_sv.0, loc_sv.1, loc_sv.2);

        // All 14 types fired — verify registry entries exist (created by record_creation).
        let mut found = false;
        registry::registry().scan(|_, stats| {
            if stats.name.starts_with(name_prefix) {
                found = true;
            }
        });
        assert!(
            found,
            "registry entries must exist (created via record_creation before cap_inspect_at)"
        );
    }

    /// Regression test for the `build_cap_inspect_suggestion` registry-key
    /// mismatch bug (see `captrack-pgo-lint/src/instrument.rs`).
    ///
    /// The lint injects `cap_inspect_at` at a *usage* site far from the
    /// `let v = X::new();` constructor.  Before the fix, the generated code
    /// used `file!()`/`line!()`/`column!()` expanded IN PLACE at the usage
    /// site — a different registry key than the constructor's, which was the
    /// key `record_creation` registered under. `record_sample` silently
    /// no-ops for an unregistered key, so every `cap_inspect_at` sample was
    /// dropped even though `creation_count` was correctly non-zero.
    ///
    /// This test proves both halves of that story directly against the
    /// registry, without going through the lint:
    ///   1. Sampling under the SAME key as the registered construction site
    ///      is observed (`total_observed` increments, sample appears).
    ///   2. Sampling under a DIFFERENT key (simulating a usage-site location
    ///      distinct from the constructor) is silently dropped — proving
    ///      *why* the bug produced empty `samples: []` in practice.
    #[test]
    fn cap_inspect_at_usage_site_key_must_match_constructor_key() {
        let name = "test:cap_inspect_at_usage_site_key_must_match_constructor_key";

        // Simulate the constructor's site (e.g. `let mut out = Vec::new();`).
        let ctor_loc: (&'static str, u32, u32) = ("fixture.rs", 10, 5);
        registry::record_creation(name, ctor_loc.0, ctor_loc.1, ctor_loc.2);
        let observed_after_ctor = total_observed_for(name);

        let v: Vec<u32> = Vec::with_capacity(8);

        // Case 1 (the FIX): cap_inspect_at uses the constructor's own
        // coordinates, baked in as literals by `build_cap_inspect_suggestion`.
        // This is exactly what the corrected lint output does.
        CapInspect::cap_inspect_at(&v, name, ctor_loc.0, ctor_loc.1, ctor_loc.2);
        assert_eq!(
            total_observed_for(name),
            observed_after_ctor + 1,
            "sampling under the constructor's own key must be observed"
        );

        // Case 2 (the BUG): cap_inspect_at uses a DIFFERENT location — this
        // is what the old buggy code produced, because `file!()`/`line!()`/
        // `column!()` expand at the *usage* call site, not the constructor's.
        // `record_sample` treats an unregistered (file, line, col) key as an
        // orphan: `debug_assert!` in debug builds (so this misuse is loud in
        // dev/test), silent no-op in release builds (so it never panics in
        // production — it just silently drops the sample, which is exactly
        // the `samples: []` symptom seen with the real shamir-db pipeline).
        // We assert the debug behaviour here via `should_panic`-style capture
        // so both code paths are exercised without duplicating the test.
        let usage_site_loc: (&'static str, u32, u32) = ("fixture.rs", 42, 9);
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            CapInspect::cap_inspect_at(
                &v,
                name,
                usage_site_loc.0,
                usage_site_loc.1,
                usage_site_loc.2,
            );
        }));

        if cfg!(debug_assertions) {
            assert!(
                result.is_err(),
                "record_sample must debug_assert on an unregistered (mismatched) key \
                 in debug builds — this is the exact bug class that produced empty \
                 `samples: []` in production"
            );
        } else {
            assert!(
                result.is_ok(),
                "record_sample must not panic in release builds"
            );
        }

        // Either way, the registry entry keyed by ctor_loc must NOT have
        // grown from the mismatched-key call: in debug builds the call
        // panicked before recording; in release builds it silently no-op'd.
        assert_eq!(
            total_observed_for(name),
            observed_after_ctor + 1,
            "sampling under a mismatched (usage-site) key must not be observed \
             under the constructor's registry entry — this is the exact bug \
             class that produced empty `samples: []` in production"
        );
    }

    /// Regression test for bug 3 — `build_record_creation_suggestion` using
    /// `file!()`/`line!()`/`column!()` *inside the generated block* instead
    /// of the constructor's own literal coordinates.
    ///
    /// This is a distinct bug from `cap_inspect_at_usage_site_key_must_match_constructor_key`
    /// above (which covers a mismatched USAGE-site key). Here both the
    /// simulated `record_creation` call AND the simulated `cap_inspect_at`
    /// call use the exact SAME literal `(file, line, col)` triple — exactly
    /// what the fixed `build_record_creation_suggestion` /
    /// `build_cap_inspect_suggestion` pair now emits for one call site — and
    /// asserts they land in the SAME `CapStats` entry: `creation_count > 0`
    /// AND the sample is observed (not silently dropped).
    #[test]
    fn record_creation_and_cap_inspect_at_with_shared_coordinates_hit_same_entry() {
        let name = "test:record_creation_and_cap_inspect_at_with_shared_coordinates_hit_same_entry";
        // Single shared coordinate triple — mirrors the constructor's own
        // span, used identically by both the record_creation suggestion and
        // the cap_inspect_at suggestion after the fix.
        let site: (&'static str, u32, u32) = ("value.rs", 180, 24);

        // Step 1: simulate the (fixed) record_creation suggestion — literal
        // coordinates, not file!()/line!()/column!() expanded in-block.
        registry::record_creation(name, site.0, site.1, site.2);
        assert_eq!(
            creation_count_for(name),
            1,
            "record_creation must register exactly one creation under the site key"
        );

        let v: Vec<u32> = Vec::with_capacity(32);
        let observed_after_ctor = total_observed_for(name);

        // Step 2: simulate the (already-fixed) cap_inspect_at suggestion —
        // same literal coordinates, taken from the same `site` value.
        crate::CapInspect::cap_inspect_at(&v, name, site.0, site.1, site.2);

        assert_eq!(
            creation_count_for(name),
            1,
            "cap_inspect_at must not affect creation_count"
        );
        assert_eq!(
            total_observed_for(name),
            observed_after_ctor + 1,
            "cap_inspect_at sample under the SAME key as record_creation must be \
             observed, not silently dropped — this is the exact bug class where \
             record_creation and cap_inspect_at disagreed on column, producing \
             creation_count > 0 but samples: [] in the merged profile"
        );
        assert!(
            max_sample_for(name).is_some(),
            "at least one sample must be present for the shared site key"
        );
    }

    /// The block-expression form used by the lint injection compiles and works:
    /// `{ ::captrack::CapInspect::cap_inspect_at(&v, name, file!(), line!(), column!()); v }`
    /// The value `v` is returned by the block, type is preserved.
    ///
    /// `cap_inspect_at` adds a sample but does NOT increment creation_count.
    #[test]
    fn block_expression_form_preserves_type_and_value() {
        let name = "test:block_expression_form_preserves_type_and_value";
        // Capture the construction-site key, then register it.
        let loc: (&'static str, u32, u32) = (file!(), line!(), column!());
        registry::record_creation(name, loc.0, loc.1, loc.2);
        let creation_before = creation_count_for(name);

        let mut v: Vec<u32> = Vec::with_capacity(16);
        v.push(42);

        // This is the exact form the lint injects at consumption points.
        // Inside the crate we use `crate::CapInspect`; at call-sites in
        // user code the generated injection uses `::captrack::CapInspect`.
        let result: Vec<u32> = {
            crate::CapInspect::cap_inspect_at(&v, name, loc.0, loc.1, loc.2);
            v
        };

        assert_eq!(result.len(), 1);
        assert_eq!(result[0], 42);
        assert!(result.capacity() >= 16);
        // creation_count must not have been incremented by cap_inspect_at.
        assert_eq!(
            creation_count_for(name),
            creation_before,
            "cap_inspect_at must not change creation_count; construction was registered via record_creation"
        );
    }
}

// Off-feature: CapInspect trait is available but all impls are no-ops.
// This test compiles in both modes; it verifies that calling cap_inspect_at
// in off-feature mode does NOT panic and does not produce observable side effects.
//
// In on-feature mode, cap_inspect_at calls record_sample which requires a
// prior record_creation for the same (file, line, col) key.  This test uses
// names that are NOT pre-registered, so in on-feature + debug mode the
// debug_assert in record_sample would fire.  To keep the test compilable in
// both modes without panicking, it is gated to off-feature only.
#[cfg(not(feature = "telemetry"))]
#[test]
fn cap_inspect_off_feature_is_noop_or_records_nothing_visible() {
    use crate::cap_inspect::CapInspect;

    // In off-feature mode: no-op — the call must complete without panic.
    let v: Vec<u32> = Vec::with_capacity(8);
    CapInspect::cap_inspect_at(&v, "test:noop_check", file!(), line!(), column!());

    // VecDeque
    let vd: std::collections::VecDeque<u32> = std::collections::VecDeque::with_capacity(4);
    CapInspect::cap_inspect_at(&vd, "test:noop_check_vd", file!(), line!(), column!());

    // No assertion — the point of the test is "does not panic".
}