vize_carton 0.240.0

Carton - The artist's toolbox for Vize compiler
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
//! Profiler core: timers, nested span guards, and the sharded metric store.

use std::cell::RefCell;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::{Duration, Instant};

use rustc_hash::FxHashMap;

use super::allocation::{
    ALLOCATION_TRACKING_ENABLED, pause_allocation_tracking, reset_allocation_counters,
};
use super::metrics::{CounterMetrics, Metrics};
use super::report::{CounterEntry, CounterSummary, ProfileEntry, ProfileSummary};

const PROFILER_SHARDS: usize = 32;

thread_local! {
    static PROFILE_STACK: RefCell<std::vec::Vec<ProfileFrame>> = const { RefCell::new(std::vec::Vec::new()) };
}

#[derive(Debug)]
struct ProfileFrame {
    name: &'static str,
    start: Instant,
    child_duration: Duration,
}

/// RAII guard for nested global profiling spans.
#[derive(Debug)]
pub struct ProfileGuard {
    profiler: &'static Profiler,
    active: bool,
}

impl ProfileGuard {
    #[inline]
    fn start(profiler: &'static Profiler, name: &'static str) -> Self {
        let _allocation_tracking = pause_allocation_tracking();
        PROFILE_STACK.with(|stack| {
            stack.borrow_mut().push(ProfileFrame {
                name,
                start: Instant::now(),
                child_duration: Duration::ZERO,
            });
        });
        Self {
            profiler,
            active: true,
        }
    }
}

impl Drop for ProfileGuard {
    fn drop(&mut self) {
        if !self.active {
            return;
        }

        PROFILE_STACK.with(|stack| {
            let mut stack = stack.borrow_mut();
            let Some(frame) = stack.pop() else {
                return;
            };

            let duration = frame.start.elapsed();
            if let Some(parent) = stack.last_mut() {
                parent.child_duration += duration;
            }
            self.profiler
                .record_sample_enabled(frame.name, duration, frame.child_duration);
        });
    }
}

/// A lightweight timer for measuring durations.
#[derive(Debug)]
pub struct Timer {
    start: Instant,
    name: &'static str,
}

impl Timer {
    /// Start a new timer.
    #[inline]
    pub fn start(name: &'static str) -> Self {
        Self {
            start: Instant::now(),
            name,
        }
    }

    /// Get the elapsed time without stopping.
    #[inline]
    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    /// Stop the timer and return the elapsed time.
    #[inline]
    pub fn stop(self) -> Duration {
        self.elapsed()
    }

    /// Stop and record to a profiler.
    #[inline]
    pub fn record(self, profiler: &Profiler) {
        profiler.record(self.name, self.elapsed());
    }
}

