memscope-rs 0.2.6

A memory tracking library for Rust applications.
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
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
//! Dashboard renderer using Handlebars templates.
//!
//! This module provides the main dashboard renderer that generates
//! HTML reports from memory tracking data.

mod context;
mod event_dto;
mod event_reconstructor;
mod evidence;
mod helpers;
mod inference;
mod layout_inference;
#[allow(dead_code)]
mod render_methods;
mod report_builder;
mod system_info;
mod telemetry;
mod template_registry;
mod types;

pub use types::*;

// Evidence/confidence vocabulary is reachable through the renderer root so DTO
// consumers do not need to know which submodule defines it.
pub use evidence::{DropExpectation, EvidenceLevel, PointerProvenance, RiskConfidence};

// Re-export for external use
pub use event_dto::{build_data_index, DashboardEventDTO, DataIndex, EventSummary};
pub use event_reconstructor::rebuild_allocations_from_events;
pub use template_registry::{
    DashboardTemplate as RegisteredTemplate, TemplateKind, TemplateRegistry,
};

use crate::analysis::memory_passport_tracker::MemoryPassportTracker;
use crate::tracker::Tracker;
use handlebars::Handlebars;
use std::path::PathBuf;
use std::sync::Arc;

/// CDN asset scripts embedded at compile time for offline use
const TAILWIND_SCRIPT: &str = include_str!("../templates/assets/tailwind.min.js");
const CHART_SCRIPT: &str = include_str!("../templates/assets/chart.min.js");
const D3_SCRIPT: &str = include_str!("../templates/assets/d3.min.js");
const FONTS_CSS: &str = include_str!("../templates/assets/fonts.css");

/// Dashboard renderer with template registry support
pub struct DashboardRenderer {
    handlebars: Arc<Handlebars<'static>>,
    /// Template registry for managing multiple templates
    template_registry: Option<TemplateRegistry>,
}

