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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
//! Unified Tracker API - Enhanced Version
//!
//! This module provides a simple, unified interface for memory tracking
//! with all the power of the old API and more.
//!
//! # Features
//!
//! - **Simple API**: `tracker!()` and `track!()` macros
//! - **Auto-capture**: Automatic variable name and type capture
//! - **System Monitoring**: CPU, memory monitoring (background thread, zero overhead)
//! - **Per-thread Tracking**: Independent tracking per thread
//! - **Sampling**: Configurable sampling rates
//! - **Hotspot Analysis**: Automatic allocation hotspot detection
//! - **HTML Dashboard**: Interactive visualization
//! - **JSON/Binary Export**: Multiple export formats
//!
//! # Architecture
//!
//! System monitoring runs in a background thread that collects metrics every 100ms.
//! The `track!` macro only reads atomic values (nanosecond overhead), ensuring
//! no blocking on data collection.
//!
//! # Usage
//!
//! ```rust
//! use memscope_rs::{tracker, track};
//!
//! // Simple usage - system monitoring is automatic
//! let tracker = tracker!();
//! let my_vec = vec![1, 2, 3];
//! track!(tracker, my_vec);
//! // Analyze the tracked allocations
//! let report = tracker.analyze();
//!
//! // Advanced usage with custom sampling
//! use memscope_rs::tracker::SamplingConfig;
//! let tracker = tracker!().with_sampling(SamplingConfig::high_performance());
//! ```
use crate::capture::system_monitor;
use crate::core::tracker::MemoryTracker;
use crate::event_store::{EventStore, MemoryEvent};
use crate::render_engine::dashboard::renderer::rebuild_allocations_from_events;
use crate::render_engine::export::{export_snapshot_with_containers, ExportJsonOptions};
use dashmap::DashMap;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
#[derive(Debug, Clone)]
pub struct SamplingConfig {
pub sample_rate: f64,
pub capture_call_stack: bool,
pub max_stack_depth: usize,
}
impl Default for SamplingConfig {
fn default() -> Self {
Self {
sample_rate: 1.0,
capture_call_stack: false,
max_stack_depth: 10,
}
}
}
impl SamplingConfig {
pub fn demo() -> Self {
Self {
sample_rate: 0.1,
capture_call_stack: false,
max_stack_depth: 5,
}
}
pub fn full() -> Self {
Self {
sample_rate: 1.0,
capture_call_stack: true,
max_stack_depth: 20,
}
}
pub fn high_performance() -> Self {
Self {
sample_rate: 0.01,
capture_call_stack: false,
max_stack_depth: 0,
}
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct SystemSnapshot {
pub timestamp: u64,
pub cpu_usage_percent: f64,
pub memory_usage_bytes: u64,
pub memory_usage_percent: f64,
pub thread_count: usize,
pub disk_read_bps: u64,
pub disk_write_bps: u64,
pub network_rx_bps: u64,
pub network_tx_bps: u64,
pub gpu_usage_percent: f64,
pub gpu_memory_used: u64,
pub gpu_memory_total: u64,
}
#[derive(Debug, Clone)]
pub struct AnalysisReport {
pub total_allocations: usize,
pub total_deallocations: usize,
pub active_allocations: usize,
pub peak_memory_bytes: u64,
pub current_memory_bytes: u64,
pub allocation_rate_per_sec: f64,
pub deallocation_rate_per_sec: f64,
pub hotspots: Vec<AllocationHotspot>,
pub system_snapshots: Vec<SystemSnapshot>,
}
#[derive(Debug, Clone)]
pub struct AllocationHotspot {
pub var_name: String,
pub type_name: String,
pub total_size: usize,
pub allocation_count: usize,
pub location: Option<String>,
}
/// State of the bindings this tracker has reported for one address.
///
/// Keyed by binding serial, *not* by address: an address can hold several generations and
/// a release must remove only the identity it closed. Keeping one entry per address made
/// a degraded release drop the surviving binding's state, so the next observation of that
/// block published a second allocation.
type RecordedState = std::collections::HashMap<u64, RecordedBinding>;
/// Serialised slot holding the state of one address.
type RecordedSlot = Arc<Mutex<RecordedState>>;
/// Address -> recorded slot. The map is shared by all clones of a tracker.
type RecordedBindings = Arc<DashMap<usize, RecordedSlot>>;
/// What this tracker has already reported for an address.
///
/// The core cache can be populated by the allocator hook without any event, and a
/// released address can be reused by a *new* block. Both cases must be told apart from
/// "this tracker already emitted the event", which is what `serial` (binding identity)
/// and `typed` (metadata present) express.
#[derive(Debug, Clone, Copy)]
struct RecordedBinding {
/// Size recorded with the event.
size: usize,
/// Whether the recorded event carried type information.
typed: bool,
/// Whether the current task was already charged for this binding. A cache entry only
/// means "the core tracker knows the block", never "the allocator charged it".
charged: bool,
}
pub struct Tracker {
inner: Arc<MemoryTracker>,
event_store: Arc<EventStore>,
/// Addresses for which *this* tracker already emitted an allocation event, with the
/// size recorded at that moment.
///
/// The core cache can be populated by the allocator hook without any event
/// (`Tracker::global` shares the hook's tracker), so cache presence alone must not
/// be treated as "already reported".
/// One slot per address; the slot also serialises the "first record" decision so
/// concurrent observers of the same block cannot each emit an event.
recorded_bindings: RecordedBindings,
config: Arc<Mutex<TrackerConfig>>,
start_time: Instant,
system_snapshots: Arc<Mutex<Vec<SystemSnapshot>>>,
}
pub(crate) mod allocator_events;
mod release;
impl Clone for Tracker {
fn clone(&self) -> Self {
Tracker {
inner: self.inner.clone(),
event_store: self.event_store.clone(),
recorded_bindings: self.recorded_bindings.clone(),
config: self.config.clone(),
start_time: Instant::now(), // Use current time for cloned tracker
system_snapshots: self.system_snapshots.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct TrackerConfig {
sampling: SamplingConfig,
auto_export_on_drop: bool,
export_path: Option<String>,
}
impl Tracker {
pub fn new() -> Self {
let _suppression = crate::core::allocator::TrackingGuard::acquire();
Self {
inner: Arc::new(MemoryTracker::new()),
event_store: Arc::new(EventStore::new()),
recorded_bindings: Arc::new(DashMap::new()),
config: Arc::new(Mutex::new(TrackerConfig {
sampling: SamplingConfig::default(),
auto_export_on_drop: false,
export_path: None,
})),
start_time: Instant::now(),
system_snapshots: Arc::new(Mutex::new(Vec::new())),
}
}
/// Construct a `Tracker` from a [`global_tracking::TrackerConfig`].
///
/// This is the bridge between the user-facing `GlobalTrackerConfig.tracker`
/// field and the internal `Tracker` construction. Currently the underlying
/// `MemoryTracker` does not honor `max_allocations` (it is unbounded by
/// design), so this method consumes the config without applying that knob.
/// `enable_statistics` is implicitly always true — the tracker always
/// collects statistics; future implementations may gate this.
///
/// The method exists so that `GlobalTracker::with_config` does not silently
/// discard its `config.tracker` field.
///
/// [`global_tracking::TrackerConfig`]: crate::capture::backends::global_tracking::TrackerConfig
pub fn with_config(config: crate::capture::backends::global_tracking::TrackerConfig) -> Self {
tracing::debug!(
target: "memscope::tracker",
max_allocations = config.max_allocations,
enable_statistics = config.enable_statistics,
"constructing Tracker from GlobalTrackerConfig.tracker \
(currently informational; fields are reserved for future enforcement)",
);
Self::new()
}
/// Create a facade `Tracker` that shares `inner`, `event_store`, and
/// `recorded_bindings` with `self` but has its own independent `config`
/// and `start_time`.
///
/// This is used by `GlobalTracker::with_config` to connect the facade
/// to the allocator's shared capture state, so that real alloc/free
/// events from the allocator hook are visible to the facade's consumers.
/// The facade gets its own config so that user-facing settings (sampling,
/// auto-export) do not modify the allocator callback's behavior.
pub(crate) fn shared_clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
event_store: Arc::clone(&self.event_store),
recorded_bindings: Arc::clone(&self.recorded_bindings),
// New, independent config so facade changes don't leak into the
// allocator callback path.
config: Arc::new(Mutex::new(TrackerConfig {
sampling: SamplingConfig::default(),
auto_export_on_drop: false,
export_path: None,
})),
start_time: Instant::now(),
system_snapshots: Arc::clone(&self.system_snapshots),
}
}
pub fn global() -> Self {
allocator_events::global_tracker().clone()
}
pub fn with_system_monitoring(self) -> Self {
self.capture_system_snapshot();
self
}
pub fn with_sampling(self, config: SamplingConfig) -> Self {
if let Ok(mut cfg) = self.config.lock() {
cfg.sampling = config;
}
self
}
pub fn with_auto_export(self, path: &str) -> Self {
if let Ok(mut cfg) = self.config.lock() {
cfg.auto_export_on_drop = true;
cfg.export_path = Some(path.to_string());
}
self
}
pub fn track_as<T: crate::Trackable>(
&self,
var: &T,
name: &str,
file: &str,
line: u32,
module_path: &str,
) {
let _suppression = crate::core::allocator::TrackingGuard::acquire();
if let Ok(cfg) = self.config.lock() {
if cfg.sampling.sample_rate < 1.0 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
// Use current timestamp for randomness to ensure sampling works
// correctly even with identical variable names in a loop
let timestamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
timestamp.hash(&mut hasher);
std::thread::current().id().hash(&mut hasher);
name.hash(&mut hasher);
file.hash(&mut hasher);
line.hash(&mut hasher);
let hash = hasher.finish();
let threshold = (cfg.sampling.sample_rate * 1000.0) as u64;
if (hash % 1000) > threshold {
return;
}
}
}
self.track_inner(var, name, file, line, module_path);
}
#[allow(clippy::too_many_arguments)]
/// Track a clone operation
pub fn track_clone(
&self,
source_ptr: usize,
target_ptr: usize,
size: usize,
var_name: Option<String>,
type_name: Option<String>,
file: &str,
line: u32,
module_path: &str,
) {
let _gate = crate::core::allocator::capture_gate::acquire(0);
let thread_id_u64 = crate::utils::current_thread_id_u64();
let mut event = crate::event_store::MemoryEvent::clone_event(
source_ptr,
target_ptr,
size,
thread_id_u64,
var_name,
type_name,
);
event.source_file = Some(file.to_string());
event.source_line = Some(line);
event.module_path = Some(module_path.to_string());
self.event_store.record(event);
}
fn track_inner<T: crate::Trackable>(
&self,
var: &T,
name: &str,
file: &str,
line: u32,
module_path: &str,
) {
let type_name = var.get_type_name().to_string();
let kind = var.track_kind();
let metadata_size = match kind {
crate::core::types::TrackKind::Container | crate::core::types::TrackKind::Value => {
var.get_size_estimate()
}
_ => 0,
};
// User-defined Trackable methods may reenter, panic, or terminate the
// process. Invoke them before taking the process-wide capture gate so
// an exit-export worker can still read the already committed history.
let _gate = crate::core::allocator::capture_gate::acquire(0);
let thread_id_u64 = crate::utils::current_thread_id_u64();
match kind {
crate::core::types::TrackKind::HeapOwner { ptr, size } => {
// The core cache can already hold this address because the allocator hook
// registered the block *without* emitting an event, or because a previous
// block at this address was released and the address was reused. Only the
// binding identity (serial) plus the presence of type metadata tell those
// cases apart from a real duplicate observation.
// Serialise the whole "read index -> update cache -> emit event -> write
// index" sequence per address. Without this, N threads observing the same
// block at once each saw "not recorded yet" and produced N allocation
// events for one block (plan A06 follow-up).
let slot = self.recorded_slot(ptr);
let mut slot_guard = match slot.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
if let Err(e) = self.inner.track_allocation(ptr, size) {
tracing::error!("Failed to track allocation at ptr {:x}: {}", ptr, e);
return;
}
let serial = self.inner.binding_serial(ptr).unwrap_or(0);
let existing = slot_guard.get(&serial).copied();
let same_binding = existing.is_some_and(|binding| binding.size == size);
if same_binding && existing.is_some_and(|binding| binding.typed) {
// Same binding, same size, type already reported: refresh the cache row
// only, never a second event.
if let Err(e) = self.inner.associate_var(
ptr,
name.to_string(),
type_name,
Some(file),
Some(line),
) {
tracing::error!(
"Failed to associate var '{}' at ptr {:x}: {}",
name,
ptr,
e
);
}
return;
}
if same_binding {
// The allocation is already reported (for example by an allocator
// reallocation event) but without type information: attach the type as an
// annotation so projections can name the block without counting a second
// allocation. Task memory is charged only if nobody did it yet.
let already_charged = existing.is_some_and(|binding| binding.charged);
if !already_charged {
crate::task_registry::global_registry().record_allocation(size);
}
let mut annotation = MemoryEvent::metadata(
name.to_string(),
type_name.clone(),
thread_id_u64,
size,
);
annotation.ptr = ptr;
annotation.binding_serial = Some(serial);
annotation.source_file = Some(file.to_string());
annotation.source_line = Some(line);
annotation.module_path = Some(module_path.to_string());
self.event_store.record(annotation);
slot_guard.insert(
serial,
RecordedBinding {
size,
typed: true,
charged: true,
},
);
if let Err(e) = self.inner.associate_var(
ptr,
name.to_string(),
type_name,
Some(file),
Some(line),
) {
tracing::error!(
"Failed to associate var '{}' at ptr {:x}: {}",
name,
ptr,
e
);
}
return;
}
// Either the first typed observation of a hook-registered block, or a new
// binding (fresh address, or a new serial after the address was reused).
// Emit one allocation event and book task memory exactly once: the
// allocator marks the addresses it charged, so a locally created tracker
// observing the same block does not charge it twice. Asking the core cache
// whether the address exists cannot answer this — this very call has just
// inserted it.
let charge_outcome = allocator_events::allocator_charge(ptr).unwrap_or_else(|| {
crate::task_registry::global_registry().try_record_allocation(size)
});
let mut event = MemoryEvent::allocate(ptr, size, thread_id_u64);
event.binding_serial = Some(serial);
event.charge_outcome = Some(charge_outcome);
event.var_name = Some(name.to_string());
event.type_name = Some(type_name.clone());
event.source_file = Some(file.to_string());
event.source_line = Some(line);
event.module_path = Some(module_path.to_string());
self.event_store.record(event);
slot_guard.insert(
serial,
RecordedBinding {
size,
typed: true,
charged: true,
},
);
if let Err(e) = self.inner.associate_var(
ptr,
name.to_string(),
type_name,
Some(file),
Some(line),
) {
tracing::error!("Failed to associate var '{}' at ptr {:x}: {}", name, ptr, e);
}
}
crate::core::types::TrackKind::StackOwner {
ptr: stack_ptr,
heap_ptr,
size,
} => {
// A smart pointer owns a heap block that the allocator already reported,
// and this observation knows the *pointee* size, not the block size:
// `Arc::new([u8; 64])` allocates 80 bytes, not 64. Publishing an
// allocation here counted the same memory twice (80 + 64). Record the
// metadata against the pointee instead and keep the stack pointer so
// clone detection can still relate the two views.
// The pointee sits *inside* its allocation (an `Arc` stores the value
// after its reference counts), so neither the address nor the pointee
// size identifies the block. Look up the containing binding and annotate
// that identity; without one the annotation stays a diagnostic.
let containing = self.inner.binding_containing(heap_ptr);
let mut annotation = MemoryEvent::metadata(
name.to_string(),
type_name.clone(),
thread_id_u64,
containing.map_or(size, |binding| binding.size),
);
annotation.ptr = containing.map_or(heap_ptr, |binding| binding.ptr);
annotation.binding_serial = containing.map(|binding| binding.serial);
annotation.stack_ptr = Some(stack_ptr);
annotation.source_file = Some(file.to_string());
annotation.source_line = Some(line);
annotation.module_path = Some(module_path.to_string());
self.event_store.record(annotation);
if let Err(e) = self.inner.associate_var(
heap_ptr,
name.to_string(),
type_name,
Some(file),
Some(line),
) {
tracing::error!(
"Failed to associate var '{}' at ptr {:x}: {}",
name,
heap_ptr,
e
);
}
}
crate::core::types::TrackKind::Container | crate::core::types::TrackKind::Value => {
// Container and Value record metadata events without heap allocation
// They will be tracked as graph nodes but not scanned by HeapScanner
let mut event = MemoryEvent::metadata(
name.to_string(),
type_name,
thread_id_u64,
metadata_size,
);
event.source_file = Some(file.to_string());
event.source_line = Some(line);
event.module_path = Some(module_path.to_string());
self.event_store.record(event);
}
}
}
/// Number of duplicate observations of an already tracked address.
///
/// These sightings are not counted as allocations or bytes; the value exists so
/// reports can show that the capture layer saw the same block twice.
pub fn duplicate_observations(&self) -> u64 {
self.inner.duplicate_observations()
}
/// Releases that could only be matched by address.
///
/// Non-zero means a release arrived for an address that still held several live
/// bindings, so the closed binding was the oldest one rather than a named identity.
pub fn degraded_releases(&self) -> u64 {
self.inner.degraded_releases()
}
pub fn events(&self) -> Vec<MemoryEvent> {
self.event_store.snapshot()
}
pub fn event_store(&self) -> &Arc<EventStore> {
&self.event_store
}
fn capture_system_snapshot(&self) {
let snapshot = SystemSnapshot {
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64,
cpu_usage_percent: system_monitor::cpu_usage(),
memory_usage_bytes: system_monitor::memory_used(),
memory_usage_percent: system_monitor::memory_usage_percent(),
thread_count: system_monitor::thread_count(),
disk_read_bps: system_monitor::disk_read_bps(),
disk_write_bps: system_monitor::disk_write_bps(),
network_rx_bps: system_monitor::network_rx_bps(),
network_tx_bps: system_monitor::network_tx_bps(),
gpu_usage_percent: system_monitor::gpu_memory_usage_percent(),
gpu_memory_used: system_monitor::gpu_memory_used(),
gpu_memory_total: system_monitor::gpu_memory_total(),
};
if let Ok(mut snapshots) = self.system_snapshots.lock() {
snapshots.push(snapshot);
}
}
pub fn stats(&self) -> crate::core::types::MemoryStats {
let stats = self.inner.get_stats().unwrap_or_default();
crate::core::types::MemoryStats {
total_allocations: stats.total_allocations as usize,
total_allocated: stats.total_allocated as usize,
active_allocations: stats.active_allocations,
active_memory: stats.active_memory as usize,
peak_allocations: stats.peak_allocations,
peak_memory: stats.peak_memory as usize,
total_deallocations: stats.total_deallocations as usize,
total_deallocated: stats.total_deallocated as usize,
leaked_allocations: stats.leaked_allocations,
leaked_memory: stats.leaked_memory as usize,
..Default::default()
}
}
pub fn analyze(&self) -> AnalysisReport {
let _suppression = crate::core::allocator::TrackingGuard::acquire();
let stats = self.stats();
let events = self.event_store().snapshot();
let allocations = rebuild_allocations_from_events(&events);
let elapsed = self.start_time.elapsed().as_secs_f64();
let current_memory: usize = allocations.iter().map(|a| a.size).sum();
let peak_memory = stats.peak_memory.max(current_memory);
let mut hotspot_map: HashMap<String, (String, usize, usize)> = HashMap::new();
for alloc in &allocations {
if let Some(ref var_name) = alloc.var_name {
let key = var_name.clone();
let entry = hotspot_map.entry(key).or_insert((
alloc.type_name.clone().unwrap_or_default(),
0,
0,
));
entry.1 += alloc.size;
entry.2 += 1;
}
}
let hotspots: Vec<AllocationHotspot> = hotspot_map
.into_iter()
.map(
|(var_name, (type_name, total_size, count))| AllocationHotspot {
var_name,
type_name,
total_size,
allocation_count: count,
location: None,
},
)
.collect();
let system_snapshots = self
.system_snapshots
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
AnalysisReport {
total_allocations: stats.total_allocations,
total_deallocations: stats.total_deallocations,
active_allocations: allocations.len(),
peak_memory_bytes: peak_memory as u64,
current_memory_bytes: current_memory as u64,
allocation_rate_per_sec: if elapsed > 0.0 {
stats.total_allocations as f64 / elapsed
} else {
0.0
},
deallocation_rate_per_sec: if elapsed > 0.0 {
stats.total_deallocations as f64 / elapsed
} else {
0.0
},
hotspots,
system_snapshots,
}
}
pub fn inner(&self) -> &Arc<MemoryTracker> {
&self.inner
}
pub fn elapsed(&self) -> Duration {
self.start_time.elapsed()
}
pub fn system_snapshots(&self) -> Vec<SystemSnapshot> {
self.system_snapshots
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
pub fn current_system_snapshot(&self) -> SystemSnapshot {
SystemSnapshot {
timestamp: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_millis() as u64,
cpu_usage_percent: system_monitor::cpu_usage(),
memory_usage_bytes: system_monitor::memory_used(),
memory_usage_percent: system_monitor::memory_usage_percent(),
thread_count: system_monitor::thread_count(),
disk_read_bps: system_monitor::disk_read_bps(),
disk_write_bps: system_monitor::disk_write_bps(),
network_rx_bps: system_monitor::network_rx_bps(),
network_tx_bps: system_monitor::network_tx_bps(),
gpu_usage_percent: system_monitor::gpu_memory_usage_percent(),
gpu_memory_used: system_monitor::gpu_memory_used(),
gpu_memory_total: system_monitor::gpu_memory_total(),
}
}
}
impl Default for Tracker {
fn default() -> Self {
Self::new()
}
}
impl Drop for Tracker {
fn drop(&mut self) {
// Dropping a tracker (or a clone of one that shares the event store) is a
// *profiler* event, not an object release. Emitting `Deallocate` for every
// still-live allocation here fabricated free events: they silently
// converted live objects into "freed" ones and destroyed the accuracy of
// every downstream statistic (see plan A01).
//
// The only thing a drop is still allowed to do is the legacy compatibility
// snapshot enabled by `with_auto_export`. That path is read-only with
// respect to the event store.
self.export_legacy_on_drop();
}
}
impl Tracker {
/// Write the legacy auto-export snapshot if `with_auto_export` was enabled.
///
/// This is a compatibility entry point, not a session end: it only projects the
/// events recorded so far (`memory_analysis.json`, `lifetime.json`,
/// `thread_analysis.json`) and never appends release events, so a live object
/// stays a live object in the exported files.
fn export_legacy_on_drop(&self) {
let _suppression = crate::core::allocator::TrackingGuard::acquire();
let Some(path) = self.auto_export_path() else {
return;
};
// Use the event store as the single data source (covers both HeapOwner and
// Container observations).
let events = self.event_store().snapshot();
// The live list cannot reconstruct cumulative totals or the high-water mark, so
// the legacy drop export projects the same ledger cut as `export_all_json`
// instead of re-aggregating what is still alive (plan A06 follow-up).
let mut ledger = crate::snapshot::BindingLedger::new();
for event in &events {
ledger.apply(event);
}
let cut_ns = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|elapsed| elapsed.as_nanos().min(u128::from(u64::MAX)) as u64)
.unwrap_or(0);
let snapshot = crate::snapshot::builder::project_snapshot(&ledger, cut_ns);
let containers: Vec<crate::capture::types::AllocationInfo> =
rebuild_allocations_from_events(&events)
.into_iter()
.filter(|allocation| allocation.ptr >= crate::analysis::VIRTUAL_PTR_BASE)
.collect();
let options = ExportJsonOptions::default();
if let Err(e) = export_snapshot_with_containers(
&snapshot,
&containers,
std::path::Path::new(&path),
&options,
) {
tracing::error!("Failed to auto-export on drop: {}", e);
}
}
/// Read the configured legacy auto-export path, if enabled.
fn auto_export_path(&self) -> Option<String> {
let cfg = self.config.lock().ok()?;
if !cfg.auto_export_on_drop {
return None;
}
cfg.export_path.clone()
}
}
impl serde::Serialize for AnalysisReport {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("AnalysisReport", 9)?;
state.serialize_field("total_allocations", &self.total_allocations)?;
state.serialize_field("total_deallocations", &self.total_deallocations)?;
state.serialize_field("active_allocations", &self.active_allocations)?;
state.serialize_field("peak_memory_bytes", &self.peak_memory_bytes)?;
state.serialize_field("current_memory_bytes", &self.current_memory_bytes)?;
state.serialize_field("allocation_rate_per_sec", &self.allocation_rate_per_sec)?;
state.serialize_field("deallocation_rate_per_sec", &self.deallocation_rate_per_sec)?;
state.serialize_field("hotspots", &self.hotspots)?;
state.serialize_field("system_snapshots", &self.system_snapshots)?;
state.end()
}
}
impl serde::Serialize for AllocationHotspot {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeStruct;
let mut state = serializer.serialize_struct("AllocationHotspot", 5)?;
state.serialize_field("var_name", &self.var_name)?;
state.serialize_field("type_name", &self.type_name)?;
state.serialize_field("total_size", &self.total_size)?;
state.serialize_field("allocation_count", &self.allocation_count)?;
state.serialize_field("location", &self.location)?;
state.end()
}
}
#[macro_export]
macro_rules! tracker {
() => {
$crate::tracker::Tracker::new()
};
}
#[macro_export]
macro_rules! track {
($tracker:expr, $var:expr) => {{
let var_name = stringify!($var);
$tracker.track_as(&$var, var_name, file!(), line!(), module_path!());
}};
}
#[macro_export]
macro_rules! track_clone {
($tracker:expr, $source:expr, $target:expr) => {{
let source_name = stringify!($source);
let target_name = stringify!($target);
let source_ptr = &$source as *const _ as usize;
let target_ptr = &$target as *const _ as usize;
let type_name = $crate::utils::type_of(&$target);
$tracker.track_clone(
source_ptr,
target_ptr,
std::mem::size_of_val(&$target),
Some(target_name.to_string()),
Some(type_name.to_string()),
file!(),
line!(),
module_path!(),
);
}};
}
#[cfg(test)]
mod tests;