Skip to main content

skenion_runtime/
telemetry.rs

1use std::{
2    fs, io,
3    path::{Path, PathBuf},
4    sync::atomic::{AtomicU64, Ordering},
5    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
6};
7
8use serde::{Deserialize, Serialize};
9
10use crate::{
11    PreviewState, RuntimeDiagnostic, RuntimePreviewStatusResponse, RuntimeSessionSnapshot,
12};
13
14pub const TELEMETRY_SCHEMA: &str = "skenion.runtime.telemetry";
15pub const TELEMETRY_SCHEMA_VERSION: &str = "0.1.0";
16pub const PREVIEW_TELEMETRY_SCHEMA: &str = "skenion.preview.telemetry";
17pub const PREVIEW_TELEMETRY_SCHEMA_VERSION: &str = "0.1.0";
18static PREVIEW_TELEMETRY_COUNTER: AtomicU64 = AtomicU64::new(0);
19
20#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
21#[serde(rename_all = "camelCase")]
22pub struct RuntimeTelemetrySnapshot {
23    pub schema: String,
24    pub schema_version: String,
25    pub ok: bool,
26    pub timestamp: String,
27    pub session: RuntimeTelemetrySession,
28    pub preview: RuntimeTelemetryPreview,
29    pub render: RuntimeTelemetryRender,
30    pub process: RuntimeTelemetryProcess,
31    pub diagnostics: Vec<RuntimeDiagnostic>,
32}
33
34#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
35#[serde(rename_all = "camelCase")]
36pub struct RuntimeTelemetrySession {
37    pub loaded: bool,
38    pub graph_id: Option<String>,
39    pub graph_revision: Option<String>,
40    pub session_revision: u64,
41    pub control_revision: u64,
42}
43
44#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
45#[serde(rename_all = "camelCase")]
46pub struct RuntimeTelemetryPreview {
47    pub state: PreviewState,
48    pub pid: Option<u32>,
49    pub stale: bool,
50    pub graph_id: Option<String>,
51    pub graph_revision: Option<String>,
52    pub session_revision: Option<u64>,
53    pub preview_session_revision: Option<u64>,
54    pub control_revision: Option<u64>,
55    pub preview_control_revision: Option<u64>,
56    pub control_live: bool,
57    pub last_control_update_at: Option<String>,
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62pub struct RuntimeTelemetryRender {
63    pub active: bool,
64    pub backend: Option<String>,
65    pub renderer: Option<String>,
66    pub frames_rendered: u64,
67    pub approx_fps: Option<f64>,
68    pub last_frame_ms: Option<f64>,
69    pub last_error: Option<String>,
70    pub source_node_id: Option<String>,
71    pub diagnostics: Vec<ShaderDiagnostic>,
72    pub generated_source_available: bool,
73    pub control_revision: Option<u64>,
74    pub preview_control_revision: Option<u64>,
75    pub control_live: bool,
76    pub last_control_update_at: Option<String>,
77}
78
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(rename_all = "camelCase")]
81pub struct RuntimeTelemetryProcess {
82    pub runtime_version: String,
83    pub uptime_ms: u64,
84}
85
86#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct PreviewTelemetryHeartbeat {
89    pub schema: String,
90    pub schema_version: String,
91    pub timestamp: String,
92    pub pid: u32,
93    pub graph_id: String,
94    pub graph_revision: String,
95    pub session_revision: u64,
96    pub renderer: String,
97    pub backend: String,
98    pub frames_rendered: u64,
99    pub approx_fps: Option<f64>,
100    pub last_frame_ms: Option<f64>,
101    pub last_error: Option<String>,
102    pub source_node_id: Option<String>,
103    pub diagnostics: Vec<ShaderDiagnostic>,
104    pub generated_source_available: bool,
105    pub control_revision: Option<u64>,
106    pub preview_control_revision: Option<u64>,
107    pub control_live: bool,
108    pub last_control_update_at: Option<String>,
109}
110
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(rename_all = "lowercase")]
113pub enum ShaderDiagnosticSeverity {
114    Error,
115    Warning,
116    Info,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "kebab-case")]
121pub enum ShaderDiagnosticPhase {
122    InterfaceAnalysis,
123    SourceSync,
124    WgslGeneration,
125    WgslCompile,
126    RenderPipeline,
127    RenderFrame,
128}
129
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(rename_all = "lowercase")]
132pub enum ShaderDiagnosticSource {
133    User,
134    Generated,
135    Runtime,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(rename_all = "camelCase")]
140pub struct ShaderDiagnostic {
141    pub severity: ShaderDiagnosticSeverity,
142    pub phase: ShaderDiagnosticPhase,
143    pub code: String,
144    pub message: String,
145    #[serde(skip_serializing_if = "Option::is_none")]
146    pub line: Option<usize>,
147    #[serde(skip_serializing_if = "Option::is_none")]
148    pub column: Option<usize>,
149    #[serde(skip_serializing_if = "Option::is_none")]
150    pub end_line: Option<usize>,
151    #[serde(skip_serializing_if = "Option::is_none")]
152    pub end_column: Option<usize>,
153    #[serde(skip_serializing_if = "Option::is_none")]
154    pub uniform_id: Option<String>,
155    pub source: ShaderDiagnosticSource,
156}
157
158impl ShaderDiagnostic {
159    pub fn new(
160        severity: ShaderDiagnosticSeverity,
161        phase: ShaderDiagnosticPhase,
162        code: impl Into<String>,
163        message: impl Into<String>,
164        source: ShaderDiagnosticSource,
165    ) -> Self {
166        Self {
167            severity,
168            phase,
169            code: code.into(),
170            message: message.into(),
171            line: None,
172            column: None,
173            end_line: None,
174            end_column: None,
175            uniform_id: None,
176            source,
177        }
178    }
179
180    pub fn error(
181        phase: ShaderDiagnosticPhase,
182        code: impl Into<String>,
183        message: impl Into<String>,
184        source: ShaderDiagnosticSource,
185    ) -> Self {
186        Self::new(
187            ShaderDiagnosticSeverity::Error,
188            phase,
189            code,
190            message,
191            source,
192        )
193    }
194
195    pub fn with_line_column(mut self, line: Option<usize>, column: Option<usize>) -> Self {
196        self.line = line;
197        self.column = column;
198        self
199    }
200
201    pub fn with_uniform_id(mut self, uniform_id: Option<String>) -> Self {
202        self.uniform_id = uniform_id;
203        self
204    }
205}
206
207#[derive(Debug)]
208pub struct PreviewTelemetryWriter {
209    path: PathBuf,
210    graph_id: String,
211    graph_revision: String,
212    session_revision: u64,
213    renderer: String,
214    backend: String,
215    source_node_id: Option<String>,
216    frames_rendered: u64,
217    first_frame_at: Option<Instant>,
218    last_write_at: Option<Instant>,
219    last_frame_ms: Option<f64>,
220    last_error: Option<String>,
221    diagnostics: Vec<ShaderDiagnostic>,
222    generated_source_available: bool,
223    control_revision: Option<u64>,
224    preview_control_revision: Option<u64>,
225    control_live: bool,
226    last_control_update_at: Option<String>,
227}
228
229impl RuntimeTelemetrySnapshot {
230    pub(crate) fn from_parts(
231        session: RuntimeSessionSnapshot,
232        preview: RuntimePreviewStatusResponse,
233        heartbeat: Option<PreviewTelemetryHeartbeat>,
234        dry_run: bool,
235        uptime_ms: u64,
236        diagnostics: Vec<RuntimeDiagnostic>,
237    ) -> Self {
238        let render = render_from_preview(&preview, heartbeat, dry_run, &diagnostics);
239
240        Self {
241            schema: TELEMETRY_SCHEMA.to_owned(),
242            schema_version: TELEMETRY_SCHEMA_VERSION.to_owned(),
243            ok: true,
244            timestamp: unix_ms_timestamp(),
245            session: RuntimeTelemetrySession {
246                loaded: session.loaded(),
247                graph_id: session.graph_id().map(ToOwned::to_owned),
248                graph_revision: session.graph_revision().map(ToOwned::to_owned),
249                session_revision: session.session_revision,
250                control_revision: session.control_revision,
251            },
252            preview: RuntimeTelemetryPreview {
253                state: preview.state,
254                pid: preview.pid,
255                stale: preview.stale,
256                graph_id: preview.graph_id,
257                graph_revision: preview.graph_revision,
258                session_revision: preview.session_revision,
259                preview_session_revision: preview.preview_session_revision,
260                control_revision: preview.control_revision,
261                preview_control_revision: preview.preview_control_revision,
262                control_live: preview.control_live,
263                last_control_update_at: preview.last_control_update_at,
264            },
265            render,
266            process: RuntimeTelemetryProcess {
267                runtime_version: env!("CARGO_PKG_VERSION").to_owned(),
268                uptime_ms,
269            },
270            diagnostics,
271        }
272    }
273}
274
275impl PreviewTelemetryWriter {
276    pub fn new(
277        path: PathBuf,
278        graph_id: String,
279        graph_revision: String,
280        session_revision: u64,
281        renderer: impl Into<String>,
282        backend: impl Into<String>,
283        source_node_id: Option<String>,
284    ) -> Self {
285        let renderer = renderer.into();
286        let generated_source_available = renderer == "fullscreen-shader";
287        Self {
288            path,
289            graph_id,
290            graph_revision,
291            session_revision,
292            renderer,
293            backend: backend.into(),
294            source_node_id,
295            frames_rendered: 0,
296            first_frame_at: None,
297            last_write_at: None,
298            last_frame_ms: None,
299            last_error: None,
300            diagnostics: Vec::new(),
301            generated_source_available,
302            control_revision: None,
303            preview_control_revision: None,
304            control_live: false,
305            last_control_update_at: None,
306        }
307    }
308
309    pub fn record_frame(&mut self, last_frame_ms: f64) {
310        let now = Instant::now();
311        self.frames_rendered += 1;
312        self.first_frame_at.get_or_insert(now);
313        self.last_frame_ms = Some(last_frame_ms.max(0.0));
314        self.write_if_due(now, false);
315    }
316
317    pub fn record_error(&mut self, error: impl Into<String>) {
318        let message = error.into();
319        self.last_error = Some(message.clone());
320        self.diagnostics.push(ShaderDiagnostic::error(
321            ShaderDiagnosticPhase::RenderFrame,
322            "render-error",
323            message,
324            ShaderDiagnosticSource::Runtime,
325        ));
326        self.write_if_due(Instant::now(), true);
327    }
328
329    pub fn record_shader_diagnostic(&mut self, diagnostic: ShaderDiagnostic) {
330        if diagnostic.severity == ShaderDiagnosticSeverity::Error {
331            self.last_error = Some(diagnostic.message.clone());
332        }
333        self.diagnostics.push(diagnostic);
334        self.write_if_due(Instant::now(), true);
335    }
336
337    pub fn record_control_revision(
338        &mut self,
339        control_revision: u64,
340        last_control_update_at: String,
341    ) {
342        self.control_revision = Some(control_revision);
343        self.preview_control_revision = Some(control_revision);
344        self.control_live = true;
345        self.last_control_update_at = Some(last_control_update_at);
346        self.write_if_due(Instant::now(), true);
347    }
348
349    fn write_if_due(&mut self, now: Instant, force: bool) {
350        let due = force
351            || self
352                .last_write_at
353                .map(|last_write| now.duration_since(last_write) >= Duration::from_millis(250))
354                .unwrap_or(true);
355        if !due {
356            return;
357        }
358
359        if let Err(error) = write_preview_telemetry_heartbeat(&self.path, &self.heartbeat(now)) {
360            self.last_error = Some(error);
361        }
362        self.last_write_at = Some(now);
363    }
364
365    fn heartbeat(&self, now: Instant) -> PreviewTelemetryHeartbeat {
366        let elapsed = self
367            .first_frame_at
368            .map(|first_frame| now.duration_since(first_frame).as_secs_f64())
369            .unwrap_or_default();
370        let approx_fps = if self.frames_rendered > 1 && elapsed > 0.0 {
371            Some(round_1(self.frames_rendered as f64 / elapsed))
372        } else {
373            None
374        };
375
376        PreviewTelemetryHeartbeat {
377            schema: PREVIEW_TELEMETRY_SCHEMA.to_owned(),
378            schema_version: PREVIEW_TELEMETRY_SCHEMA_VERSION.to_owned(),
379            timestamp: unix_ms_timestamp(),
380            pid: std::process::id(),
381            graph_id: self.graph_id.clone(),
382            graph_revision: self.graph_revision.clone(),
383            session_revision: self.session_revision,
384            renderer: self.renderer.clone(),
385            backend: self.backend.clone(),
386            frames_rendered: self.frames_rendered,
387            approx_fps,
388            last_frame_ms: self.last_frame_ms.map(round_1),
389            last_error: self.last_error.clone(),
390            source_node_id: self.source_node_id.clone(),
391            diagnostics: self.diagnostics.clone(),
392            generated_source_available: self.generated_source_available,
393            control_revision: self.control_revision,
394            preview_control_revision: self.preview_control_revision,
395            control_live: self.control_live,
396            last_control_update_at: self.last_control_update_at.clone(),
397        }
398    }
399}
400
401pub fn preview_telemetry_path(session_revision: u64) -> PathBuf {
402    let directory = std::env::temp_dir().join("skenion-runtime-preview");
403    let nonce = PREVIEW_TELEMETRY_COUNTER.fetch_add(1, Ordering::Relaxed);
404    directory.join(format!(
405        "preview-{}-{}-{}-telemetry.json",
406        std::process::id(),
407        nonce,
408        session_revision
409    ))
410}
411
412pub fn read_preview_telemetry(path: &Path) -> Result<Option<PreviewTelemetryHeartbeat>, String> {
413    let Some(bytes) = read_preview_telemetry_bytes(path).map_err(|error| error.to_string())? else {
414        return Ok(None);
415    };
416
417    match serde_json::from_slice(&bytes) {
418        Ok(heartbeat) => Ok(Some(heartbeat)),
419        Err(error) => Err(error.to_string()),
420    }
421}
422
423pub fn write_preview_telemetry_heartbeat(
424    path: &Path,
425    heartbeat: &PreviewTelemetryHeartbeat,
426) -> Result<(), String> {
427    write_preview_telemetry_heartbeat_io(path, heartbeat).map_err(|error| error.to_string())
428}
429
430fn read_preview_telemetry_bytes(path: &Path) -> io::Result<Option<Vec<u8>>> {
431    if !path.exists() {
432        return Ok(None);
433    }
434
435    fs::read(path).map(Some)
436}
437
438fn write_preview_telemetry_heartbeat_io(
439    path: &Path,
440    heartbeat: &PreviewTelemetryHeartbeat,
441) -> io::Result<()> {
442    path.parent()
443        .filter(|parent| !parent.as_os_str().is_empty())
444        .map(fs::create_dir_all)
445        .transpose()?;
446    let temp_path = path.with_extension("json.tmp");
447    let bytes = serde_json::to_vec_pretty(heartbeat)
448        .expect("preview telemetry heartbeat should always serialize");
449    fs::write(&temp_path, bytes)?;
450    fs::rename(&temp_path, path)
451}
452
453pub fn unix_ms_timestamp() -> String {
454    let millis = SystemTime::now()
455        .duration_since(UNIX_EPOCH)
456        .map(|duration| duration.as_millis())
457        .unwrap_or_default();
458    format!("unix-ms:{millis}")
459}
460
461fn render_from_preview(
462    preview: &RuntimePreviewStatusResponse,
463    heartbeat: Option<PreviewTelemetryHeartbeat>,
464    dry_run: bool,
465    diagnostics: &[RuntimeDiagnostic],
466) -> RuntimeTelemetryRender {
467    let active = matches!(
468        preview.state,
469        PreviewState::Starting | PreviewState::Running
470    );
471    if dry_run && active {
472        let renderer = heartbeat
473            .as_ref()
474            .map(|heartbeat| heartbeat.renderer.clone())
475            .unwrap_or_else(|| "none".to_owned());
476        let source_node_id = heartbeat
477            .as_ref()
478            .and_then(|heartbeat| heartbeat.source_node_id.clone());
479        let last_error = heartbeat
480            .as_ref()
481            .and_then(|heartbeat| heartbeat.last_error.clone())
482            .or_else(|| preview.message.clone());
483        return RuntimeTelemetryRender {
484            active,
485            backend: Some("dry-run".to_owned()),
486            renderer: Some(renderer),
487            frames_rendered: 0,
488            approx_fps: None,
489            last_frame_ms: None,
490            last_error,
491            source_node_id,
492            diagnostics: heartbeat
493                .as_ref()
494                .map(|heartbeat| heartbeat.diagnostics.clone())
495                .unwrap_or_default(),
496            generated_source_available: heartbeat
497                .as_ref()
498                .is_some_and(|heartbeat| heartbeat.generated_source_available),
499            control_revision: heartbeat
500                .as_ref()
501                .and_then(|heartbeat| heartbeat.control_revision)
502                .or(preview.control_revision),
503            preview_control_revision: heartbeat
504                .as_ref()
505                .and_then(|heartbeat| heartbeat.preview_control_revision)
506                .or(preview.preview_control_revision),
507            control_live: heartbeat
508                .as_ref()
509                .map(|heartbeat| heartbeat.control_live)
510                .unwrap_or(preview.control_live),
511            last_control_update_at: heartbeat
512                .as_ref()
513                .and_then(|heartbeat| heartbeat.last_control_update_at.clone())
514                .or_else(|| preview.last_control_update_at.clone()),
515        };
516    }
517
518    if let Some(heartbeat) = heartbeat {
519        let control_revision = heartbeat.control_revision.or(preview.control_revision);
520        let preview_control_revision = heartbeat
521            .preview_control_revision
522            .or(preview.preview_control_revision);
523        let control_live = heartbeat.control_live || preview.control_live;
524        let last_control_update_at = heartbeat
525            .last_control_update_at
526            .or_else(|| preview.last_control_update_at.clone());
527        return RuntimeTelemetryRender {
528            active,
529            backend: Some(heartbeat.backend),
530            renderer: Some(heartbeat.renderer),
531            frames_rendered: heartbeat.frames_rendered,
532            approx_fps: heartbeat.approx_fps,
533            last_frame_ms: heartbeat.last_frame_ms,
534            last_error: heartbeat.last_error.or_else(|| preview.message.clone()),
535            source_node_id: heartbeat.source_node_id,
536            diagnostics: heartbeat.diagnostics,
537            generated_source_available: heartbeat.generated_source_available,
538            control_revision,
539            preview_control_revision,
540            control_live,
541            last_control_update_at,
542        };
543    }
544
545    RuntimeTelemetryRender {
546        active,
547        backend: None,
548        renderer: None,
549        frames_rendered: 0,
550        approx_fps: None,
551        last_frame_ms: None,
552        last_error: diagnostics
553            .first()
554            .map(|diagnostic| diagnostic.message.clone())
555            .or_else(|| preview.message.clone()),
556        source_node_id: None,
557        diagnostics: Vec::new(),
558        generated_source_available: false,
559        control_revision: preview.control_revision,
560        preview_control_revision: preview.preview_control_revision,
561        control_live: preview.control_live,
562        last_control_update_at: preview.last_control_update_at.clone(),
563    }
564}
565
566fn round_1(value: f64) -> f64 {
567    (value * 10.0).round() / 10.0
568}
569
570#[cfg(test)]
571mod tests {
572    use serde_json::json;
573
574    use super::*;
575    use crate::{
576        DiagnosticSeverity, GraphDocument, GraphNode, ProjectDocumentCurrent, RuntimeDiagnostic,
577    };
578
579    #[test]
580    fn writes_and_reads_preview_heartbeat_atomically() {
581        let path = std::env::temp_dir().join(format!(
582            "skenion-preview-telemetry-test-{}.json",
583            std::process::id()
584        ));
585        let heartbeat = heartbeat();
586
587        write_preview_telemetry_heartbeat(&path, &heartbeat).expect("heartbeat should write");
588        let decoded = read_preview_telemetry(&path)
589            .expect("heartbeat should read")
590            .expect("heartbeat should exist");
591
592        assert_eq!(decoded, heartbeat);
593        std::fs::remove_file(path).expect("heartbeat should be removable");
594    }
595
596    #[test]
597    fn preview_telemetry_path_uses_runtime_preview_directory() {
598        let path = preview_telemetry_path(77);
599        let text = path.to_string_lossy();
600
601        assert!(text.contains("skenion-runtime-preview"));
602        assert!(text.contains("77-telemetry.json"));
603    }
604
605    #[test]
606    fn write_preview_telemetry_creates_nested_parent_directory() {
607        let directory = std::env::temp_dir().join(format!(
608            "skenion-preview-telemetry-nested-{}",
609            std::process::id()
610        ));
611        let path = directory.join("child").join("telemetry.json");
612
613        write_preview_telemetry_heartbeat(&path, &heartbeat()).expect("heartbeat should write");
614
615        assert!(path.exists());
616        std::fs::remove_dir_all(directory).expect("nested heartbeat dir should be removable");
617    }
618
619    #[test]
620    fn read_preview_telemetry_tolerates_missing_file() {
621        let path = std::env::temp_dir().join("skenion-preview-telemetry-missing.json");
622
623        assert_eq!(
624            read_preview_telemetry(&path).expect("read should work"),
625            None
626        );
627    }
628
629    #[test]
630    fn read_preview_telemetry_reports_invalid_json() {
631        let path = std::env::temp_dir().join(format!(
632            "skenion-preview-telemetry-invalid-{}.json",
633            std::process::id()
634        ));
635        std::fs::write(&path, b"{").expect("invalid heartbeat should write");
636
637        let error = read_preview_telemetry(&path).expect_err("invalid heartbeat should fail");
638
639        assert!(error.contains("EOF"));
640        std::fs::remove_file(path).expect("heartbeat should be removable");
641    }
642
643    #[test]
644    fn read_preview_telemetry_reports_read_errors() {
645        let directory = std::env::temp_dir().join(format!(
646            "skenion-preview-telemetry-read-error-{}",
647            std::process::id()
648        ));
649        std::fs::create_dir_all(&directory).expect("directory should be created");
650
651        let error = read_preview_telemetry(&directory).expect_err("directory read should fail");
652
653        assert!(!error.is_empty());
654        std::fs::remove_dir_all(directory).expect("directory should be removable");
655    }
656
657    #[test]
658    fn runtime_snapshot_uses_dry_run_render_state() {
659        let snapshot = RuntimeTelemetrySnapshot::from_parts(
660            session_snapshot(true),
661            preview_status(PreviewState::Running),
662            None,
663            true,
664            42,
665            Vec::new(),
666        );
667
668        assert_eq!(snapshot.schema, TELEMETRY_SCHEMA);
669        assert!(snapshot.session.loaded);
670        assert_eq!(snapshot.preview.state, PreviewState::Running);
671        assert!(snapshot.render.active);
672        assert_eq!(snapshot.render.backend.as_deref(), Some("dry-run"));
673        assert_eq!(snapshot.process.uptime_ms, 42);
674    }
675
676    #[test]
677    fn runtime_snapshot_uses_native_heartbeat() {
678        let snapshot = RuntimeTelemetrySnapshot::from_parts(
679            session_snapshot(true),
680            preview_status(PreviewState::Running),
681            Some(heartbeat()),
682            false,
683            12,
684            Vec::new(),
685        );
686
687        assert_eq!(snapshot.render.backend.as_deref(), Some("wgpu"));
688        assert_eq!(snapshot.render.renderer.as_deref(), Some("clear-color"));
689        assert_eq!(snapshot.render.frames_rendered, 10);
690        assert_eq!(snapshot.render.source_node_id.as_deref(), Some("clear_1"));
691    }
692
693    #[test]
694    fn runtime_snapshot_falls_back_to_preview_control_metadata_for_native_heartbeat() {
695        let mut heartbeat = heartbeat();
696        heartbeat.control_live = false;
697        heartbeat.last_control_update_at = None;
698
699        let snapshot = RuntimeTelemetrySnapshot::from_parts(
700            session_snapshot(true),
701            preview_status(PreviewState::Running),
702            Some(heartbeat),
703            false,
704            12,
705            Vec::new(),
706        );
707
708        assert!(snapshot.render.control_live);
709        assert_eq!(
710            snapshot.render.last_control_update_at.as_deref(),
711            Some("unix-ms:2")
712        );
713    }
714
715    #[test]
716    fn runtime_snapshot_keeps_invalid_heartbeat_diagnostic_nonfatal() {
717        let diagnostic = RuntimeDiagnostic {
718            severity: DiagnosticSeverity::Warning,
719            message: "invalid preview telemetry heartbeat: expected value".to_owned(),
720            code: None,
721            details: None,
722        };
723        let snapshot = RuntimeTelemetrySnapshot::from_parts(
724            session_snapshot(false),
725            preview_status(PreviewState::Stopped),
726            None,
727            false,
728            0,
729            vec![diagnostic],
730        );
731
732        assert!(snapshot.ok);
733        assert_eq!(
734            snapshot.diagnostics[0].severity,
735            DiagnosticSeverity::Warning
736        );
737        assert_eq!(
738            snapshot.render.last_error.as_deref(),
739            Some("invalid preview telemetry heartbeat: expected value")
740        );
741    }
742
743    #[test]
744    fn preview_telemetry_writer_writes_first_frame() {
745        let path = std::env::temp_dir().join(format!(
746            "skenion-preview-telemetry-writer-{}.json",
747            std::process::id()
748        ));
749        let mut writer = PreviewTelemetryWriter::new(
750            path.clone(),
751            "graph".to_owned(),
752            "1".to_owned(),
753            2,
754            "clear-color",
755            "wgpu",
756            Some("clear_1".to_owned()),
757        );
758        writer.record_frame(16.67);
759        let decoded = read_preview_telemetry(&path)
760            .expect("heartbeat should read")
761            .expect("heartbeat should exist");
762
763        assert_eq!(decoded.frames_rendered, 1);
764        assert_eq!(decoded.last_frame_ms, Some(16.7));
765        assert_eq!(decoded.source_node_id.as_deref(), Some("clear_1"));
766        std::fs::remove_file(path).expect("heartbeat should be removable");
767    }
768
769    #[test]
770    fn preview_telemetry_writer_records_control_revision() {
771        let path = std::env::temp_dir().join(format!(
772            "skenion-preview-telemetry-control-revision-{}.json",
773            std::process::id()
774        ));
775        let mut writer = test_writer(path.clone());
776
777        writer.record_control_revision(2, "unix-ms:2".to_owned());
778        let decoded = read_preview_telemetry(&path)
779            .expect("heartbeat should read")
780            .expect("heartbeat should exist");
781
782        assert_eq!(decoded.control_revision, Some(2));
783        assert_eq!(decoded.preview_control_revision, Some(2));
784        assert!(decoded.control_live);
785        assert_eq!(decoded.last_control_update_at.as_deref(), Some("unix-ms:2"));
786        std::fs::remove_file(path).expect("heartbeat should be removable");
787    }
788
789    #[test]
790    fn preview_telemetry_writer_rate_limits_non_forced_writes() {
791        let path = std::env::temp_dir().join(format!(
792            "skenion-preview-telemetry-rate-limit-{}.json",
793            std::process::id()
794        ));
795        let mut writer = test_writer(path.clone());
796
797        writer.record_frame(16.0);
798        writer.record_frame(17.0);
799        let decoded = read_preview_telemetry(&path)
800            .expect("heartbeat should read")
801            .expect("heartbeat should exist");
802
803        assert_eq!(decoded.frames_rendered, 1);
804        assert_eq!(decoded.last_frame_ms, Some(16.0));
805        std::fs::remove_file(path).expect("heartbeat should be removable");
806    }
807
808    #[test]
809    fn preview_telemetry_writer_forces_error_heartbeat() {
810        let path = std::env::temp_dir().join(format!(
811            "skenion-preview-telemetry-error-{}.json",
812            std::process::id()
813        ));
814        let mut writer = test_writer(path.clone());
815
816        writer.record_error("surface lost");
817        let decoded = read_preview_telemetry(&path)
818            .expect("heartbeat should read")
819            .expect("heartbeat should exist");
820
821        assert_eq!(decoded.frames_rendered, 0);
822        assert_eq!(decoded.last_error.as_deref(), Some("surface lost"));
823        assert_eq!(
824            decoded.diagnostics[0].phase,
825            ShaderDiagnosticPhase::RenderFrame
826        );
827        std::fs::remove_file(path).expect("heartbeat should be removable");
828    }
829
830    #[test]
831    fn preview_telemetry_writer_records_shader_diagnostics() {
832        let path = std::env::temp_dir().join(format!(
833            "skenion-preview-telemetry-shader-diagnostic-{}.json",
834            std::process::id()
835        ));
836        let mut writer = test_writer(path.clone());
837
838        writer.record_shader_diagnostic(ShaderDiagnostic {
839            severity: ShaderDiagnosticSeverity::Warning,
840            phase: ShaderDiagnosticPhase::InterfaceAnalysis,
841            code: "unused-uniform".to_owned(),
842            message: "uniform tint is not referenced".to_owned(),
843            line: Some(2),
844            column: Some(5),
845            end_line: None,
846            end_column: None,
847            uniform_id: Some("tint".to_owned()),
848            source: ShaderDiagnosticSource::User,
849        });
850        let warning = read_preview_telemetry(&path)
851            .expect("heartbeat should read")
852            .expect("heartbeat should exist");
853        assert_eq!(warning.last_error, None);
854        assert_eq!(
855            warning.diagnostics[0].severity,
856            ShaderDiagnosticSeverity::Warning
857        );
858
859        writer.record_shader_diagnostic(ShaderDiagnostic::error(
860            ShaderDiagnosticPhase::WgslCompile,
861            "wgsl-validation",
862            "invalid shader module",
863            ShaderDiagnosticSource::Generated,
864        ));
865        let error = read_preview_telemetry(&path)
866            .expect("heartbeat should read")
867            .expect("heartbeat should exist");
868        assert_eq!(error.last_error.as_deref(), Some("invalid shader module"));
869        assert_eq!(error.diagnostics.len(), 2);
870        assert_eq!(
871            error.diagnostics[1].phase,
872            ShaderDiagnosticPhase::WgslCompile
873        );
874        std::fs::remove_file(path).expect("heartbeat should be removable");
875    }
876
877    #[test]
878    fn preview_telemetry_writer_keeps_write_errors_as_last_error() {
879        let blocker = std::env::temp_dir().join(format!(
880            "skenion-preview-telemetry-blocker-{}",
881            std::process::id()
882        ));
883        std::fs::write(&blocker, b"not a directory").expect("blocker should write");
884        let path = blocker.join("telemetry.json");
885        let mut writer = test_writer(path);
886
887        writer.record_frame(16.0);
888
889        assert!(writer.last_error.is_some());
890        std::fs::remove_file(blocker).expect("blocker should be removable");
891    }
892
893    #[test]
894    fn preview_telemetry_writer_calculates_approximate_fps() {
895        let path = std::env::temp_dir().join(format!(
896            "skenion-preview-telemetry-fps-{}.json",
897            std::process::id()
898        ));
899        let mut writer = test_writer(path);
900        let now = Instant::now();
901        writer.frames_rendered = 2;
902        writer.first_frame_at = Some(now - Duration::from_secs(1));
903
904        let heartbeat = writer.heartbeat(now);
905
906        assert_eq!(heartbeat.approx_fps, Some(2.0));
907    }
908
909    fn heartbeat() -> PreviewTelemetryHeartbeat {
910        PreviewTelemetryHeartbeat {
911            schema: PREVIEW_TELEMETRY_SCHEMA.to_owned(),
912            schema_version: PREVIEW_TELEMETRY_SCHEMA_VERSION.to_owned(),
913            timestamp: "unix-ms:1".to_owned(),
914            pid: 123,
915            graph_id: "clear-color-render".to_owned(),
916            graph_revision: "2".to_owned(),
917            session_revision: 5,
918            renderer: "clear-color".to_owned(),
919            backend: "wgpu".to_owned(),
920            frames_rendered: 10,
921            approx_fps: Some(59.8),
922            last_frame_ms: Some(16.7),
923            last_error: None,
924            source_node_id: Some("clear_1".to_owned()),
925            diagnostics: vec![ShaderDiagnostic::error(
926                ShaderDiagnosticPhase::RenderFrame,
927                "test-diagnostic",
928                "test diagnostic",
929                ShaderDiagnosticSource::Runtime,
930            )],
931            generated_source_available: false,
932            control_revision: Some(7),
933            preview_control_revision: Some(7),
934            control_live: true,
935            last_control_update_at: Some("unix-ms:2".to_owned()),
936        }
937    }
938
939    fn test_writer(path: PathBuf) -> PreviewTelemetryWriter {
940        PreviewTelemetryWriter::new(
941            path,
942            "graph".to_owned(),
943            "1".to_owned(),
944            2,
945            "clear-color",
946            "wgpu",
947            Some("clear_1".to_owned()),
948        )
949    }
950
951    fn session_snapshot(loaded: bool) -> RuntimeSessionSnapshot {
952        let graph = loaded.then(|| GraphDocument {
953            schema: "skenion.graph".to_owned(),
954            schema_version: "0.1.0".to_owned(),
955            id: "clear-color-render".to_owned(),
956            revision: "2".to_owned(),
957            nodes: vec![GraphNode {
958                id: "clear_1".to_owned(),
959                kind: "render.clear-color".to_owned(),
960                kind_version: "0.1.0".to_owned(),
961                params: serde_json::Map::new(),
962                ports: Vec::new(),
963            }],
964            edges: Vec::new(),
965        });
966        let project = graph.as_ref().map(project_document);
967        RuntimeSessionSnapshot {
968            session_revision: if loaded { 5 } else { 0 },
969            view_revision: if loaded { 1 } else { 0 },
970            control_revision: if loaded { 7 } else { 0 },
971            project,
972            diagnostics: Vec::new(),
973            plan: None,
974        }
975    }
976
977    fn project_document(graph: &GraphDocument) -> ProjectDocumentCurrent {
978        serde_json::from_value(json!({
979            "schema": "skenion.project",
980            "schemaVersion": "0.1.0",
981            "id": format!("{}-project", graph.id),
982            "revision": graph.revision.clone(),
983            "graph": {
984                "schema": "skenion.graph",
985                "schemaVersion": "0.1.0",
986                "id": graph.id.clone(),
987                "revision": graph.revision.clone(),
988                "nodes": graph.nodes.iter().map(|node| json!({
989                    "id": node.id.clone(),
990                    "kind": node.kind.clone(),
991                    "kindVersion": node.kind_version.clone(),
992                    "params": node.params.clone(),
993                    "ports": []
994                })).collect::<Vec<_>>(),
995                "edges": []
996            },
997            "viewState": default_view_state(graph),
998            "patchLibrary": []
999        }))
1000        .expect("runtime telemetry test project document should parse")
1001    }
1002
1003    fn default_view_state(graph: &GraphDocument) -> serde_json::Value {
1004        json!({
1005            "schema": "skenion.view-state",
1006            "schemaVersion": "0.1.0",
1007            "canvas": {
1008                "nodes": graph.nodes.iter().enumerate().map(|(index, node)| {
1009                    (
1010                        node.id.clone(),
1011                        json!({
1012                            "x": 160.0 * (index as f64),
1013                            "y": 0.0
1014                        }),
1015                    )
1016                }).collect::<serde_json::Map<_, _>>()
1017            }
1018        })
1019    }
1020
1021    fn preview_status(state: PreviewState) -> RuntimePreviewStatusResponse {
1022        let active = state != PreviewState::Stopped;
1023        RuntimePreviewStatusResponse {
1024            ok: true,
1025            state,
1026            pid: active.then_some(123),
1027            graph_id: active.then(|| "clear-color-render".to_owned()),
1028            graph_revision: active.then(|| "2".to_owned()),
1029            session_revision: active.then_some(5),
1030            preview_session_revision: active.then_some(5),
1031            control_revision: active.then_some(7),
1032            preview_control_revision: active.then_some(7),
1033            control_live: active,
1034            last_control_update_at: active.then(|| "unix-ms:2".to_owned()),
1035            stale: false,
1036            started_at: active.then(|| "unix-ms:1".to_owned()),
1037            exited_at: None,
1038            exit_code: None,
1039            message: None,
1040            diagnostics: Vec::new(),
1041        }
1042    }
1043
1044    #[test]
1045    fn preview_heartbeat_json_shape_is_camel_case() {
1046        let value = serde_json::to_value(heartbeat()).expect("heartbeat should serialize");
1047
1048        assert_eq!(value["schema"], json!(PREVIEW_TELEMETRY_SCHEMA));
1049        assert_eq!(
1050            value["schemaVersion"],
1051            json!(PREVIEW_TELEMETRY_SCHEMA_VERSION)
1052        );
1053        assert_eq!(value["framesRendered"], json!(10));
1054        assert_eq!(value["sourceNodeId"], json!("clear_1"));
1055        assert_eq!(value["diagnostics"][0]["phase"], json!("render-frame"));
1056        assert_eq!(value["generatedSourceAvailable"], json!(false));
1057    }
1058}