impl DashboardRenderer {
    /// Create a new dashboard renderer (built-in templates only)
    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
        Self::with_external_templates(None)
    }

    /// Create a new dashboard renderer with optional external template directory
    ///
    /// The single built-in merged dashboard template lives at
    /// `src/render_engine/dashboard/templates/dashboard_unified.html`.
    /// `None` uses only embedded templates. `Some(path)` additionally loads
    /// external templates from `<path>/<dir>/code.html`.
    pub fn with_external_templates(
        templetes_dir: Option<PathBuf>,
    ) -> Result<Self, Box<dyn std::error::Error>> {
        let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));

        // Build template registry from the single merged built-in template.
        // The templates_dir argument is unused now (kept only for API stability);
        // pass a placeholder that TemplateRegistry will ignore.
        let mut registry = TemplateRegistry::with_built_in_templates(&manifest_dir)?;

        if let Some(external_dir) = templetes_dir {
            registry.set_external_base(external_dir.clone());
            registry.load_external_templates(&external_dir)?;
        }

        // For backward compatibility, keep a separate handlebars for old/direct template names
        let handlebars = template_registry::builtin_handlebars()?;

        Ok(Self {
            handlebars,
            template_registry: Some(registry),
        })
    }

    /// Render using the template registry (new API)
    ///
    /// Injects embedded asset scripts (tailwind, fonts, chart, d3) into the context
    /// so templates can use `{{{tailwind_script}}}`, `{{{fonts_css}}}`, etc.
    pub fn render_with_template(
        &self,
        template_id: &str,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let registry = self
            .template_registry
            .as_ref()
            .ok_or("Template registry not initialized")?;

        let mut data = serde_json::to_value(context)
            .map_err(|e| format!("Failed to serialize context: {}", e))?;

        // Inject asset scripts
        if let Some(obj) = data.as_object_mut() {
            obj.insert(
                "tailwind_script".to_string(),
                serde_json::Value::String(TAILWIND_SCRIPT.to_string()),
            );
            obj.insert(
                "chart_script".to_string(),
                serde_json::Value::String(CHART_SCRIPT.to_string()),
            );
            obj.insert(
                "d3_script".to_string(),
                serde_json::Value::String(D3_SCRIPT.to_string()),
            );
            obj.insert(
                "fonts_css".to_string(),
                serde_json::Value::String(FONTS_CSS.to_string()),
            );
            let duration_fmt = context
                .task_duration_mean_ms
                .map(|value| format!("{value:.2}"))
                .unwrap_or_else(|| "โ€”".into());
            obj.insert(
                "task_duration_mean_ms_fmt".to_string(),
                serde_json::Value::String(duration_fmt),
            );
            // Inject thread_memory_total_fmt (not a native field on DashboardContext)
            let thread_mem_total: usize =
                context.threads.iter().map(|t| t.current_memory_bytes).sum();
            let thread_mem_fmt = if thread_mem_total >= 1_000_000 {
                format!("{:.1} MB", thread_mem_total as f64 / 1_000_000.0)
            } else if thread_mem_total >= 1_000 {
                format!("{:.1} KB", thread_mem_total as f64 / 1_000.0)
            } else {
                format!("{} B", thread_mem_total)
            };
            obj.insert(
                "thread_memory_total".to_string(),
                serde_json::Value::Number(thread_mem_total.into()),
            );
            obj.insert(
                "thread_memory_total_fmt".to_string(),
                serde_json::Value::String(thread_mem_fmt),
            );
            // Inject total_smart_pointers (native field, but needed in template_data)
            obj.insert(
                "total_smart_pointers".to_string(),
                serde_json::Value::Number(context.circular_references.total_smart_pointers.into()),
            );
            // Smart pointer type breakdown
            let mut sp_breakdown: std::collections::BTreeMap<String, usize> =
                std::collections::BTreeMap::new();
            for alloc in &context.allocations {
                if alloc.is_smart_pointer {
                    *sp_breakdown
                        .entry(alloc.smart_pointer_type.clone())
                        .or_insert(0) += 1;
                }
            }
            obj.insert(
                "smart_pointer_breakdown".to_string(),
                serde_json::to_value(&sp_breakdown)
                    .unwrap_or(serde_json::Value::Object(Default::default())),
            );
        }

        registry.render(template_id, &data)
    }

    /// List available template IDs
    pub fn list_templates(&self) -> Vec<String> {
        match &self.template_registry {
            Some(reg) => reg.template_ids(),
            None => vec!["dashboard_unified".to_string()],
        }
    }

    /// Build dashboard context from tracker data
    pub fn build_context_from_tracker(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
    ) -> Result<DashboardContext, Box<dyn std::error::Error>> {
        self.build_context_from_tracker_with_async(tracker, passport_tracker, None)
    }

    /// Build dashboard context from tracker data with async support
    pub fn build_context_from_tracker_with_async(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
        async_tracker: Option<&Arc<crate::capture::backends::async_tracker::AsyncTracker>>,
    ) -> Result<DashboardContext, Box<dyn std::error::Error>> {
        context::build_context_from_tracker_with_async(tracker, passport_tracker, async_tracker)
    }

    /// Render dashboard from tracker data (for standalone template)
    pub fn render_from_tracker(
        &self,
        tracker: &Tracker,
        passport_tracker: &Arc<MemoryPassportTracker>,
    ) -> Result<String, Box<dyn std::error::Error>> {
        let context = self.build_context_from_tracker(tracker, passport_tracker)?;
        self.render_dashboard(&context)
    }

    /// Render dashboard from context
    pub fn render_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_unified_dashboard(context)
    }

    /// Render standalone dashboard (no external dependencies, works with file:// protocol)
    pub fn render_standalone_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_unified_dashboard(context)
    }

    /// Render unified dashboard โ€” uses the merged dashboard_unified template
    pub fn render_unified_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_with_template("dashboard_unified", context)
    }

    /// Render final dashboard โ€” now delegates to the same unified template
    pub fn render_final_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        self.render_with_template("dashboard_unified", context)
    }

    /// Render binary dashboard (legacy template)
    pub fn render_binary_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        render_methods::render_binary_dashboard(&self.handlebars, context)
    }

    /// Render clean dashboard (legacy template)
    pub fn render_clean_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        render_methods::render_clean_dashboard(&self.handlebars, context)
    }

    /// Render hybrid dashboard (legacy template)
    pub fn render_hybrid_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        render_methods::render_hybrid_dashboard(&self.handlebars, context)
    }

    /// Render performance dashboard (legacy template)
    pub fn render_performance_dashboard(
        &self,
        context: &DashboardContext,
    ) -> Result<String, Box<dyn std::error::Error>> {
        render_methods::render_performance_dashboard(&self.handlebars, context)
    }
}

