candle-graph 0.5.0

TensorFlow Profiler-style execution graphs for candle-rs (trace-only)
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
//! Structural trust and evidence-coverage checks for a parsed trace.

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

use crate::phase::{ExecutionPhase, ExecutionStep};

use super::TraceDocument;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HealthSeverity {
    Error,
    Warning,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HealthIssue {
    pub severity: HealthSeverity,
    pub code: String,
    pub message: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EvidenceCoverage {
    pub spans: usize,
    pub closed_spans: usize,
    pub root_spans: usize,
    pub measured_spans: usize,
    pub operations: usize,
    pub tensors: usize,
    pub memory_events: usize,
    pub device_memory_samples: usize,
    pub gradients: usize,
    pub edges: usize,
    pub forward_spans: usize,
    pub backward_spans: usize,
    pub optimizer_spans: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TraceHealth {
    pub trusted: bool,
    pub issues: Vec<HealthIssue>,
    pub coverage: EvidenceCoverage,
}

impl TraceHealth {
    pub fn gaps(&self) -> impl Iterator<Item = &HealthIssue> {
        self.issues
            .iter()
            .filter(|issue| issue.severity == HealthSeverity::Warning)
    }
}

pub fn analyze_health(doc: &TraceDocument) -> TraceHealth {
    let ids: HashSet<&str> = doc.spans.iter().map(|span| span.id.as_str()).collect();
    let by_id: HashMap<&str, _> = doc
        .spans
        .iter()
        .map(|span| (span.id.as_str(), span))
        .collect();
    let mut issues = Vec::new();
    if ids.len() != doc.spans.len() {
        error(
            &mut issues,
            "duplicate_span_id",
            format!(
                "span IDs must be unique; found {} records but {} unique IDs",
                doc.spans.len(),
                ids.len()
            ),
        );
    }
    let root_spans = doc
        .spans
        .iter()
        .filter(|span| span.parent_id.is_none())
        .count();
    if root_spans != 1 {
        error(
            &mut issues,
            "root_count",
            format!("expected exactly one root span, found {root_spans}"),
        );
    }
    let measured_spans = doc.spans.iter().filter(|span| span.measured).count();
    if measured_spans != 1 {
        error(
            &mut issues,
            "measurement_count",
            format!("expected exactly one measured region, found {measured_spans}"),
        );
    }
    for span in &doc.spans {
        if !span.closed {
            error(
                &mut issues,
                "open_span",
                format!("span `{}` was not closed", span.id),
            );
        }
        if let Some(parent) = span.parent_id.as_deref() {
            match by_id.get(parent) {
                None => error(
                    &mut issues,
                    "unknown_parent",
                    format!("span `{}` refers to missing parent `{parent}`", span.id),
                ),
                Some(parent_span) => {
                    let child_end = span.start_ns.saturating_add(span.duration_ns);
                    let parent_end = parent_span.start_ns.saturating_add(parent_span.duration_ns);
                    if span.start_ns < parent_span.start_ns || child_end > parent_end {
                        error(
                            &mut issues,
                            "child_outside_parent",
                            format!(
                                "span `{}` interval {}..{} is outside parent `{parent}` interval {}..{}",
                                span.id,
                                span.start_ns,
                                child_end,
                                parent_span.start_ns,
                                parent_end
                            ),
                        );
                    }
                }
            }
        }
        let mut current = Some(span.id.as_str());
        let mut seen = HashSet::new();
        while let Some(id) = current {
            if !seen.insert(id) {
                error(
                    &mut issues,
                    "span_cycle",
                    format!("span `{}` participates in a parent cycle", span.id),
                );
                break;
            }
            current = by_id.get(id).and_then(|item| item.parent_id.as_deref());
        }
    }
    for parent in &doc.spans {
        let child_total: u64 = doc
            .spans
            .iter()
            .filter(|span| span.parent_id.as_deref() == Some(parent.id.as_str()))
            .map(|span| span.duration_ns)
            .sum();
        if child_total > parent.duration_ns {
            error(
                &mut issues,
                "children_exceed_parent",
                format!(
                    "children of span `{}` total {} ns, exceeding its {} ns duration",
                    parent.id, child_total, parent.duration_ns
                ),
            );
        }
    }
    for (kind, span_id) in doc
        .ops
        .iter()
        .map(|x| ("operation", x.span_id.as_str()))
        .chain(doc.tensors.iter().map(|x| ("tensor", x.span_id.as_str())))
        .chain(doc.memory.iter().map(|x| ("memory", x.span_id.as_str())))
    {
        if !ids.contains(span_id) {
            error(
                &mut issues,
                "unknown_span",
                format!("{kind} evidence refers to missing span `{span_id}`"),
            );
        }
    }
    for edge in &doc.edges {
        if !ids.contains(edge.from_span.as_str()) || !ids.contains(edge.to_span.as_str()) {
            error(
                &mut issues,
                "unknown_edge_span",
                format!(
                    "edge `{}` -> `{}` refers to a missing span",
                    edge.from_span, edge.to_span
                ),
            );
        }
    }
    let mut live_memory = HashSet::new();
    let mut memory = doc.memory.iter().collect::<Vec<_>>();
    memory.sort_by_key(|event| event.timestamp_ns);
    for event in memory {
        let key = (event.device.as_str(), event.tensor_id.as_str());
        match event.action {
            super::MemoryAction::Alloc if !live_memory.insert(key) => error(
                &mut issues,
                "duplicate_allocation",
                format!(
                    "tensor `{}` was allocated twice without a free",
                    event.tensor_id
                ),
            ),
            super::MemoryAction::Free if !live_memory.remove(&key) => error(
                &mut issues,
                "unpaired_free",
                format!(
                    "tensor `{}` was freed without a live allocation",
                    event.tensor_id
                ),
            ),
            _ => {}
        }
    }
    if !live_memory.is_empty() {
        warning(
            &mut issues,
            "retained_allocations",
            format!(
                "{} explicit allocations remained live at measurement end",
                live_memory.len()
            ),
        );
    }

    let coverage = EvidenceCoverage {
        spans: doc.spans.len(),
        closed_spans: doc.spans.iter().filter(|span| span.closed).count(),
        root_spans,
        measured_spans,
        operations: doc.ops.len(),
        tensors: doc.tensors.len(),
        memory_events: doc.memory.len(),
        device_memory_samples: doc.device_memory.len(),
        gradients: doc.gradients.len(),
        edges: doc.edges.len(),
        forward_spans: step_count(doc, ExecutionStep::Forward),
        backward_spans: step_count(doc, ExecutionStep::Backward),
        optimizer_spans: step_count(doc, ExecutionStep::Optimizer),
    };

    for (empty, code, message) in [
        (
            coverage.operations == 0,
            "operations_absent",
            "no timed operation evidence was captured",
        ),
        (
            coverage.tensors == 0,
            "tensors_absent",
            "no tensor checkpoints were captured",
        ),
        (
            coverage.memory_events == 0,
            "memory_absent",
            "no tensor memory events were captured",
        ),
        (
            coverage.device_memory_samples == 0,
            "device_memory_absent",
            "no device-memory checkpoints were captured",
        ),
        (
            coverage.gradients == 0 && doc.run.phase == ExecutionPhase::Train,
            "gradients_absent",
            "no gradient facts were captured for this training run",
        ),
        (
            coverage.forward_spans == 0 && doc.run.phase == ExecutionPhase::Train,
            "forward_absent",
            "no forward span was tagged",
        ),
        (
            coverage.backward_spans == 0 && doc.run.phase == ExecutionPhase::Train,
            "backward_absent",
            "no backward span was tagged",
        ),
        (
            coverage.optimizer_spans == 0 && doc.run.phase == ExecutionPhase::Train,
            "optimizer_absent",
            "no optimizer span was tagged",
        ),
    ] {
        if empty {
            warning(&mut issues, code, message);
        }
    }

    let trusted = !issues
        .iter()
        .any(|issue| issue.severity == HealthSeverity::Error);
    TraceHealth {
        trusted,
        issues,
        coverage,
    }
}

fn step_count(doc: &TraceDocument, step: ExecutionStep) -> usize {
    doc.spans
        .iter()
        .filter(|span| span.step == Some(step))
        .count()
}

fn error(issues: &mut Vec<HealthIssue>, code: &str, message: impl Into<String>) {
    issues.push(HealthIssue {
        severity: HealthSeverity::Error,
        code: code.into(),
        message: message.into(),
    });
}

fn warning(issues: &mut Vec<HealthIssue>, code: &str, message: impl Into<String>) {
    issues.push(HealthIssue {
        severity: HealthSeverity::Warning,
        code: code.into(),
        message: message.into(),
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::trace::{SpanKind, SpanRecord, TimingMode, TraceRunMeta, SCHEMA};

    fn document(spans: Vec<SpanRecord>) -> TraceDocument {
        TraceDocument {
            schema: SCHEMA.into(),
            run: TraceRunMeta {
                run_id: "health".into(),
                correlation_id: "health/update-1".into(),
                entrypoint: "health".into(),
                phase: ExecutionPhase::Infer,
                timestamp: "2026-08-08T00:00:00Z".into(),
                capture_step: 1,
                warmup_steps: 0,
                device: "cpu".into(),
                timing_mode: TimingMode::Host,
                tags: Default::default(),
                candle_version: None,
            },
            spans,
            ops: vec![],
            tensors: vec![],
            memory: vec![],
            device_memory: vec![],
            gradients: vec![],
            edges: vec![],
        }
    }

    fn span(id: &str, parent: Option<&str>, measured: bool, duration_ns: u64) -> SpanRecord {
        SpanRecord {
            id: id.into(),
            parent_id: parent.map(str::to_string),
            name: id.into(),
            kind: SpanKind::Function,
            measured,
            start_ns: 0,
            closed: true,
            duration_ns,
            step: None,
        }
    }

    #[test]
    fn rejects_multiple_roots_before_graph_building() {
        let health = analyze_health(&document(vec![
            span("a", None, true, 10),
            span("b", None, false, 10),
        ]));
        assert!(!health.trusted);
        assert!(health.issues.iter().any(|issue| issue.code == "root_count"));
    }

    #[test]
    fn rejects_disconnected_parent_cycle() {
        let health = analyze_health(&document(vec![
            span("root", None, true, 100),
            span("a", Some("b"), false, 0),
            span("b", Some("a"), false, 0),
        ]));
        assert!(!health.trusted);
        assert!(health.issues.iter().any(|issue| issue.code == "span_cycle"));
    }

    #[test]
    fn rejects_aggregate_child_time_larger_than_parent() {
        let health = analyze_health(&document(vec![
            span("root", None, true, 100),
            span("a", Some("root"), false, 70),
            span("b", Some("root"), false, 70),
        ]));
        assert!(!health.trusted);
        assert!(health
            .issues
            .iter()
            .any(|issue| issue.code == "children_exceed_parent"));
    }

    #[test]
    fn rejects_duplicate_ids_and_child_outside_parent_interval() {
        let mut spans = vec![
            span("root", None, true, 100),
            span("child", Some("root"), false, 10),
            span("child", Some("root"), false, 10),
        ];
        spans[1].start_ns = 101;
        spans[2].start_ns = 101;
        let health = analyze_health(&document(spans));
        assert!(!health.trusted);
        assert!(health
            .issues
            .iter()
            .any(|issue| issue.code == "duplicate_span_id"));
        assert!(health
            .issues
            .iter()
            .any(|issue| issue.code == "child_outside_parent"));
    }
}