/// Performance profiler for collecting metrics.
///
/// Disabled profiling sits directly on several CLI/LSP hot paths, so the fast
/// path is just one relaxed atomic load in the `profile!` macro. When enabled,
/// samples are sharded by operation name to keep parallel file processing from
/// contending on one global lock, and profiler-internal allocation accounting is
/// paused so the measurement machinery does not count itself.
#[derive(Debug)]
pub struct Profiler {
    /// Metrics by operation name, split into shards to keep parallel profile runs from
    /// funnelling every span through the same lock.
    pub(super) metrics: [RwLock<FxHashMap<&'static str, Metrics>>; PROFILER_SHARDS],
    /// Non-duration counters by name.
    counters: [RwLock<FxHashMap<&'static str, CounterMetrics>>; PROFILER_SHARDS],
    /// Whether profiling is enabled
    enabled: AtomicBool,
}

impl Profiler {
    /// Create a new profiler.
    pub fn new() -> Self {
        Self {
            metrics: std::array::from_fn(|_| RwLock::new(FxHashMap::default())),
            counters: std::array::from_fn(|_| RwLock::new(FxHashMap::default())),
            enabled: AtomicBool::new(false),
        }
    }

    /// Create an enabled profiler.
    pub fn enabled() -> Self {
        let p = Self::new();
        p.enable();
        p
    }

    /// Enable profiling.
    pub fn enable(&self) {
        reset_allocation_counters();
        ALLOCATION_TRACKING_ENABLED.store(true, Ordering::Relaxed);
        self.enabled.store(true, Ordering::Relaxed);
    }

    /// Disable profiling.
    pub fn disable(&self) {
        self.enabled.store(false, Ordering::Relaxed);
        ALLOCATION_TRACKING_ENABLED.store(false, Ordering::Relaxed);
    }

    /// Check if profiling is enabled.
    #[inline]
    pub fn is_enabled(&self) -> bool {
        self.enabled.load(Ordering::Relaxed)
    }

    /// Start a timer for the given operation.
    #[inline]
    pub fn timer(&self, name: &'static str) -> Option<Timer> {
        if self.is_enabled() {
            Some(Timer::start(name))
        } else {
            None
        }
    }

    /// Record a duration for the given operation.
    pub fn record(&self, name: &'static str, duration: Duration) {
        if !self.is_enabled() {
            return;
        }

        self.record_enabled(name, duration);
    }

    /// Record a duration after the caller has already checked that profiling is enabled.
    #[doc(hidden)]
    pub fn record_enabled(&self, name: &'static str, duration: Duration) {
        self.record_sample_enabled(name, duration, Duration::ZERO);
    }

    /// Start a nested profiling span on the global profiler.
    #[inline]
    pub fn global_span(&'static self, name: &'static str) -> Option<ProfileGuard> {
        if self.is_enabled() {
            Some(ProfileGuard::start(self, name))
        } else {
            None
        }
    }

    /// Record a duration and child duration after the caller has already checked profiling.
    ///
    /// `ProfileGuard::drop` uses this path after the macro has checked
    /// `is_enabled()`, avoiding another atomic load for every nested span.
    #[doc(hidden)]
    pub fn record_sample_enabled(
        &self,
        name: &'static str,
        duration: Duration,
        child_duration: Duration,
    ) {
        let _allocation_tracking = pause_allocation_tracking();
        let mut metrics = self.metrics_write(Self::shard_index(name));
        metrics
            .entry(name)
            .or_default()
            .record_with_child(duration, child_duration);
    }

    /// Record a non-duration counter sample.
    pub fn record_counter(&self, name: &'static str, value: u64) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled(name, value);
    }

    /// Record a counter after the caller has already checked profiling.
    #[doc(hidden)]
    pub fn record_counter_enabled(&self, name: &'static str, value: u64) {
        let _allocation_tracking = pause_allocation_tracking();
        let mut counters = self.counters_write(Self::shard_index(name));
        counters.entry(name).or_default().record(value);
    }

    /// Record a successful `std::fs::read_to_string` call.
    pub fn record_fs_read_to_string(&self, bytes: usize) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("io.read.calls", 1);
        self.record_counter_enabled("io.read.bytes", bytes as u64);
        self.record_counter_enabled("syscall.fs.read_to_string.calls", 1);
    }

    /// Record a failed `std::fs::read_to_string` call.
    pub fn record_fs_read_to_string_failure(&self) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("io.read.calls", 1);
        self.record_counter_enabled("io.read.failures", 1);
        self.record_counter_enabled("syscall.fs.read_to_string.calls", 1);
        self.record_counter_enabled("syscall.fs.read_to_string.failures", 1);
    }

