Skip to main content

ftui_runtime/
schema_compat.rs

1#![forbid(unsafe_code)]
2
3//! Suite-wide trace and evidence schema compatibility (bd-ehk.3).
4//!
5//! Centralizes schema version constants for all FrankenTUI trace and evidence
6//! formats, and provides a compatibility checker that validates reader/writer
7//! version pairs.
8//!
9//! # Schema Kinds
10//!
11//! | Kind           | Current Version        | Format   |
12//! |----------------|------------------------|----------|
13//! | Evidence       | `ftui-evidence-v2`     | JSONL    |
14//! | RenderTrace    | `render-trace-v2`      | JSONL    |
15//! | EventTrace     | `event-trace-v1`       | JSONL.gz |
16//! | GoldenTrace    | `golden-trace-v2`      | JSONL    |
17//! | Telemetry      | `1.0.0`                | OTLP     |
18//! | MigrationIr    | `migration-ir-v1`      | JSON     |
19//!
20//! # Compatibility Rules
21//!
22//! - **Exact**: reader version == writer version → always compatible.
23//! - **Forward**: reader is newer than writer → compatible (reader can
24//!   understand older formats), except GoldenTrace.
25//! - **MigrationRequired**: older GoldenTrace data is incompatible: v1 lacks
26//!   the explicit execution boundaries required by v2. Re-record from the
27//!   original session source; guessing boundaries cannot preserve execution.
28//! - **Backward**: writer is newer than reader → incompatible (reader cannot
29//!   understand newer formats without migration).
30//! - **Unknown**: version string doesn't match the expected prefix for its
31//!   schema kind → incompatible.
32//!
33//! # Tracing
34//!
35//! Every compatibility check emits a `trace.compat_check` span with fields:
36//! `schema_version`, `reader_version`, `writer_version`, `compatible`.
37//! Incompatible checks log at ERROR level.
38//!
39//! # Metrics
40//!
41//! Incompatible checks increment `trace_compat_failures_total` via
42//! [`BuiltinCounter::TraceCompatFailuresTotal`].
43
44use std::fmt;
45
46use crate::metrics_registry::{BuiltinCounter, METRICS};
47
48// ============================================================================
49// Schema Kind
50// ============================================================================
51
52/// All schema kinds in the FrankenTUI suite.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
54pub enum SchemaKind {
55    /// Unified evidence ledger JSONL (`ftui-evidence-v{N}`).
56    Evidence,
57    /// Render-trace JSONL (`render-trace-v{N}`).
58    RenderTrace,
59    /// Event-trace JSONL.gz (`event-trace-v{N}`).
60    EventTrace,
61    /// Golden-trace JSONL (`golden-trace-v{N}`).
62    GoldenTrace,
63    /// Telemetry OTLP (`{major}.{minor}.{patch}`).
64    Telemetry,
65    /// Doctor migration IR JSON (`migration-ir-v{N}`).
66    MigrationIr,
67}
68
69impl SchemaKind {
70    /// All schema kinds.
71    pub const ALL: [Self; 6] = [
72        Self::Evidence,
73        Self::RenderTrace,
74        Self::EventTrace,
75        Self::GoldenTrace,
76        Self::Telemetry,
77        Self::MigrationIr,
78    ];
79
80    /// Current version string for this schema kind.
81    pub const fn current_version(self) -> &'static str {
82        match self {
83            Self::Evidence => "ftui-evidence-v2",
84            Self::RenderTrace => crate::render_trace::RENDER_TRACE_SCHEMA_VERSION,
85            Self::EventTrace => "event-trace-v1",
86            Self::GoldenTrace => "golden-trace-v2",
87            Self::Telemetry => "1.0.0",
88            Self::MigrationIr => "migration-ir-v1",
89        }
90    }
91
92    /// Version prefix (everything before the version number).
93    const fn version_prefix(self) -> &'static str {
94        match self {
95            Self::Evidence => "ftui-evidence-v",
96            Self::RenderTrace => "render-trace-v",
97            Self::EventTrace => "event-trace-v",
98            Self::GoldenTrace => "golden-trace-v",
99            Self::Telemetry => "", // semver, handled separately
100            Self::MigrationIr => "migration-ir-v",
101        }
102    }
103
104    /// Human-readable name for display.
105    pub const fn as_str(self) -> &'static str {
106        match self {
107            Self::Evidence => "evidence",
108            Self::RenderTrace => "render_trace",
109            Self::EventTrace => "event_trace",
110            Self::GoldenTrace => "golden_trace",
111            Self::Telemetry => "telemetry",
112            Self::MigrationIr => "migration_ir",
113        }
114    }
115}
116
117impl fmt::Display for SchemaKind {
118    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119        f.write_str(self.as_str())
120    }
121}
122
123// ============================================================================
124// Compatibility Result
125// ============================================================================
126
127/// Outcome of a schema compatibility check.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum Compatibility {
130    /// Versions match exactly.
131    Exact,
132    /// Reader is newer than writer — forward compatible (reader can read older data).
133    Forward {
134        reader_version: u32,
135        writer_version: u32,
136    },
137    /// Older data lacks required semantics and needs an explicit migration.
138    MigrationRequired {
139        reader_version: u32,
140        writer_version: u32,
141    },
142    /// Writer is newer than reader — incompatible (needs migration).
143    Backward {
144        reader_version: u32,
145        writer_version: u32,
146    },
147    /// Version string doesn't match expected format for this schema kind.
148    Unknown { writer_version: String },
149}
150
151impl Compatibility {
152    /// Whether the reader can process data from the writer.
153    pub fn is_compatible(&self) -> bool {
154        matches!(self, Self::Exact | Self::Forward { .. })
155    }
156}
157
158impl fmt::Display for Compatibility {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::Exact => write!(f, "exact match"),
162            Self::Forward {
163                reader_version,
164                writer_version,
165            } => write!(
166                f,
167                "forward compatible (reader=v{reader_version}, writer=v{writer_version})"
168            ),
169            Self::MigrationRequired {
170                reader_version,
171                writer_version,
172            } => write!(
173                f,
174                "incompatible: migration required (reader=v{reader_version}, writer=v{writer_version})"
175            ),
176            Self::Backward {
177                reader_version,
178                writer_version,
179            } => write!(
180                f,
181                "incompatible: writer newer (reader=v{reader_version}, writer=v{writer_version})"
182            ),
183            Self::Unknown { writer_version } => {
184                write!(f, "unknown version format: {writer_version}")
185            }
186        }
187    }
188}
189
190// ============================================================================
191// Compatibility Check Result
192// ============================================================================
193
194/// Full result of a schema compatibility check, including metadata.
195#[derive(Debug, Clone)]
196pub struct CompatCheckResult {
197    /// Schema kind that was checked.
198    pub kind: SchemaKind,
199    /// Reader's version string.
200    pub reader_version: &'static str,
201    /// Writer's version string.
202    pub writer_version: String,
203    /// Compatibility outcome.
204    pub compatibility: Compatibility,
205}
206
207impl CompatCheckResult {
208    /// Whether this check passed (reader can process writer's data).
209    pub fn is_compatible(&self) -> bool {
210        self.compatibility.is_compatible()
211    }
212}
213
214impl fmt::Display for CompatCheckResult {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        write!(
217            f,
218            "{}: {} (reader={}, writer={})",
219            self.kind, self.compatibility, self.reader_version, self.writer_version,
220        )
221    }
222}
223
224// ============================================================================
225// Version Parsing
226// ============================================================================
227
228/// Parse a version number from a prefixed version string (e.g., "ftui-evidence-v2" → 2).
229fn parse_prefixed_version(version: &str, prefix: &str) -> Option<u32> {
230    version.strip_prefix(prefix)?.parse().ok()
231}
232
233/// Parse the major version from a semver string (e.g., "1.0.0" → 1).
234fn parse_semver_major(version: &str) -> Option<u32> {
235    version.split('.').next()?.parse().ok()
236}
237
238/// Parse the version number for a given schema kind.
239fn parse_version_number(kind: SchemaKind, version: &str) -> Option<u32> {
240    if kind == SchemaKind::Telemetry {
241        parse_semver_major(version)
242    } else {
243        parse_prefixed_version(version, kind.version_prefix())
244    }
245}
246
247// ============================================================================
248// Core Compatibility Check
249// ============================================================================
250
251/// Classify compatibility between a reader (current) and writer version without
252/// emitting tracing spans or metrics.
253///
254/// The reader version is always the current version for the given schema kind.
255/// The writer version is the version found in the data being read.
256pub fn classify_schema_compat(kind: SchemaKind, writer_version: &str) -> CompatCheckResult {
257    let reader_version = kind.current_version();
258
259    let compatibility = if writer_version == reader_version {
260        Compatibility::Exact
261    } else {
262        match (
263            parse_version_number(kind, reader_version),
264            parse_version_number(kind, writer_version),
265        ) {
266            (Some(rv), Some(wv)) if kind == SchemaKind::GoldenTrace && rv > wv => {
267                Compatibility::MigrationRequired {
268                    reader_version: rv,
269                    writer_version: wv,
270                }
271            }
272            // Golden traces require the exact schema identifier, matching the
273            // session parser. Numeric aliases such as v02 are not v2 schemas.
274            (Some(rv), Some(wv)) if kind == SchemaKind::GoldenTrace && rv == wv => {
275                Compatibility::Unknown {
276                    writer_version: writer_version.to_string(),
277                }
278            }
279            (Some(rv), Some(wv)) if rv > wv => Compatibility::Forward {
280                reader_version: rv,
281                writer_version: wv,
282            },
283            (Some(rv), Some(wv)) if rv == wv => Compatibility::Exact,
284            (Some(rv), Some(wv)) => Compatibility::Backward {
285                reader_version: rv,
286                writer_version: wv,
287            },
288            _ => Compatibility::Unknown {
289                writer_version: writer_version.to_string(),
290            },
291        }
292    };
293
294    CompatCheckResult {
295        kind,
296        reader_version,
297        writer_version: writer_version.to_string(),
298        compatibility,
299    }
300}
301
302/// Check compatibility between a reader (current) and writer version.
303///
304/// The reader version is always the current version for the given schema kind.
305/// The writer version is the version found in the data being read.
306///
307/// Emits a `trace.compat_check` tracing span and increments
308/// `trace_compat_failures_total` on incompatibility.
309pub fn check_schema_compat(kind: SchemaKind, writer_version: &str) -> CompatCheckResult {
310    let result = classify_schema_compat(kind, writer_version);
311    let compatible = result.is_compatible();
312
313    // Tracing span
314    #[cfg(feature = "tracing")]
315    {
316        use tracing::{error, info_span};
317
318        let span = info_span!(
319            "trace.compat_check",
320            schema_version = kind.current_version(),
321            reader_version = result.reader_version,
322            writer_version = writer_version,
323            compatible = compatible,
324        );
325        let _guard = span.enter();
326
327        if !compatible {
328            error!(
329                target: crate::telemetry_schema::TARGET_RUNTIME,
330                schema_kind = kind.as_str(),
331                reader_version = result.reader_version,
332                writer_version = writer_version,
333                "trace schema version incompatible"
334            );
335        }
336    }
337
338    // Metrics
339    if !compatible {
340        METRICS
341            .counter(BuiltinCounter::TraceCompatFailuresTotal)
342            .inc();
343    }
344
345    result
346}
347
348/// Convenience: check evidence schema compatibility.
349pub fn check_evidence_compat(writer_version: &str) -> CompatCheckResult {
350    check_schema_compat(SchemaKind::Evidence, writer_version)
351}
352
353/// Convenience: check render-trace schema compatibility.
354pub fn check_render_trace_compat(writer_version: &str) -> CompatCheckResult {
355    check_schema_compat(SchemaKind::RenderTrace, writer_version)
356}
357
358/// Convenience: check event-trace schema compatibility.
359pub fn check_event_trace_compat(writer_version: &str) -> CompatCheckResult {
360    check_schema_compat(SchemaKind::EventTrace, writer_version)
361}
362
363/// Convenience: check golden-trace schema compatibility.
364pub fn check_golden_trace_compat(writer_version: &str) -> CompatCheckResult {
365    check_schema_compat(SchemaKind::GoldenTrace, writer_version)
366}
367
368// ============================================================================
369// Compatibility Matrix
370// ============================================================================
371
372/// Entry in the compatibility matrix, pairing a schema kind with a
373/// writer version and expected outcome.
374#[derive(Debug, Clone)]
375pub struct MatrixEntry {
376    pub kind: SchemaKind,
377    pub writer_version: String,
378    pub expected_compatible: bool,
379}
380
381/// Run the full compatibility matrix and return all results.
382///
383/// This is the CI gate function: every entry must match its expected outcome.
384pub fn run_compatibility_matrix(entries: &[MatrixEntry]) -> Vec<(MatrixEntry, CompatCheckResult)> {
385    entries
386        .iter()
387        .map(|entry| {
388            let result = classify_schema_compat(entry.kind, &entry.writer_version);
389            (entry.clone(), result)
390        })
391        .collect()
392}
393
394/// Build the default compatibility matrix covering all schema kinds.
395///
396/// For each kind, tests:
397/// - Current version (exact match, compatible)
398/// - One version older (migration required for GoldenTrace, otherwise forward compatible)
399/// - One version newer (backward incompatible)
400/// - Garbage version string (unknown, incompatible)
401pub fn default_compatibility_matrix() -> Vec<MatrixEntry> {
402    let mut entries = Vec::new();
403
404    for kind in SchemaKind::ALL {
405        let current = kind.current_version();
406
407        // Exact match — always compatible
408        entries.push(MatrixEntry {
409            kind,
410            writer_version: current.to_string(),
411            expected_compatible: true,
412        });
413
414        // Garbage — always incompatible
415        entries.push(MatrixEntry {
416            kind,
417            writer_version: "not-a-version".to_string(),
418            expected_compatible: false,
419        });
420
421        if kind == SchemaKind::Telemetry {
422            // Semver: older major version is forward-compatible
423            entries.push(MatrixEntry {
424                kind,
425                writer_version: "0.9.0".to_string(),
426                expected_compatible: true,
427            });
428            // Semver: newer major version is backward-incompatible
429            entries.push(MatrixEntry {
430                kind,
431                writer_version: "2.0.0".to_string(),
432                expected_compatible: false,
433            });
434        } else {
435            // Prefixed: generate older and newer versions
436            let prefix = kind.version_prefix();
437            if let Some(current_num) = parse_version_number(kind, current) {
438                if current_num > 0 {
439                    entries.push(MatrixEntry {
440                        kind,
441                        writer_version: format!("{prefix}{}", current_num - 1),
442                        expected_compatible: kind != SchemaKind::GoldenTrace,
443                    });
444                }
445                entries.push(MatrixEntry {
446                    kind,
447                    writer_version: format!("{prefix}{}", current_num + 1),
448                    expected_compatible: false,
449                });
450            }
451        }
452    }
453
454    entries
455}
456
457// ============================================================================
458// Tests
459// ============================================================================
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    static COMPAT_METRICS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
466
467    fn compat_metrics_guard() -> std::sync::MutexGuard<'static, ()> {
468        COMPAT_METRICS_LOCK
469            .lock()
470            .unwrap_or_else(std::sync::PoisonError::into_inner)
471    }
472
473    #[test]
474    fn exact_match_all_kinds() {
475        for kind in SchemaKind::ALL {
476            let result = classify_schema_compat(kind, kind.current_version());
477            assert_eq!(result.compatibility, Compatibility::Exact, "{kind}");
478            assert!(result.is_compatible(), "{kind}");
479        }
480    }
481
482    #[test]
483    fn forward_compat_evidence() {
484        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v1");
485        assert!(
486            matches!(
487                result.compatibility,
488                Compatibility::Forward {
489                    reader_version: 2,
490                    writer_version: 1
491                }
492            ),
493            "got {:?}",
494            result.compatibility
495        );
496        assert!(result.is_compatible());
497    }
498
499    #[test]
500    fn backward_incompat_evidence() {
501        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v3");
502        assert!(
503            matches!(
504                result.compatibility,
505                Compatibility::Backward {
506                    reader_version: 2,
507                    writer_version: 3
508                }
509            ),
510            "got {:?}",
511            result.compatibility
512        );
513        assert!(!result.is_compatible());
514    }
515
516    #[test]
517    fn unknown_version_format() {
518        let result = classify_schema_compat(SchemaKind::Evidence, "garbage-string");
519        assert!(
520            matches!(result.compatibility, Compatibility::Unknown { .. }),
521            "got {:?}",
522            result.compatibility
523        );
524        assert!(!result.is_compatible());
525    }
526
527    #[test]
528    fn forward_compat_telemetry_semver() {
529        let result = classify_schema_compat(SchemaKind::Telemetry, "0.9.0");
530        assert!(
531            matches!(
532                result.compatibility,
533                Compatibility::Forward {
534                    reader_version: 1,
535                    writer_version: 0
536                }
537            ),
538            "got {:?}",
539            result.compatibility
540        );
541        assert!(result.is_compatible());
542    }
543
544    #[test]
545    fn backward_incompat_telemetry_semver() {
546        let result = classify_schema_compat(SchemaKind::Telemetry, "2.0.0");
547        assert!(
548            matches!(
549                result.compatibility,
550                Compatibility::Backward {
551                    reader_version: 1,
552                    writer_version: 2
553                }
554            ),
555            "got {:?}",
556            result.compatibility
557        );
558        assert!(!result.is_compatible());
559    }
560
561    #[test]
562    fn all_kinds_have_current_version() {
563        for kind in SchemaKind::ALL {
564            let v = kind.current_version();
565            assert!(!v.is_empty(), "{kind} has empty version");
566        }
567    }
568
569    #[test]
570    fn all_kinds_have_unique_versions() {
571        let mut versions = std::collections::HashSet::new();
572        for kind in SchemaKind::ALL {
573            assert!(
574                versions.insert(kind.current_version()),
575                "duplicate version: {}",
576                kind.current_version()
577            );
578        }
579    }
580
581    #[test]
582    fn default_matrix_covers_all_kinds() {
583        let matrix = default_compatibility_matrix();
584        for kind in SchemaKind::ALL {
585            let count = matrix.iter().filter(|e| e.kind == kind).count();
586            assert!(
587                count >= 3,
588                "{kind} has only {count} matrix entries, expected >=3"
589            );
590        }
591    }
592
593    #[test]
594    fn default_matrix_all_pass() {
595        let matrix = default_compatibility_matrix();
596        let results = run_compatibility_matrix(&matrix);
597        for (entry, result) in &results {
598            assert_eq!(
599                result.is_compatible(),
600                entry.expected_compatible,
601                "{}: writer={}, expected_compatible={}, got {:?}",
602                entry.kind,
603                entry.writer_version,
604                entry.expected_compatible,
605                result.compatibility,
606            );
607        }
608    }
609
610    #[test]
611    fn compat_failures_counter_increments() {
612        let _guard = compat_metrics_guard();
613
614        let before = METRICS
615            .counter(BuiltinCounter::TraceCompatFailuresTotal)
616            .get();
617        let _ = check_schema_compat(SchemaKind::Evidence, "ftui-evidence-v99");
618        let after = METRICS
619            .counter(BuiltinCounter::TraceCompatFailuresTotal)
620            .get();
621        assert!(
622            after > before,
623            "counter should increment on incompatibility"
624        );
625    }
626
627    #[test]
628    fn exact_match_does_not_increment_counter() {
629        let _guard = compat_metrics_guard();
630
631        let before = METRICS
632            .counter(BuiltinCounter::TraceCompatFailuresTotal)
633            .get();
634        let _ = check_schema_compat(SchemaKind::Evidence, "ftui-evidence-v2");
635        let after = METRICS
636            .counter(BuiltinCounter::TraceCompatFailuresTotal)
637            .get();
638        assert_eq!(after, before, "counter should not increment on exact match");
639    }
640
641    #[test]
642    fn display_impls() {
643        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v1");
644        let s = result.to_string();
645        assert!(s.contains("evidence"), "{s}");
646        assert!(s.contains("forward compatible"), "{s}");
647
648        let result2 = classify_schema_compat(SchemaKind::RenderTrace, "render-trace-v99");
649        let s2 = result2.to_string();
650        assert!(s2.contains("incompatible"), "{s2}");
651    }
652
653    #[test]
654    fn schema_kind_display() {
655        assert_eq!(SchemaKind::Evidence.to_string(), "evidence");
656        assert_eq!(SchemaKind::RenderTrace.to_string(), "render_trace");
657        assert_eq!(SchemaKind::Telemetry.to_string(), "telemetry");
658    }
659
660    #[test]
661    fn render_trace_forward_compat() {
662        let result = classify_schema_compat(SchemaKind::RenderTrace, "render-trace-v1");
663        assert!(result.is_compatible());
664        assert!(matches!(
665            result.compatibility,
666            Compatibility::Forward {
667                reader_version: 2,
668                writer_version: 1
669            }
670        ));
671    }
672
673    #[test]
674    fn event_trace_exact() {
675        let result = classify_schema_compat(SchemaKind::EventTrace, "event-trace-v1");
676        assert_eq!(result.compatibility, Compatibility::Exact);
677    }
678
679    #[test]
680    fn golden_trace_v2_exact() {
681        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v2");
682        assert_eq!(result.reader_version, "golden-trace-v2");
683        assert_eq!(result.compatibility, Compatibility::Exact);
684        assert!(result.is_compatible());
685    }
686
687    #[test]
688    fn golden_trace_v1_requires_migration() {
689        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v1");
690        assert_eq!(
691            result.compatibility,
692            Compatibility::MigrationRequired {
693                reader_version: 2,
694                writer_version: 1,
695            }
696        );
697        assert!(!result.is_compatible());
698        assert_eq!(
699            result.compatibility.to_string(),
700            "incompatible: migration required (reader=v2, writer=v1)"
701        );
702    }
703
704    #[test]
705    fn golden_trace_backward_incompat() {
706        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v3");
707        assert_eq!(
708            result.compatibility,
709            Compatibility::Backward {
710                reader_version: 2,
711                writer_version: 3,
712            }
713        );
714        assert!(!result.is_compatible());
715    }
716
717    #[test]
718    fn golden_trace_noncanonical_version_is_not_exact() {
719        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v02");
720        assert_eq!(
721            result.compatibility,
722            Compatibility::Unknown {
723                writer_version: "golden-trace-v02".to_string(),
724            }
725        );
726        assert!(!result.is_compatible());
727    }
728
729    #[test]
730    fn migration_ir_exact() {
731        let result = classify_schema_compat(SchemaKind::MigrationIr, "migration-ir-v1");
732        assert_eq!(result.compatibility, Compatibility::Exact);
733    }
734
735    #[test]
736    fn evidence_v0_forward() {
737        // Evidence reader is v2, writer is v0 → forward compatible
738        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v0");
739        assert!(result.is_compatible());
740        assert!(matches!(
741            result.compatibility,
742            Compatibility::Forward {
743                reader_version: 2,
744                writer_version: 0
745            }
746        ));
747    }
748}