impl Default for DashboardRenderer {
    fn default() -> Self {
        Self::new().expect("Failed to create dashboard renderer")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::render_engine::dashboard::renderer::types::{
        AsyncSummary, CircularReferenceReport, DashboardContext, OwnershipGraphInfo,
        SystemResources,
    };

    fn create_empty_context() -> DashboardContext {
        DashboardContext {
            title: "Test".to_string(),
            export_timestamp: "2024-01-01".to_string(),
            total_memory: "0 B".to_string(),
            total_allocations: 0,
            active_allocations: 0,
            peak_memory: "0 B".to_string(),
            thread_count: 0,
            passport_count: 0,
            leak_count: 0,
            unsafe_count: 0,
            ffi_count: 0,
            allocations: vec![],
            relationships: vec![],
            unsafe_reports: vec![],
            passport_details: vec![],
            allocations_count: 0,
            relationships_count: 0,
            unsafe_reports_count: 0,
            json_data: "{}".to_string(),
            os_name: "test".to_string(),
            architecture: "test".to_string(),
            cpu_cores: 1,
            system_resources: SystemResources {
                os_name: "test".to_string(),
                os_version: "1.0".to_string(),
                architecture: "test".to_string(),
                cpu_cores: 1,
                total_physical: "0 B".to_string(),
                available_physical: "0 B".to_string(),
                used_physical: "0 B".to_string(),
                page_size: 4096,
                cpu_usage_pct: 0.0,
                total_physical_bytes: 0,
                used_physical_bytes: 0,
            },
            threads: vec![],
            async_tasks: vec![],
            async_summary: AsyncSummary {
                total_tasks: 0,
                active_tasks: 0,
                total_allocations: 0,
                total_memory_bytes: 0,
                peak_memory_bytes: 0,
                completed: 0,
                leaked: 0,
                zombie: 0,
                success_rate: 0.0,
            },
            health_score: 100,
            health_status: "Good".to_string(),
            safe_ops_count: 0,
            high_risk_count: 0,
            clean_passport_count: 0,
            active_passport_count: 0,
            leaked_passport_count: 0,
            ffi_tracked_count: 0,
            safe_code_percent: 100,
            ownership_graph: OwnershipGraphInfo {
                total_nodes: 0,
                total_edges: 0,
                total_cycles: 0,
                rc_clone_count: 0,
                arc_clone_count: 0,
                has_issues: false,
                issues: vec![],
                root_cause: None,
            },
            top_allocation_sites: vec![],
            top_leaked_allocations: vec![],
            top_temporary_churn: vec![],
            circular_references: CircularReferenceReport {
                count: 0,
                total_leaked_memory: 0,
                pointers_in_cycles: 0,
                total_smart_pointers: 0,
                has_cycles: false,
            },
            task_graph_json: "{}".to_string(),
            ffi_call_topology: Default::default(),
            symbol_table: vec![],
            symbol_table_count: 0,
            stack_integrity: Default::default(),
            resource_bars: vec![],
            thread_timeline: vec![],
            thread_timeline_count: 0,
            waker_efficiency_grid: vec![],
            task_duration_mean_ms: None,
            task_duration_samples: vec![],
            task_topology_nodes: vec![],
            task_topology_nodes_count: 0,
            task_topology_edges: vec![],
            task_topology_edges_count: 0,
            streaming_topology_stats: Default::default(),
            trace_logs: vec![],
            allocation_lifetimes: Default::default(),
            dependency_graph_nodes: vec![],
            selected_node_detail: None,
            thread_affinity_grid: vec![],
            allocation_interval_histogram: vec![],
            allocation_interval_mean_ms: None,
            allocation_interval_sample_count: 0,
            non_dominant_thread_allocation_share_pct: None,
            system_uptime_formatted: String::new(),
            thread_event_log: vec![],
            thread_policies: vec![],
            resource_limits: vec![],
        }
    }

    /// Objective: Verify that DashboardRenderer creates successfully.
    /// Invariants: Renderer must be created with valid templates registered.
    #[test]
    fn test_dashboard_renderer_creation() {
        let result = DashboardRenderer::new();
        assert!(
            result.is_ok(),
            "DashboardRenderer should create successfully"
        );
    }

    /// Objective: Verify that DashboardRenderer implements Default.
    /// Invariants: Default should create a valid renderer instance.
    #[test]
    fn test_dashboard_renderer_default() {
        let renderer = DashboardRenderer::default();
        let _ = &renderer;
    }

    /// Objective: Verify that render_unified_dashboard works with minimal context.
    /// Invariants: Should render without errors for valid context.
    #[test]
    fn test_render_unified_dashboard() {
        let renderer = DashboardRenderer::new().expect("Should create renderer");
        let context = create_empty_context();
        let result = renderer.render_unified_dashboard(&context);
        assert!(
            result.is_ok(),
            "Should render unified dashboard successfully"
        );
    }

    /// Objective: Verify that render_final_dashboard works with minimal context.
    /// Invariants: Should render without errors for valid context.
    #[test]
    fn test_render_final_dashboard() {
        let renderer = DashboardRenderer::new().expect("Should create renderer");
        let context = create_empty_context();
        let result = renderer.render_final_dashboard(&context);
        assert!(result.is_ok(), "Should render final dashboard successfully");
    }

    /// Objective: Verify that render_dashboard delegates to unified dashboard.
    /// Invariants: Should produce same output as render_unified_dashboard.
    #[test]
    fn test_render_dashboard() {
        let renderer = DashboardRenderer::new().expect("Should create renderer");
        let context = create_empty_context();
        let result = renderer.render_dashboard(&context);
        assert!(result.is_ok(), "Should render dashboard successfully");
    }

    /// Objective: Verify that render_standalone_dashboard delegates correctly.
    /// Invariants: Should produce same output as unified dashboard.
    #[test]
    fn test_render_standalone_dashboard() {
        let renderer = DashboardRenderer::new().expect("Should create renderer");
        let context = create_empty_context();
        let result = renderer.render_standalone_dashboard(&context);
        assert!(
            result.is_ok(),
            "Should render standalone dashboard successfully"
        );
    }

    /// Objective: Preserve missing versus observed-zero metrics through every render path.
    /// Invariants: all eight modes and the complete script survive partial extraction;
    /// unknown pinning is never rendered as OFF, and recorded zero remains numeric zero.
    #[test]
    fn rendered_telemetry_preserves_unknown_and_zero() {
        let renderer = DashboardRenderer::new().expect("built-in templates must load");
        let mut context = create_empty_context();
        context.allocation_interval_mean_ms = Some(0.0);
        context.thread_policies = vec![ThreadPolicy {
            name: "Pinning".into(),
            enabled: None,
        }];
        for html in [
            renderer.render_with_template("dashboard_unified", &context),
            render_methods::render_unified_dashboard(&renderer.handlebars, &context),
            render_methods::render_final_dashboard(&renderer.handlebars, &context),
        ] {
            let html = html.expect("all renderer paths must resolve the same partials");
            for mode in [
                "overview",
                "thread",
                "task",
                "taskgraph",
                "variable",
                "passport",
                "ffi",
                "unsafe",
            ] {
                assert!(
                    html.contains(&format!("id=\"mode-{mode}\"")),
                    "missing dashboard mode {mode}"
                );
            }
            assert!(html.contains("<span>Pinning</span><span class=\"text-outline\" title=\"Unknown means no policy instrumentation is available.\">Unknown</span>"), "missing policy measurements must render as Unknown");
            assert!(
                html.contains("MEAN: 0.0 ms ยท grouped by allocating thread"),
                "zero interval must survive DTO serialization and rendering"
            );
            assert!(
                !html.contains("{{>"),
                "partials must be expanded in the exported HTML"
            );
            assert!(
                html.contains("function renderTaskTopology()"),
                "interactive topology must survive extraction"
            );
            assert!(
                html.contains("Ownership graph issues list items"),
                "final interaction bindings must survive extraction"
            );
        }
    }
}