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                schema_kind = kind.as_str(),
330                reader_version = result.reader_version,
331                writer_version = writer_version,
332                "trace schema version incompatible"
333            );
334        }
335    }
336
337    // Metrics
338    if !compatible {
339        METRICS
340            .counter(BuiltinCounter::TraceCompatFailuresTotal)
341            .inc();
342    }
343
344    result
345}
346
347/// Convenience: check evidence schema compatibility.
348pub fn check_evidence_compat(writer_version: &str) -> CompatCheckResult {
349    check_schema_compat(SchemaKind::Evidence, writer_version)
350}
351
352/// Convenience: check render-trace schema compatibility.
353pub fn check_render_trace_compat(writer_version: &str) -> CompatCheckResult {
354    check_schema_compat(SchemaKind::RenderTrace, writer_version)
355}
356
357/// Convenience: check event-trace schema compatibility.
358pub fn check_event_trace_compat(writer_version: &str) -> CompatCheckResult {
359    check_schema_compat(SchemaKind::EventTrace, writer_version)
360}
361
362/// Convenience: check golden-trace schema compatibility.
363pub fn check_golden_trace_compat(writer_version: &str) -> CompatCheckResult {
364    check_schema_compat(SchemaKind::GoldenTrace, writer_version)
365}
366
367// ============================================================================
368// Compatibility Matrix
369// ============================================================================
370
371/// Entry in the compatibility matrix, pairing a schema kind with a
372/// writer version and expected outcome.
373#[derive(Debug, Clone)]
374pub struct MatrixEntry {
375    pub kind: SchemaKind,
376    pub writer_version: String,
377    pub expected_compatible: bool,
378}
379
380/// Run the full compatibility matrix and return all results.
381///
382/// This is the CI gate function: every entry must match its expected outcome.
383pub fn run_compatibility_matrix(entries: &[MatrixEntry]) -> Vec<(MatrixEntry, CompatCheckResult)> {
384    entries
385        .iter()
386        .map(|entry| {
387            let result = classify_schema_compat(entry.kind, &entry.writer_version);
388            (entry.clone(), result)
389        })
390        .collect()
391}
392
393/// Build the default compatibility matrix covering all schema kinds.
394///
395/// For each kind, tests:
396/// - Current version (exact match, compatible)
397/// - One version older (migration required for GoldenTrace, otherwise forward compatible)
398/// - One version newer (backward incompatible)
399/// - Garbage version string (unknown, incompatible)
400pub fn default_compatibility_matrix() -> Vec<MatrixEntry> {
401    let mut entries = Vec::new();
402
403    for kind in SchemaKind::ALL {
404        let current = kind.current_version();
405
406        // Exact match — always compatible
407        entries.push(MatrixEntry {
408            kind,
409            writer_version: current.to_string(),
410            expected_compatible: true,
411        });
412
413        // Garbage — always incompatible
414        entries.push(MatrixEntry {
415            kind,
416            writer_version: "not-a-version".to_string(),
417            expected_compatible: false,
418        });
419
420        if kind == SchemaKind::Telemetry {
421            // Semver: older major version is forward-compatible
422            entries.push(MatrixEntry {
423                kind,
424                writer_version: "0.9.0".to_string(),
425                expected_compatible: true,
426            });
427            // Semver: newer major version is backward-incompatible
428            entries.push(MatrixEntry {
429                kind,
430                writer_version: "2.0.0".to_string(),
431                expected_compatible: false,
432            });
433        } else {
434            // Prefixed: generate older and newer versions
435            let prefix = kind.version_prefix();
436            if let Some(current_num) = parse_version_number(kind, current) {
437                if current_num > 0 {
438                    entries.push(MatrixEntry {
439                        kind,
440                        writer_version: format!("{prefix}{}", current_num - 1),
441                        expected_compatible: kind != SchemaKind::GoldenTrace,
442                    });
443                }
444                entries.push(MatrixEntry {
445                    kind,
446                    writer_version: format!("{prefix}{}", current_num + 1),
447                    expected_compatible: false,
448                });
449            }
450        }
451    }
452
453    entries
454}
455
456// ============================================================================
457// Tests
458// ============================================================================
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463
464    static COMPAT_METRICS_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
465
466    fn compat_metrics_guard() -> std::sync::MutexGuard<'static, ()> {
467        COMPAT_METRICS_LOCK
468            .lock()
469            .unwrap_or_else(std::sync::PoisonError::into_inner)
470    }
471
472    #[test]
473    fn exact_match_all_kinds() {
474        for kind in SchemaKind::ALL {
475            let result = classify_schema_compat(kind, kind.current_version());
476            assert_eq!(result.compatibility, Compatibility::Exact, "{kind}");
477            assert!(result.is_compatible(), "{kind}");
478        }
479    }
480
481    #[test]
482    fn forward_compat_evidence() {
483        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v1");
484        assert!(
485            matches!(
486                result.compatibility,
487                Compatibility::Forward {
488                    reader_version: 2,
489                    writer_version: 1
490                }
491            ),
492            "got {:?}",
493            result.compatibility
494        );
495        assert!(result.is_compatible());
496    }
497
498    #[test]
499    fn backward_incompat_evidence() {
500        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v3");
501        assert!(
502            matches!(
503                result.compatibility,
504                Compatibility::Backward {
505                    reader_version: 2,
506                    writer_version: 3
507                }
508            ),
509            "got {:?}",
510            result.compatibility
511        );
512        assert!(!result.is_compatible());
513    }
514
515    #[test]
516    fn unknown_version_format() {
517        let result = classify_schema_compat(SchemaKind::Evidence, "garbage-string");
518        assert!(
519            matches!(result.compatibility, Compatibility::Unknown { .. }),
520            "got {:?}",
521            result.compatibility
522        );
523        assert!(!result.is_compatible());
524    }
525
526    #[test]
527    fn forward_compat_telemetry_semver() {
528        let result = classify_schema_compat(SchemaKind::Telemetry, "0.9.0");
529        assert!(
530            matches!(
531                result.compatibility,
532                Compatibility::Forward {
533                    reader_version: 1,
534                    writer_version: 0
535                }
536            ),
537            "got {:?}",
538            result.compatibility
539        );
540        assert!(result.is_compatible());
541    }
542
543    #[test]
544    fn backward_incompat_telemetry_semver() {
545        let result = classify_schema_compat(SchemaKind::Telemetry, "2.0.0");
546        assert!(
547            matches!(
548                result.compatibility,
549                Compatibility::Backward {
550                    reader_version: 1,
551                    writer_version: 2
552                }
553            ),
554            "got {:?}",
555            result.compatibility
556        );
557        assert!(!result.is_compatible());
558    }
559
560    #[test]
561    fn all_kinds_have_current_version() {
562        for kind in SchemaKind::ALL {
563            let v = kind.current_version();
564            assert!(!v.is_empty(), "{kind} has empty version");
565        }
566    }
567
568    #[test]
569    fn all_kinds_have_unique_versions() {
570        let mut versions = std::collections::HashSet::new();
571        for kind in SchemaKind::ALL {
572            assert!(
573                versions.insert(kind.current_version()),
574                "duplicate version: {}",
575                kind.current_version()
576            );
577        }
578    }
579
580    #[test]
581    fn default_matrix_covers_all_kinds() {
582        let matrix = default_compatibility_matrix();
583        for kind in SchemaKind::ALL {
584            let count = matrix.iter().filter(|e| e.kind == kind).count();
585            assert!(
586                count >= 3,
587                "{kind} has only {count} matrix entries, expected >=3"
588            );
589        }
590    }
591
592    #[test]
593    fn default_matrix_all_pass() {
594        let matrix = default_compatibility_matrix();
595        let results = run_compatibility_matrix(&matrix);
596        for (entry, result) in &results {
597            assert_eq!(
598                result.is_compatible(),
599                entry.expected_compatible,
600                "{}: writer={}, expected_compatible={}, got {:?}",
601                entry.kind,
602                entry.writer_version,
603                entry.expected_compatible,
604                result.compatibility,
605            );
606        }
607    }
608
609    #[test]
610    fn compat_failures_counter_increments() {
611        let _guard = compat_metrics_guard();
612
613        let before = METRICS
614            .counter(BuiltinCounter::TraceCompatFailuresTotal)
615            .get();
616        let _ = check_schema_compat(SchemaKind::Evidence, "ftui-evidence-v99");
617        let after = METRICS
618            .counter(BuiltinCounter::TraceCompatFailuresTotal)
619            .get();
620        assert!(
621            after > before,
622            "counter should increment on incompatibility"
623        );
624    }
625
626    #[test]
627    fn exact_match_does_not_increment_counter() {
628        let _guard = compat_metrics_guard();
629
630        let before = METRICS
631            .counter(BuiltinCounter::TraceCompatFailuresTotal)
632            .get();
633        let _ = check_schema_compat(SchemaKind::Evidence, "ftui-evidence-v2");
634        let after = METRICS
635            .counter(BuiltinCounter::TraceCompatFailuresTotal)
636            .get();
637        assert_eq!(after, before, "counter should not increment on exact match");
638    }
639
640    #[test]
641    fn display_impls() {
642        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v1");
643        let s = result.to_string();
644        assert!(s.contains("evidence"), "{s}");
645        assert!(s.contains("forward compatible"), "{s}");
646
647        let result2 = classify_schema_compat(SchemaKind::RenderTrace, "render-trace-v99");
648        let s2 = result2.to_string();
649        assert!(s2.contains("incompatible"), "{s2}");
650    }
651
652    #[test]
653    fn schema_kind_display() {
654        assert_eq!(SchemaKind::Evidence.to_string(), "evidence");
655        assert_eq!(SchemaKind::RenderTrace.to_string(), "render_trace");
656        assert_eq!(SchemaKind::Telemetry.to_string(), "telemetry");
657    }
658
659    #[test]
660    fn render_trace_forward_compat() {
661        let result = classify_schema_compat(SchemaKind::RenderTrace, "render-trace-v1");
662        assert!(result.is_compatible());
663        assert!(matches!(
664            result.compatibility,
665            Compatibility::Forward {
666                reader_version: 2,
667                writer_version: 1
668            }
669        ));
670    }
671
672    #[test]
673    fn event_trace_exact() {
674        let result = classify_schema_compat(SchemaKind::EventTrace, "event-trace-v1");
675        assert_eq!(result.compatibility, Compatibility::Exact);
676    }
677
678    #[test]
679    fn golden_trace_v2_exact() {
680        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v2");
681        assert_eq!(result.reader_version, "golden-trace-v2");
682        assert_eq!(result.compatibility, Compatibility::Exact);
683        assert!(result.is_compatible());
684    }
685
686    #[test]
687    fn golden_trace_v1_requires_migration() {
688        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v1");
689        assert_eq!(
690            result.compatibility,
691            Compatibility::MigrationRequired {
692                reader_version: 2,
693                writer_version: 1,
694            }
695        );
696        assert!(!result.is_compatible());
697        assert_eq!(
698            result.compatibility.to_string(),
699            "incompatible: migration required (reader=v2, writer=v1)"
700        );
701    }
702
703    #[test]
704    fn golden_trace_backward_incompat() {
705        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v3");
706        assert_eq!(
707            result.compatibility,
708            Compatibility::Backward {
709                reader_version: 2,
710                writer_version: 3,
711            }
712        );
713        assert!(!result.is_compatible());
714    }
715
716    #[test]
717    fn golden_trace_noncanonical_version_is_not_exact() {
718        let result = classify_schema_compat(SchemaKind::GoldenTrace, "golden-trace-v02");
719        assert_eq!(
720            result.compatibility,
721            Compatibility::Unknown {
722                writer_version: "golden-trace-v02".to_string(),
723            }
724        );
725        assert!(!result.is_compatible());
726    }
727
728    #[test]
729    fn migration_ir_exact() {
730        let result = classify_schema_compat(SchemaKind::MigrationIr, "migration-ir-v1");
731        assert_eq!(result.compatibility, Compatibility::Exact);
732    }
733
734    #[test]
735    fn evidence_v0_forward() {
736        // Evidence reader is v2, writer is v0 → forward compatible
737        let result = classify_schema_compat(SchemaKind::Evidence, "ftui-evidence-v0");
738        assert!(result.is_compatible());
739        assert!(matches!(
740            result.compatibility,
741            Compatibility::Forward {
742                reader_version: 2,
743                writer_version: 0
744            }
745        ));
746    }
747}