    /// Record a successful `std::fs::write` call.
    pub fn record_fs_write(&self, bytes: usize) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("io.write.calls", 1);
        self.record_counter_enabled("io.write.attempted_bytes", bytes as u64);
        self.record_counter_enabled("io.write.bytes", bytes as u64);
        self.record_counter_enabled("syscall.fs.write.calls", 1);
    }

    /// Record a failed `std::fs::write` call.
    pub fn record_fs_write_failure(&self, bytes: usize) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("io.write.calls", 1);
        self.record_counter_enabled("io.write.attempted_bytes", bytes as u64);
        self.record_counter_enabled("io.write.failures", 1);
        self.record_counter_enabled("syscall.fs.write.calls", 1);
        self.record_counter_enabled("syscall.fs.write.failures", 1);
    }

    /// Record a successful `std::fs::create_dir_all` call.
    pub fn record_fs_create_dir_all(&self) {
        if self.is_enabled() {
            self.record_counter_enabled("syscall.fs.create_dir_all.calls", 1);
        }
    }

    /// Record a failed `std::fs::create_dir_all` call.
    pub fn record_fs_create_dir_all_failure(&self) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("syscall.fs.create_dir_all.calls", 1);
        self.record_counter_enabled("syscall.fs.create_dir_all.failures", 1);
    }

    /// Record a successful `std::fs::remove_dir_all` call.
    pub fn record_fs_remove_dir_all(&self) {
        if self.is_enabled() {
            self.record_counter_enabled("syscall.fs.remove_dir_all.calls", 1);
        }
    }

    /// Record a failed `std::fs::remove_dir_all` call.
    pub fn record_fs_remove_dir_all_failure(&self) {
        if !self.is_enabled() {
            return;
        }

        self.record_counter_enabled("syscall.fs.remove_dir_all.calls", 1);
        self.record_counter_enabled("syscall.fs.remove_dir_all.failures", 1);
    }

    /// Get metrics for the given operation.
    pub fn get(&self, name: &str) -> Option<Metrics> {
        self.metrics_read(Self::shard_index(name))
            .get(name)
            .cloned()
    }

    /// Get all metrics.
    pub fn all(&self) -> FxHashMap<&'static str, Metrics> {
        let _allocation_tracking = pause_allocation_tracking();
        let mut all = FxHashMap::default();
        for shard in &self.metrics {
            let metrics = shard
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            all.extend(
                metrics
                    .iter()
                    .map(|(name, metrics)| (*name, metrics.clone())),
            );
        }
        all
    }

    /// Clear all metrics.
    pub fn clear(&self) {
        let _allocation_tracking = pause_allocation_tracking();
        for shard in &self.metrics {
            shard
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clear();
        }
        for shard in &self.counters {
            shard
                .write()
                .unwrap_or_else(|poisoned| poisoned.into_inner())
                .clear();
        }
    }

    /// Generate a summary report.
    pub fn summary(&self) -> ProfileSummary {
        let _allocation_tracking = pause_allocation_tracking();
        let mut entries = Vec::new();
        for shard in &self.metrics {
            let metrics = shard
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            entries.reserve(metrics.len());
            entries.extend(metrics.iter().map(|(name, m)| ProfileEntry {
                name,
                count: m.count,
                total: m.total_duration,
                self_total: m.self_duration,
                child_total: m.child_duration,
                average: m.average(),
                self_average: m.self_average(),
                min: m.min_duration,
                max: m.max_duration,
                self_min: m.min_self_duration,
                self_max: m.max_self_duration,
                p50: m.percentile(0.50),
                p95: m.percentile(0.95),
                p99: m.percentile(0.99),
                samples_over_1ms: m.samples_over_1ms(),
                samples_over_10ms: m.samples_over_10ms(),
                samples_over_100ms: m.samples_over_100ms(),
            }));
        }

        // Sort by total time descending
        entries.sort_by_key(|entry| std::cmp::Reverse(entry.total));

        ProfileSummary { entries }
    }

    /// Generate a counter summary report.
    pub fn counter_summary(&self) -> CounterSummary {
        let _allocation_tracking = pause_allocation_tracking();
        let mut entries = Vec::new();
        for shard in &self.counters {
            let counters = shard
                .read()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            entries.reserve(counters.len());
            entries.extend(counters.iter().map(|(name, counter)| CounterEntry {
                name,
                samples: counter.samples,
                total: counter.total,
                average: counter.average(),
                min: if counter.samples == 0 { 0 } else { counter.min },
                max: counter.max,
            }));
        }

        entries.sort_by(|left, right| left.name.cmp(right.name));

        CounterSummary { entries }
    }

    #[inline]
    fn metrics_read(&self, shard: usize) -> RwLockReadGuard<'_, FxHashMap<&'static str, Metrics>> {
        self.metrics[shard]
            .read()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[inline]
    fn metrics_write(
        &self,
        shard: usize,
    ) -> RwLockWriteGuard<'_, FxHashMap<&'static str, Metrics>> {
        self.metrics[shard]
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[inline]
    fn counters_write(
        &self,
        shard: usize,
    ) -> RwLockWriteGuard<'_, FxHashMap<&'static str, CounterMetrics>> {
        self.counters[shard]
            .write()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    #[inline]
    pub(super) fn shard_index(name: &str) -> usize {
        debug_assert!(PROFILER_SHARDS.is_power_of_two());

        // FNV-1a over static operation names is cheaper than building a
        // hasher per sample, and the power-of-two mask keeps sharding branchless.
        let mut hash = 0xcbf2_9ce4_8422_2325u64;
        for byte in name.as_bytes() {
            hash ^= u64::from(*byte);
            hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
        }
        (hash as usize) & (PROFILER_SHARDS - 1)
    }
}

impl Default for Profiler {
    fn default() -> Self {
        Self::new()
    }
}

/// Global profiler instance.
static GLOBAL_PROFILER: once_cell::sync::Lazy<Profiler> = once_cell::sync::Lazy::new(Profiler::new);

/// Get the global profiler.
#[inline]
pub fn global_profiler() -> &'static Profiler {
    &GLOBAL_PROFILER
}