Skip to main content

ftui_runtime/
telemetry_schema.rs

1#![forbid(unsafe_code)]
2
3//! Canonical telemetry schema for the FrankenTUI runtime (bd-17ar5).
4//!
5//! Defines the unified vocabulary of tracing targets, event names, metric
6//! names, and structured field contracts used across the runtime, effect
7//! system, subscription manager, and harness infrastructure.
8//!
9//! # Purpose
10//!
11//! Without a shared schema, telemetry becomes fragmented across modules.
12//! This module provides:
13//! - Named constants for tracing targets (e.g., `TARGET_RUNTIME`)
14//! - Canonical event names for structured log correlation
15//! - Metric name constants for counter/gauge telemetry
16//! - A schema manifest for validation and documentation
17//!
18//! # Usage
19//!
20//! ```ignore
21//! use ftui_runtime::telemetry_schema::{TARGET_RUNTIME, event};
22//!
23//! tracing::info!(
24//!     target: TARGET_RUNTIME,
25//!     event = event::RUNTIME_STARTUP,
26//!     "runtime started"
27//! );
28//! ```
29
30// ============================================================================
31// Tracing targets
32// ============================================================================
33
34/// Runtime lifecycle events (startup, shutdown, lane resolution).
35pub const TARGET_RUNTIME: &str = "ftui.runtime";
36
37/// Terminal log emission policy and byte counts.
38pub const TARGET_RUNTIME_LOG: &str = "ftui.runtime.log";
39
40/// Effect/command execution and queue telemetry.
41pub const TARGET_EFFECT: &str = "ftui.effect";
42
43/// Process subscription lifecycle (spawn, exit, restart).
44pub const TARGET_PROCESS: &str = "ftui.process";
45
46/// Resize coalescer decisions.
47pub const TARGET_RESIZE: &str = "ftui.decision.resize";
48
49/// Value-of-information sampling decisions.
50pub const TARGET_VOI: &str = "ftui.voi";
51
52/// Bayesian online change-point detection.
53pub const TARGET_BOCPD: &str = "ftui.bocpd";
54
55/// E-process throttle decisions.
56pub const TARGET_EPROCESS: &str = "ftui.eprocess";
57
58/// Frame guardrails (memory / effect-queue budgets): soft trims, emergency
59/// frame drops.
60pub const TARGET_GUARDRAILS: &str = "ftui.guardrails";
61
62/// Accessibility: per-frame tree diffs and screen-reader announcements
63/// (emitted only when `ProgramConfig::accessibility` is set).
64pub const TARGET_A11Y: &str = "ftui.a11y";
65
66// ============================================================================
67// Span names
68// ============================================================================
69
70/// Names of the tracing spans the runtime opens (see
71/// `docs/spec/telemetry-events.md`, sections 3.1 and 3.2). Every
72/// `info_span!` / `debug_span!` site uses these constants; the
73/// `no_stray_target_literals` test keeps it that way.
74pub mod span {
75    /// Model initialization (`Model::init`).
76    pub const PROGRAM_INIT: &str = "ftui.program.init";
77    /// One update cycle (`Model::update`, gesture and accessibility hooks).
78    pub const PROGRAM_UPDATE: &str = "ftui.program.update";
79    /// View rendering (`Model::view`).
80    pub const PROGRAM_VIEW: &str = "ftui.program.view";
81    /// Subscription reconciliation.
82    pub const PROGRAM_SUBSCRIPTIONS: &str = "ftui.program.subscriptions";
83    /// Program shutdown (`Model::on_shutdown`).
84    pub const PROGRAM_SHUTDOWN: &str = "ftui.program.shutdown";
85    /// Error handling (`Model::on_error`).
86    pub const PROGRAM_ERROR: &str = "ftui.program.error";
87
88    /// Complete frame cycle.
89    pub const RENDER_FRAME: &str = "ftui.render.frame";
90    /// Buffer diff computation (strategy selection).
91    pub const RENDER_DIFF: &str = "ftui.render.diff";
92    /// Diff computation inside a present.
93    pub const RENDER_DIFF_COMPUTE: &str = "ftui.render.diff_compute";
94    /// ANSI emission of a frame.
95    pub const RENDER_PRESENT: &str = "ftui.render.present";
96    /// Emission of the diff runs.
97    pub const RENDER_EMIT: &str = "ftui.render.emit";
98    /// Output flush.
99    pub const RENDER_FLUSH: &str = "ftui.render.flush";
100    /// Inline-mode scroll region activation.
101    pub const RENDER_SCROLL_REGION: &str = "ftui.render.scroll_region";
102
103    /// Input event processing.
104    pub const INPUT_EVENT: &str = "ftui.input.event";
105    /// Macro playback.
106    pub const INPUT_MACRO: &str = "ftui.input.macro";
107}
108
109/// Point-in-time decision event names (section 3.3 of the spec).
110pub mod decision {
111    /// Degradation level change.
112    pub const DEGRADATION: &str = "ftui.decision.degradation";
113    /// Capability fallback.
114    pub const FALLBACK: &str = "ftui.decision.fallback";
115    /// Resize handling decision (same string as [`super::TARGET_RESIZE`]).
116    pub const RESIZE: &str = "ftui.decision.resize";
117    /// Screen mode selection.
118    pub const SCREEN_MODE: &str = "ftui.decision.screen_mode";
119}
120
121// ============================================================================
122// Canonical event names
123// ============================================================================
124
125/// Structured event names emitted by the runtime.
126///
127/// These are the `event` field values in structured logs. Using constants
128/// ensures CI can verify event coverage and dashboards can filter reliably.
129pub mod event {
130    /// Program startup with lane and rollout policy.
131    pub const RUNTIME_STARTUP: &str = "runtime.startup";
132
133    /// Effect queue shutdown completed (fast or slow path).
134    pub const EFFECT_QUEUE_SHUTDOWN: &str = "effect_queue.shutdown";
135
136    /// Spawn executor shutdown completed.
137    pub const SPAWN_EXECUTOR_SHUTDOWN: &str = "spawn_executor.shutdown";
138
139    /// Subscription manager stop_all completed.
140    pub const SUBSCRIPTION_STOP_ALL: &str = "subscription.stop_all";
141
142    /// Individual subscription stopped.
143    pub const SUBSCRIPTION_STOP: &str = "subscription.stop";
144
145    /// Command effect started/completed.
146    pub const EFFECT_COMMAND: &str = "effect.command";
147
148    /// Subscription effect started/stopped.
149    pub const EFFECT_SUBSCRIPTION: &str = "effect.subscription";
150
151    /// Effect queue task dropped (backpressure or post-shutdown).
152    pub const QUEUE_DROP: &str = "effect_queue.drop";
153
154    /// Effect timeout exceeded deadline.
155    pub const EFFECT_TIMEOUT: &str = "effect.timeout";
156
157    /// Effect panicked during execution.
158    pub const EFFECT_PANIC: &str = "effect.panic";
159}
160
161// ============================================================================
162// Metric names
163// ============================================================================
164
165/// Monotonic counter and gauge metric names.
166///
167/// These correspond to the `AtomicU64` counters in `effect_system.rs` and
168/// are the canonical names for dashboards and CI gates.
169pub mod metric {
170    /// Total command effects executed.
171    pub const EFFECTS_COMMAND_TOTAL: &str = "effects_command_total";
172
173    /// Total subscription effects started.
174    pub const EFFECTS_SUBSCRIPTION_TOTAL: &str = "effects_subscription_total";
175
176    /// Total effects executed (command + subscription).
177    pub const EFFECTS_EXECUTED_TOTAL: &str = "effects_executed_total";
178
179    /// Total tasks enqueued to the effect queue.
180    pub const EFFECTS_QUEUE_ENQUEUED: &str = "effects_queue_enqueued";
181
182    /// Total tasks processed by the effect queue.
183    pub const EFFECTS_QUEUE_PROCESSED: &str = "effects_queue_processed";
184
185    /// Total tasks dropped (backpressure or shutdown).
186    pub const EFFECTS_QUEUE_DROPPED: &str = "effects_queue_dropped";
187
188    /// Maximum queue depth observed (ratchet-only).
189    pub const EFFECTS_QUEUE_HIGH_WATER: &str = "effects_queue_high_water";
190
191    /// Current in-flight tasks (enqueued - processed - dropped).
192    pub const EFFECTS_QUEUE_IN_FLIGHT: &str = "effects_queue_in_flight";
193}
194
195// ============================================================================
196// Structured field contracts
197// ============================================================================
198
199/// Common structured field names used in tracing spans and events.
200///
201/// Using named constants prevents typos and enables grep-based schema auditing.
202pub mod field {
203    /// Elapsed time in microseconds.
204    pub const ELAPSED_US: &str = "elapsed_us";
205
206    /// Duration in microseconds (for effect timing).
207    pub const DURATION_US: &str = "duration_us";
208
209    /// Subscription or task identifier.
210    pub const SUB_ID: &str = "sub_id";
211
212    /// Command type label.
213    pub const COMMAND_TYPE: &str = "command_type";
214
215    /// Requested runtime lane (before resolution).
216    pub const REQUESTED_LANE: &str = "requested_lane";
217
218    /// Resolved runtime lane (after fallback).
219    pub const RESOLVED_LANE: &str = "resolved_lane";
220
221    /// Rollout policy label.
222    pub const ROLLOUT_POLICY: &str = "rollout_policy";
223
224    /// Timeout in milliseconds.
225    pub const TIMEOUT_MS: &str = "timeout_ms";
226
227    /// Number of pending handles at shutdown.
228    pub const PENDING_HANDLES: &str = "pending_handles";
229
230    /// Drop reason (backpressure, post_shutdown, etc.).
231    pub const REASON: &str = "reason";
232}
233
234// ============================================================================
235// Schema manifest
236// ============================================================================
237
238/// Schema version for forward compatibility.
239pub const SCHEMA_VERSION: &str = "1.0.0";
240
241/// Complete list of registered tracing targets.
242pub const ALL_TARGETS: &[&str] = &[
243    TARGET_RUNTIME,
244    TARGET_RUNTIME_LOG,
245    TARGET_EFFECT,
246    TARGET_PROCESS,
247    TARGET_RESIZE,
248    TARGET_VOI,
249    TARGET_BOCPD,
250    TARGET_EPROCESS,
251    TARGET_GUARDRAILS,
252    TARGET_A11Y,
253];
254
255/// Complete list of registered span names.
256pub const ALL_SPANS: &[&str] = &[
257    span::PROGRAM_INIT,
258    span::PROGRAM_UPDATE,
259    span::PROGRAM_VIEW,
260    span::PROGRAM_SUBSCRIPTIONS,
261    span::PROGRAM_SHUTDOWN,
262    span::PROGRAM_ERROR,
263    span::RENDER_FRAME,
264    span::RENDER_DIFF,
265    span::RENDER_DIFF_COMPUTE,
266    span::RENDER_PRESENT,
267    span::RENDER_EMIT,
268    span::RENDER_FLUSH,
269    span::RENDER_SCROLL_REGION,
270    span::INPUT_EVENT,
271    span::INPUT_MACRO,
272];
273
274/// Complete list of registered decision event names.
275pub const ALL_DECISIONS: &[&str] = &[
276    decision::DEGRADATION,
277    decision::FALLBACK,
278    decision::RESIZE,
279    decision::SCREEN_MODE,
280];
281
282/// Complete list of registered event names.
283pub const ALL_EVENTS: &[&str] = &[
284    event::RUNTIME_STARTUP,
285    event::EFFECT_QUEUE_SHUTDOWN,
286    event::SPAWN_EXECUTOR_SHUTDOWN,
287    event::SUBSCRIPTION_STOP_ALL,
288    event::SUBSCRIPTION_STOP,
289    event::EFFECT_COMMAND,
290    event::EFFECT_SUBSCRIPTION,
291    event::QUEUE_DROP,
292    event::EFFECT_TIMEOUT,
293    event::EFFECT_PANIC,
294];
295
296/// Complete list of registered metric names.
297pub const ALL_METRICS: &[&str] = &[
298    metric::EFFECTS_COMMAND_TOTAL,
299    metric::EFFECTS_SUBSCRIPTION_TOTAL,
300    metric::EFFECTS_EXECUTED_TOTAL,
301    metric::EFFECTS_QUEUE_ENQUEUED,
302    metric::EFFECTS_QUEUE_PROCESSED,
303    metric::EFFECTS_QUEUE_DROPPED,
304    metric::EFFECTS_QUEUE_HIGH_WATER,
305    metric::EFFECTS_QUEUE_IN_FLIGHT,
306];
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311
312    #[test]
313    fn schema_version_is_semver() {
314        let parts: Vec<&str> = SCHEMA_VERSION.split('.').collect();
315        assert_eq!(parts.len(), 3, "schema version must be semver");
316        for part in &parts {
317            assert!(
318                part.parse::<u32>().is_ok(),
319                "each semver component must be a number: {part}"
320            );
321        }
322    }
323
324    #[test]
325    fn all_targets_are_dotted() {
326        for target in ALL_TARGETS {
327            assert!(
328                target.contains('.'),
329                "target should be dotted namespace: {target}"
330            );
331            assert!(
332                target.starts_with("ftui."),
333                "target should start with ftui.: {target}"
334            );
335        }
336    }
337
338    #[test]
339    fn all_events_have_dotted_names() {
340        for event in ALL_EVENTS {
341            assert!(event.contains('.'), "event name should be dotted: {event}");
342        }
343    }
344
345    #[test]
346    fn all_metrics_are_snake_case() {
347        for metric in ALL_METRICS {
348            assert!(
349                metric.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
350                "metric name should be snake_case: {metric}"
351            );
352        }
353    }
354
355    #[test]
356    fn no_duplicate_targets() {
357        let mut seen = std::collections::HashSet::new();
358        for target in ALL_TARGETS {
359            assert!(seen.insert(target), "duplicate target: {target}");
360        }
361    }
362
363    #[test]
364    fn no_duplicate_events() {
365        let mut seen = std::collections::HashSet::new();
366        for event in ALL_EVENTS {
367            assert!(seen.insert(event), "duplicate event: {event}");
368        }
369    }
370
371    #[test]
372    fn no_duplicate_metrics() {
373        let mut seen = std::collections::HashSet::new();
374        for metric in ALL_METRICS {
375            assert!(seen.insert(metric), "duplicate metric: {metric}");
376        }
377    }
378
379    #[test]
380    fn all_spans_are_dotted_and_unique() {
381        let mut seen = std::collections::HashSet::new();
382        for span in ALL_SPANS {
383            assert!(
384                span.starts_with("ftui."),
385                "span should start with ftui.: {span}"
386            );
387            assert!(seen.insert(span), "duplicate span: {span}");
388        }
389        for decision in ALL_DECISIONS {
390            assert!(
391                decision.starts_with("ftui.decision."),
392                "decision event should start with ftui.decision.: {decision}"
393            );
394        }
395    }
396
397    /// Every tracing target and span name in the runtime, core, render and
398    /// showcase crates must come from this module (or, for the showcase's
399    /// own targets, from its constants block), never from a string literal
400    /// at the call site: a typo would otherwise create a target that no
401    /// subscriber filters on and nothing would notice.
402    ///
403    /// Scans the sources at test time. A literal is any `"ftui.` followed by
404    /// a name character outside a comment; the prefix check `"ftui."` (quote
405    /// right after the dot) is allowed. `const NAME: &str = "ftui...."`
406    /// definitions are allowed in this file and in the showcase's
407    /// `crates/ftui-demo-showcase/src/app.rs`. Files listed in
408    /// `docs/telemetry-target-literal-allowlist.txt` (one path per line,
409    /// relative to the workspace root) are skipped; that list may only
410    /// shrink.
411    #[test]
412    fn no_stray_target_literals() {
413        use std::path::{Path, PathBuf};
414
415        let root = Path::new(env!("CARGO_MANIFEST_DIR"))
416            .join("../..")
417            .canonicalize()
418            .expect("workspace root");
419        let allowlist_path = root.join("docs/telemetry-target-literal-allowlist.txt");
420        let allowlist: Vec<PathBuf> = std::fs::read_to_string(&allowlist_path)
421            .map(|text| {
422                text.lines()
423                    .map(str::trim)
424                    .filter(|line| !line.is_empty() && !line.starts_with('#'))
425                    .map(|line| root.join(line))
426                    .collect()
427            })
428            .unwrap_or_default();
429        let this_file = root.join("crates/ftui-runtime/src/telemetry_schema.rs");
430        let showcase_app = root.join("crates/ftui-demo-showcase/src/app.rs");
431
432        fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
433            let Ok(entries) = std::fs::read_dir(dir) else {
434                return;
435            };
436            for entry in entries.flatten() {
437                let path = entry.path();
438                if path.is_dir() {
439                    collect(&path, out);
440                } else if path.extension().is_some_and(|ext| ext == "rs") {
441                    out.push(path);
442                }
443            }
444        }
445
446        let mut files = Vec::new();
447        for dir in [
448            "crates/ftui-runtime/src",
449            "crates/ftui-runtime/tests",
450            "crates/ftui-core/src",
451            "crates/ftui-render/src",
452            "crates/ftui-demo-showcase/src",
453        ] {
454            collect(&root.join(dir), &mut files);
455        }
456        assert!(
457            files.len() > 50,
458            "source scan found too few files: {}",
459            files.len()
460        );
461
462        // A stray literal is a *complete* schema-style name string:
463        // `"ftui.<dotted.name>"` where the run of name characters is closed
464        // immediately by the quote. This flags `"ftui.bocpd"` and
465        // `info_span!("ftui.program.init")` but not a human message that
466        // merely starts with a name, like `"ftui.program.init should exist"`
467        // (a space follows the name), which is not a schema reference.
468        let is_literal = |line: &str| -> bool {
469            let trimmed = line.trim_start();
470            if trimmed.starts_with("//") {
471                return false;
472            }
473            let mut rest = trimmed;
474            while let Some(idx) = rest.find("\"ftui.") {
475                let after = &rest[idx + "\"".len()..];
476                let name_len = after
477                    .bytes()
478                    .take_while(|b| {
479                        b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'.' || *b == b'_'
480                    })
481                    .count();
482                if after.as_bytes().get(name_len) == Some(&b'"') {
483                    return true;
484                }
485                rest = &after[name_len..];
486            }
487            false
488        };
489        let is_definition = |line: &str| -> bool {
490            let trimmed = line.trim_start();
491            (trimmed.starts_with("pub const ") || trimmed.starts_with("const "))
492                && trimmed.contains(": &str = \"ftui.")
493        };
494
495        let mut offenders = Vec::new();
496        for file in files {
497            if file == this_file || allowlist.contains(&file) {
498                continue;
499            }
500            let Ok(text) = std::fs::read_to_string(&file) else {
501                continue;
502            };
503            for (idx, line) in text.lines().enumerate() {
504                if !is_literal(line) {
505                    continue;
506                }
507                if file == showcase_app && is_definition(line) {
508                    continue;
509                }
510                offenders.push(format!(
511                    "{}:{}: {}",
512                    file.strip_prefix(&root).unwrap_or(&file).display(),
513                    idx + 1,
514                    line.trim()
515                ));
516            }
517        }
518        assert!(
519            offenders.is_empty(),
520            "tracing targets and span names must use telemetry_schema constants:\n{}",
521            offenders.join("\n")
522        );
523    }
524}