1#![forbid(unsafe_code)]
2
3pub const TARGET_RUNTIME: &str = "ftui.runtime";
36
37pub const TARGET_RUNTIME_LOG: &str = "ftui.runtime.log";
39
40pub const TARGET_EFFECT: &str = "ftui.effect";
42
43pub const TARGET_PROCESS: &str = "ftui.process";
45
46pub const TARGET_RESIZE: &str = "ftui.decision.resize";
48
49pub const TARGET_VOI: &str = "ftui.voi";
51
52pub const TARGET_BOCPD: &str = "ftui.bocpd";
54
55pub const TARGET_EPROCESS: &str = "ftui.eprocess";
57
58pub const TARGET_GUARDRAILS: &str = "ftui.guardrails";
61
62pub const TARGET_A11Y: &str = "ftui.a11y";
65
66pub const TARGET_WIDTH_CACHE: &str = "ftui.text.width_cache";
68
69pub const TARGET_LOCALE: &str = "ftui.runtime.locale";
71
72pub const TARGET_INPUT_PARSER: &str = "ftui.input.parser";
74
75pub mod span {
84 pub const PROGRAM_INIT: &str = "ftui.program.init";
86 pub const PROGRAM_UPDATE: &str = "ftui.program.update";
88 pub const PROGRAM_VIEW: &str = "ftui.program.view";
90 pub const PROGRAM_SUBSCRIPTIONS: &str = "ftui.program.subscriptions";
92 pub const PROGRAM_SHUTDOWN: &str = "ftui.program.shutdown";
94 pub const PROGRAM_ERROR: &str = "ftui.program.error";
96
97 pub const RENDER_FRAME: &str = "ftui.render.frame";
99 pub const RENDER_DIFF: &str = "ftui.render.diff";
101 pub const RENDER_DIFF_COMPUTE: &str = "ftui.render.diff_compute";
103 pub const RENDER_PRESENT: &str = "ftui.render.present";
105 pub const RENDER_EMIT: &str = "ftui.render.emit";
107 pub const RENDER_FLUSH: &str = "ftui.render.flush";
109 pub const RENDER_SCROLL_REGION: &str = "ftui.render.scroll_region";
111
112 pub const INPUT_EVENT: &str = "ftui.input.event";
114 pub const INPUT_MACRO: &str = "ftui.input.macro";
116}
117
118pub mod decision {
120 pub const DEGRADATION: &str = "ftui.decision.degradation";
122 pub const FALLBACK: &str = "ftui.decision.fallback";
124 pub const RESIZE: &str = "ftui.decision.resize";
126 pub const SCREEN_MODE: &str = "ftui.decision.screen_mode";
128}
129
130pub mod event {
139 pub const RUNTIME_STARTUP: &str = "runtime.startup";
141
142 pub const EFFECT_QUEUE_SHUTDOWN: &str = "effect_queue.shutdown";
144
145 pub const SPAWN_EXECUTOR_SHUTDOWN: &str = "spawn_executor.shutdown";
147
148 pub const SUBSCRIPTION_STOP_ALL: &str = "subscription.stop_all";
150
151 pub const SUBSCRIPTION_STOP: &str = "subscription.stop";
153
154 pub const EFFECT_COMMAND: &str = "effect.command";
156
157 pub const EFFECT_SUBSCRIPTION: &str = "effect.subscription";
159
160 pub const QUEUE_DROP: &str = "effect_queue.drop";
162
163 pub const EFFECT_TIMEOUT: &str = "effect.timeout";
165
166 pub const EFFECT_PANIC: &str = "effect.panic";
168}
169
170pub mod evidence {
176 pub const A11Y_ANNOUNCEMENT: &str = "a11y_announcement";
178 pub const A11Y_TREE: &str = "a11y_tree";
180 pub const BOCPD: &str = "bocpd";
182 pub const BUDGET_DECISION: &str = "budget_decision";
184 pub const CAPABILITY_DECISION: &str = "capability_decision";
186 pub const CERTIFICATE_DECISION: &str = "certificate_decision";
188 pub const CONFIG: &str = "config";
190 pub const CYCLE_TIME_PERCENTILES: &str = "cycle_time_percentiles";
192 pub const DECISION: &str = "decision";
194 pub const DECISION_EVIDENCE: &str = "decision_evidence";
196 pub const DIFF_DECISION: &str = "diff_decision";
198 pub const DIFF_REGIME_TRANSITION: &str = "diff_regime_transition";
200 pub const EFFECT_QUEUE_SELECT: &str = "effect_queue_select";
202 pub const FAIRNESS_CONFIG: &str = "fairness_config";
204 pub const FAIRNESS_DECISION: &str = "fairness_decision";
206 pub const GUARDRAIL_SNAPSHOT: &str = "guardrail_snapshot";
208 pub const INLINE_STRATEGY: &str = "inline_strategy";
210 pub const INLINE_STRATEGY_FALLBACK: &str = "inline_strategy_fallback";
212 pub const REGIME_TRANSITION: &str = "regime_transition";
214 pub const SHADOW_FRAME: &str = "shadow_frame";
216 pub const SUMMARY: &str = "summary";
218 pub const TASK_EXECUTOR_BACKEND: &str = "task_executor_backend";
220 pub const TASK_EXECUTOR_BACKPRESSURE: &str = "task_executor_backpressure";
222 pub const TASK_EXECUTOR_COMPLETE: &str = "task_executor_complete";
224 pub const TASK_EXECUTOR_PANIC: &str = "task_executor_panic";
226 pub const VOI_DECISION: &str = "voi_decision";
228 pub const VOI_OBSERVE: &str = "voi_observe";
230 pub const VOI_SAMPLE: &str = "voi_sample";
232 pub const WIDGET_REFRESH: &str = "widget_refresh";
234 pub const WIDTH_CACHE_STATS: &str = "width_cache_stats";
236}
237
238pub const EVENT_SHADOW_FRAME: &str = evidence::SHADOW_FRAME;
240
241pub mod metric {
250 pub const EFFECTS_COMMAND_TOTAL: &str = "effects_command_total";
252
253 pub const EFFECTS_SUBSCRIPTION_TOTAL: &str = "effects_subscription_total";
255
256 pub const EFFECTS_EXECUTED_TOTAL: &str = "effects_executed_total";
258
259 pub const EFFECTS_QUEUE_ENQUEUED: &str = "effects_queue_enqueued";
261
262 pub const EFFECTS_QUEUE_PROCESSED: &str = "effects_queue_processed";
264
265 pub const EFFECTS_QUEUE_DROPPED: &str = "effects_queue_dropped";
267
268 pub const EFFECTS_QUEUE_HIGH_WATER: &str = "effects_queue_high_water";
270
271 pub const EFFECTS_QUEUE_IN_FLIGHT: &str = "effects_queue_in_flight";
273}
274
275pub mod field {
283 pub const ELAPSED_US: &str = "elapsed_us";
285
286 pub const DURATION_US: &str = "duration_us";
288
289 pub const SUB_ID: &str = "sub_id";
291
292 pub const COMMAND_TYPE: &str = "command_type";
294
295 pub const REQUESTED_LANE: &str = "requested_lane";
297
298 pub const RESOLVED_LANE: &str = "resolved_lane";
300
301 pub const ROLLOUT_POLICY: &str = "rollout_policy";
303
304 pub const TIMEOUT_MS: &str = "timeout_ms";
306
307 pub const PENDING_HANDLES: &str = "pending_handles";
309
310 pub const REASON: &str = "reason";
312}
313
314pub const SCHEMA_VERSION: &str = "1.0.0";
320
321pub const ALL_TARGETS: &[&str] = &[
323 TARGET_RUNTIME,
324 TARGET_RUNTIME_LOG,
325 TARGET_EFFECT,
326 TARGET_PROCESS,
327 TARGET_RESIZE,
328 TARGET_VOI,
329 TARGET_BOCPD,
330 TARGET_EPROCESS,
331 TARGET_GUARDRAILS,
332 TARGET_A11Y,
333 TARGET_WIDTH_CACHE,
334 TARGET_LOCALE,
335 TARGET_INPUT_PARSER,
336];
337
338pub const ALL_SPANS: &[&str] = &[
340 span::PROGRAM_INIT,
341 span::PROGRAM_UPDATE,
342 span::PROGRAM_VIEW,
343 span::PROGRAM_SUBSCRIPTIONS,
344 span::PROGRAM_SHUTDOWN,
345 span::PROGRAM_ERROR,
346 span::RENDER_FRAME,
347 span::RENDER_DIFF,
348 span::RENDER_DIFF_COMPUTE,
349 span::RENDER_PRESENT,
350 span::RENDER_EMIT,
351 span::RENDER_FLUSH,
352 span::RENDER_SCROLL_REGION,
353 span::INPUT_EVENT,
354 span::INPUT_MACRO,
355];
356
357pub const ALL_DECISIONS: &[&str] = &[
359 decision::DEGRADATION,
360 decision::FALLBACK,
361 decision::RESIZE,
362 decision::SCREEN_MODE,
363];
364
365pub const ALL_EVENTS: &[&str] = &[
367 event::RUNTIME_STARTUP,
368 event::EFFECT_QUEUE_SHUTDOWN,
369 event::SPAWN_EXECUTOR_SHUTDOWN,
370 event::SUBSCRIPTION_STOP_ALL,
371 event::SUBSCRIPTION_STOP,
372 event::EFFECT_COMMAND,
373 event::EFFECT_SUBSCRIPTION,
374 event::QUEUE_DROP,
375 event::EFFECT_TIMEOUT,
376 event::EFFECT_PANIC,
377];
378
379pub const ALL_METRICS: &[&str] = &[
381 metric::EFFECTS_COMMAND_TOTAL,
382 metric::EFFECTS_SUBSCRIPTION_TOTAL,
383 metric::EFFECTS_EXECUTED_TOTAL,
384 metric::EFFECTS_QUEUE_ENQUEUED,
385 metric::EFFECTS_QUEUE_PROCESSED,
386 metric::EFFECTS_QUEUE_DROPPED,
387 metric::EFFECTS_QUEUE_HIGH_WATER,
388 metric::EFFECTS_QUEUE_IN_FLIGHT,
389];
390
391pub const ALL_EVIDENCE_EVENTS: &[&str] = &[
393 evidence::A11Y_ANNOUNCEMENT,
394 evidence::A11Y_TREE,
395 evidence::BOCPD,
396 evidence::BUDGET_DECISION,
397 evidence::CAPABILITY_DECISION,
398 evidence::CERTIFICATE_DECISION,
399 evidence::CONFIG,
400 evidence::CYCLE_TIME_PERCENTILES,
401 evidence::DECISION,
402 evidence::DECISION_EVIDENCE,
403 evidence::DIFF_DECISION,
404 evidence::DIFF_REGIME_TRANSITION,
405 evidence::EFFECT_QUEUE_SELECT,
406 evidence::FAIRNESS_CONFIG,
407 evidence::FAIRNESS_DECISION,
408 evidence::GUARDRAIL_SNAPSHOT,
409 evidence::INLINE_STRATEGY,
410 evidence::INLINE_STRATEGY_FALLBACK,
411 evidence::REGIME_TRANSITION,
412 evidence::SHADOW_FRAME,
413 evidence::SUMMARY,
414 evidence::TASK_EXECUTOR_BACKEND,
415 evidence::TASK_EXECUTOR_BACKPRESSURE,
416 evidence::TASK_EXECUTOR_COMPLETE,
417 evidence::TASK_EXECUTOR_PANIC,
418 evidence::VOI_DECISION,
419 evidence::VOI_OBSERVE,
420 evidence::VOI_SAMPLE,
421 evidence::WIDGET_REFRESH,
422 evidence::WIDTH_CACHE_STATS,
423];
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428
429 #[test]
430 fn schema_version_is_semver() {
431 let parts: Vec<&str> = SCHEMA_VERSION.split('.').collect();
432 assert_eq!(parts.len(), 3, "schema version must be semver");
433 for part in &parts {
434 assert!(
435 part.parse::<u32>().is_ok(),
436 "each semver component must be a number: {part}"
437 );
438 }
439 }
440
441 #[test]
442 fn all_targets_are_dotted() {
443 for target in ALL_TARGETS {
444 assert!(
445 target.contains('.'),
446 "target should be dotted namespace: {target}"
447 );
448 assert!(
449 target.starts_with("ftui."),
450 "target should start with ftui.: {target}"
451 );
452 }
453 }
454
455 #[test]
456 fn all_events_have_dotted_names() {
457 for event in ALL_EVENTS {
458 assert!(event.contains('.'), "event name should be dotted: {event}");
459 }
460 }
461
462 #[test]
463 fn all_metrics_are_snake_case() {
464 for metric in ALL_METRICS {
465 assert!(
466 metric.chars().all(|c| c.is_ascii_lowercase() || c == '_'),
467 "metric name should be snake_case: {metric}"
468 );
469 }
470 }
471
472 #[test]
473 fn no_duplicate_targets() {
474 let mut seen = std::collections::HashSet::new();
475 for target in ALL_TARGETS {
476 assert!(seen.insert(target), "duplicate target: {target}");
477 }
478 }
479
480 #[test]
481 fn no_duplicate_events() {
482 let mut seen = std::collections::HashSet::new();
483 for event in ALL_EVENTS {
484 assert!(seen.insert(event), "duplicate event: {event}");
485 }
486 }
487
488 #[test]
489 fn no_duplicate_metrics() {
490 let mut seen = std::collections::HashSet::new();
491 for metric in ALL_METRICS {
492 assert!(seen.insert(metric), "duplicate metric: {metric}");
493 }
494 }
495
496 #[test]
497 fn all_spans_are_dotted_and_unique() {
498 let mut seen = std::collections::HashSet::new();
499 for span in ALL_SPANS {
500 assert!(
501 span.starts_with("ftui."),
502 "span should start with ftui.: {span}"
503 );
504 assert!(seen.insert(span), "duplicate span: {span}");
505 }
506 for decision in ALL_DECISIONS {
507 assert!(
508 decision.starts_with("ftui.decision."),
509 "decision event should start with ftui.decision.: {decision}"
510 );
511 }
512 }
513
514 #[test]
529 fn no_stray_target_literals() {
530 use std::path::{Path, PathBuf};
531
532 let root = Path::new(env!("CARGO_MANIFEST_DIR"))
533 .join("../..")
534 .canonicalize()
535 .expect("workspace root");
536 let allowlist_path = root.join("docs/telemetry-target-literal-allowlist.txt");
537 let allowlist: Vec<PathBuf> = std::fs::read_to_string(&allowlist_path)
538 .map(|text| {
539 text.lines()
540 .map(str::trim)
541 .filter(|line| !line.is_empty() && !line.starts_with('#'))
542 .map(|line| root.join(line))
543 .collect()
544 })
545 .unwrap_or_default();
546 let this_file = root.join("crates/ftui-runtime/src/telemetry_schema.rs");
547 let showcase_app = root.join("crates/ftui-demo-showcase/src/app.rs");
548 let core_lib = root.join("crates/ftui-core/src/lib.rs");
549
550 fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
551 let Ok(entries) = std::fs::read_dir(dir) else {
552 return;
553 };
554 for entry in entries.flatten() {
555 let path = entry.path();
556 if path.is_dir() {
557 collect(&path, out);
558 } else if path.extension().is_some_and(|ext| ext == "rs") {
559 out.push(path);
560 }
561 }
562 }
563
564 let mut files = Vec::new();
565 for dir in [
566 "crates/ftui-runtime/src",
567 "crates/ftui-runtime/tests",
568 "crates/ftui-core/src",
569 "crates/ftui-render/src",
570 "crates/ftui-demo-showcase/src",
571 ] {
572 collect(&root.join(dir), &mut files);
573 }
574 assert!(
575 files.len() > 50,
576 "source scan found too few files: {}",
577 files.len()
578 );
579
580 let is_literal = |line: &str| -> bool {
587 let trimmed = line.trim_start();
588 if trimmed.starts_with("//") {
589 return false;
590 }
591 let mut rest = trimmed;
592 while let Some(idx) = rest.find("\"ftui.") {
593 let after = &rest[idx + "\"".len()..];
594 let name_len = after
595 .bytes()
596 .take_while(|b| {
597 b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'.' || *b == b'_'
598 })
599 .count();
600 if after.as_bytes().get(name_len) == Some(&b'"') {
601 return true;
602 }
603 rest = &after[name_len..];
604 }
605 false
606 };
607 let is_definition = |line: &str| -> bool {
608 let trimmed = line.trim_start();
609 (trimmed.starts_with("pub const ")
614 || trimmed.starts_with("pub(crate) const ")
615 || trimmed.starts_with("const "))
616 && trimmed.contains(": &str = \"ftui.")
617 };
618
619 let mut offenders = Vec::new();
620 for file in files {
621 if file == this_file || allowlist.contains(&file) {
622 continue;
623 }
624 let Ok(text) = std::fs::read_to_string(&file) else {
625 continue;
626 };
627 for (idx, line) in text.lines().enumerate() {
628 if !is_literal(line) {
629 continue;
630 }
631 if (file == showcase_app || file == core_lib) && is_definition(line) {
632 continue;
633 }
634 offenders.push(format!(
635 "{}:{}: {}",
636 file.strip_prefix(&root).unwrap_or(&file).display(),
637 idx + 1,
638 line.trim()
639 ));
640 }
641 }
642 assert!(
643 offenders.is_empty(),
644 "tracing targets and span names must use telemetry_schema constants:\n{}",
645 offenders.join("\n")
646 );
647 }
648
649 #[test]
650 fn core_width_cache_target_matches_schema() {
651 assert_eq!(
652 TARGET_WIDTH_CACHE,
653 ftui_core::text_width::TARGET_WIDTH_CACHE
654 );
655 }
656
657 #[test]
658 fn all_targets_include_guardrails_and_a11y() {
659 assert!(ALL_TARGETS.contains(&TARGET_GUARDRAILS));
660 assert!(ALL_TARGETS.contains(&TARGET_A11Y));
661 }
662
663 #[test]
664 fn all_targets_unique_and_prefixed() {
665 let mut seen = std::collections::HashSet::new();
666 for target in ALL_TARGETS {
667 assert!(
668 target.starts_with("ftui."),
669 "target must start with ftui.: {target}"
670 );
671 assert!(seen.insert(target), "duplicate target: {target}");
672 }
673 }
674
675 #[test]
676 fn all_evidence_events_unique_and_snake_case() {
677 let mut seen = std::collections::HashSet::new();
678 for event in ALL_EVIDENCE_EVENTS {
679 assert!(
680 event
681 .chars()
682 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
683 "evidence event must be snake_case: {event}"
684 );
685 assert!(seen.insert(event), "duplicate evidence event: {event}");
686 }
687 }
688
689 #[test]
690 fn schema_events_match_constants() {
691 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
692 .join("../..")
693 .canonicalize()
694 .expect("workspace root");
695 let schema_path = root.join("tests/e2e/lib/e2e_evidence_schema.json");
696 let text = std::fs::read_to_string(&schema_path).expect("e2e_evidence_schema.json");
697 let json: serde_json::Value = serde_json::from_str(&text).expect("valid json");
698 let events_obj = json
699 .get("events")
700 .and_then(|v| v.as_object())
701 .expect("events object");
702 let schema_keys: std::collections::BTreeSet<&str> =
703 events_obj.keys().map(String::as_str).collect();
704 let const_keys: std::collections::BTreeSet<&str> =
705 ALL_EVIDENCE_EVENTS.iter().copied().collect();
706 assert_eq!(
707 schema_keys, const_keys,
708 "evidence schema events must match ALL_EVIDENCE_EVENTS"
709 );
710 }
711
712 #[test]
713 fn spec_lists_every_evidence_event() {
714 let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
715 .join("../..")
716 .canonicalize()
717 .expect("workspace root");
718 let spec_path = root.join("docs/spec/telemetry-events.md");
719 let spec = std::fs::read_to_string(&spec_path).expect("docs/spec/telemetry-events.md");
720 for event in ALL_EVIDENCE_EVENTS {
721 let heading = format!("#### Event: `{event}`");
722 assert!(
723 spec.contains(&heading),
724 "docs/spec/telemetry-events.md is missing heading `{heading}`"
725 );
726 }
727 }
728
729 #[test]
730 fn no_untargeted_tracing_macros_in_runtime() {
731 use std::path::{Path, PathBuf};
732
733 let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
734 fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
735 let Ok(entries) = std::fs::read_dir(dir) else {
736 return;
737 };
738 for entry in entries.flatten() {
739 let path = entry.path();
740 if path.is_dir() {
741 collect(&path, out);
742 } else if path.extension().is_some_and(|ext| ext == "rs") {
743 out.push(path);
744 }
745 }
746 }
747
748 let mut files = Vec::new();
749 collect(&src_dir, &mut files);
750 files.sort();
751
752 let mut offenders = Vec::new();
753 for file in files {
754 if file.file_name().is_some_and(|n| n == "debug_trace.rs") {
755 continue;
756 }
757 let text = std::fs::read_to_string(&file).expect("read source");
758 let prod = match text.find("#[cfg(test)]") {
759 Some(idx) => &text[..idx],
760 None => &text[..],
761 };
762 let bytes = prod.as_bytes();
763 let mut idx = 0;
764 while idx < bytes.len() {
765 if bytes[idx..].starts_with(b"//") {
767 while idx < bytes.len() && bytes[idx] != b'\n' {
768 idx += 1;
769 }
770 continue;
771 }
772 if bytes[idx..].starts_with(b"/*") {
773 idx += 2;
774 while idx + 1 < bytes.len() && !bytes[idx..].starts_with(b"*/") {
775 idx += 1;
776 }
777 idx += 2;
778 continue;
779 }
780 for macro_name in ["trace!", "debug!", "info!", "warn!", "error!"] {
781 if bytes[idx..].starts_with(macro_name.as_bytes()) {
782 let prev = if idx > 0 { bytes[idx - 1] } else { b' ' };
783 if prev.is_ascii_alphanumeric() || prev == b'_' {
784 continue;
785 }
786 let after = &prod[idx + macro_name.len()..];
787 let trimmed = after.trim_start();
788 if trimmed.starts_with('(') {
789 let end = trimmed.find(");").unwrap_or_else(|| {
790 let mut e = trimmed.len().min(300);
791 while !trimmed.is_char_boundary(e) {
792 e -= 1;
793 }
794 e
795 });
796 let body = &trimmed[..end];
797 if !body.contains("target:") {
798 let line_no =
799 bytes[..idx].iter().filter(|&&b| b == b'\n').count() + 1;
800 offenders.push(format!(
801 "{}:{}: untargeted {}",
802 file.strip_prefix(&src_dir).unwrap_or(&file).display(),
803 line_no,
804 macro_name
805 ));
806 }
807 }
808 }
809 }
810 idx += 1;
811 }
812 }
813
814 assert!(
815 offenders.is_empty(),
816 "all production tracing macros in ftui-runtime must specify `target:`:\n{}",
817 offenders.join("\n")
818 );
819 }
820}