Skip to main content

allsource_core/application/services/
schema_evolution.rs

1//! Autonomous schema evolution
2//!
3//! Automatically detects schema changes from ingested events and manages
4//! schema evolution without manual intervention. Works alongside the existing
5//! `SchemaRegistry` to:
6//!
7//! 1. **Infer schemas** from event payloads on first ingestion of a new event type
8//! 2. **Detect drift** when new events have fields not in the registered schema
9//! 3. **Auto-register** backward-compatible schema versions (new optional fields)
10//! 4. **Flag breaking changes** that require manual review (type changes, removed required fields)
11//!
12//! ## How it works
13//!
14//! On each event ingestion, the `SchemaEvolutionManager` compares the event's
15//! payload structure against the latest registered schema for that event type.
16//! If differences are detected:
17//! - New optional fields → auto-registered as a new schema version
18//! - Type changes or missing required fields → flagged as breaking, not auto-registered
19//!
20//! ## Limitations
21//!
22//! - Only analyzes top-level and one level of nested fields
23//! - Type inference is basic: string, number, boolean, array, object, null
24//! - Does not handle polymorphic types (field sometimes string, sometimes number)
25//! - No automatic data migration — schemas describe shape, don't transform data
26
27use crate::infrastructure::memory::ledger::{Owner, Tally};
28use chrono::{DateTime, Utc};
29use dashmap::DashMap;
30use serde::{Deserialize, Serialize};
31use serde_json::Value as JsonValue;
32use std::collections::{BTreeMap, BTreeSet};
33use uuid::Uuid;
34
35/// Schema evolution event types
36#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
37pub enum EvolutionAction {
38    /// Schema was inferred from first event of this type
39    Inferred,
40    /// Backward-compatible change auto-registered
41    AutoEvolved,
42    /// Breaking change detected, requires manual review
43    BreakingChangeDetected,
44}
45
46/// A record of a schema evolution event
47#[derive(Debug, Clone, Serialize)]
48pub struct EvolutionRecord {
49    pub id: Uuid,
50    pub event_type: String,
51    pub action: EvolutionAction,
52    pub from_version: Option<u32>,
53    pub to_version: Option<u32>,
54    pub added_fields: Vec<String>,
55    pub removed_fields: Vec<String>,
56    pub type_changes: Vec<FieldTypeChange>,
57    pub timestamp: DateTime<Utc>,
58}
59
60/// A field type change (potential breaking change)
61#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
62pub struct FieldTypeChange {
63    pub field: String,
64    pub old_type: String,
65    pub new_type: String,
66}
67
68/// Inferred JSON type for a field
69#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
70pub enum InferredType {
71    String,
72    Number,
73    Boolean,
74    Array,
75    Object,
76    Null,
77}
78
79impl std::fmt::Display for InferredType {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        match self {
82            InferredType::String => write!(f, "string"),
83            InferredType::Number => write!(f, "number"),
84            InferredType::Boolean => write!(f, "boolean"),
85            InferredType::Array => write!(f, "array"),
86            InferredType::Object => write!(f, "object"),
87            InferredType::Null => write!(f, "null"),
88        }
89    }
90}
91
92/// Infer the type of a JSON value
93fn infer_type(value: &JsonValue) -> InferredType {
94    match value {
95        JsonValue::Null => InferredType::Null,
96        JsonValue::Bool(_) => InferredType::Boolean,
97        JsonValue::Number(_) => InferredType::Number,
98        JsonValue::String(_) => InferredType::String,
99        JsonValue::Array(_) => InferredType::Array,
100        JsonValue::Object(_) => InferredType::Object,
101    }
102}
103
104/// An inferred field schema
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct FieldSchema {
107    pub name: String,
108    pub inferred_type: InferredType,
109    pub nullable: bool,
110    /// Nested fields (only if type is Object)
111    pub nested: BTreeMap<String, FieldSchema>,
112}
113
114/// Schema shape inferred from a payload
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct InferredSchema {
117    pub fields: BTreeMap<String, FieldSchema>,
118}
119
120/// Diff between two schemas
121#[derive(Debug, Clone, Serialize)]
122pub struct SchemaDiff {
123    pub added_fields: Vec<String>,
124    pub removed_fields: Vec<String>,
125    pub type_changes: Vec<FieldTypeChange>,
126    pub is_backward_compatible: bool,
127}
128
129/// Infer a schema shape from a JSON payload
130pub fn infer_schema(payload: &JsonValue) -> InferredSchema {
131    let mut fields = BTreeMap::new();
132    if let Some(obj) = payload.as_object() {
133        for (key, value) in obj {
134            let mut nested = BTreeMap::new();
135            if let Some(inner_obj) = value.as_object() {
136                for (nk, nv) in inner_obj {
137                    nested.insert(
138                        nk.clone(),
139                        FieldSchema {
140                            name: nk.clone(),
141                            inferred_type: infer_type(nv),
142                            nullable: nv.is_null(),
143                            nested: BTreeMap::new(),
144                        },
145                    );
146                }
147            }
148            fields.insert(
149                key.clone(),
150                FieldSchema {
151                    name: key.clone(),
152                    inferred_type: infer_type(value),
153                    nullable: value.is_null(),
154                    nested,
155                },
156            );
157        }
158    }
159    InferredSchema { fields }
160}
161
162/// Convert an inferred schema to a JSON Schema document
163pub fn to_json_schema(schema: &InferredSchema) -> JsonValue {
164    let mut properties = serde_json::Map::new();
165    let mut required = Vec::new();
166
167    for (name, field) in &schema.fields {
168        let type_str = match field.inferred_type {
169            InferredType::String => "string",
170            InferredType::Number => "number",
171            InferredType::Boolean => "boolean",
172            InferredType::Array => "array",
173            InferredType::Object => "object",
174            InferredType::Null => "null",
175        };
176
177        let mut prop = serde_json::json!({"type": type_str});
178
179        // Add nested properties for objects
180        if field.inferred_type == InferredType::Object && !field.nested.is_empty() {
181            let nested_schema = InferredSchema {
182                fields: field.nested.clone(),
183            };
184            let nested_json = to_json_schema(&nested_schema);
185            if let Some(np) = nested_json.get("properties") {
186                prop["properties"] = np.clone();
187            }
188        }
189
190        properties.insert(name.clone(), prop);
191        if !field.nullable {
192            required.push(JsonValue::String(name.clone()));
193        }
194    }
195
196    serde_json::json!({
197        "type": "object",
198        "properties": properties,
199        "required": required,
200    })
201}
202
203/// Compute the diff between an existing schema and a new payload's inferred schema
204pub fn compute_diff(existing: &InferredSchema, new: &InferredSchema) -> SchemaDiff {
205    let existing_keys: BTreeSet<&String> = existing.fields.keys().collect();
206    let new_keys: BTreeSet<&String> = new.fields.keys().collect();
207
208    let added: Vec<String> = new_keys
209        .difference(&existing_keys)
210        .map(|k| (*k).clone())
211        .collect();
212    let removed: Vec<String> = existing_keys
213        .difference(&new_keys)
214        .map(|k| (*k).clone())
215        .collect();
216
217    let mut type_changes = Vec::new();
218    for key in existing_keys.intersection(&new_keys) {
219        let old_field = &existing.fields[*key];
220        let new_field = &new.fields[*key];
221        if old_field.inferred_type != new_field.inferred_type
222            && old_field.inferred_type != InferredType::Null
223            && new_field.inferred_type != InferredType::Null
224        {
225            type_changes.push(FieldTypeChange {
226                field: (*key).clone(),
227                old_type: old_field.inferred_type.to_string(),
228                new_type: new_field.inferred_type.to_string(),
229            });
230        }
231    }
232
233    // Backward compatible = no type changes, no removed required fields
234    let removed_required = removed
235        .iter()
236        .any(|r| existing.fields.get(r).is_some_and(|f| !f.nullable));
237
238    let is_backward_compatible = type_changes.is_empty() && !removed_required;
239
240    SchemaDiff {
241        added_fields: added,
242        removed_fields: removed,
243        type_changes,
244        is_backward_compatible,
245    }
246}
247
248/// Schema evolution manager — tracks inferred schemas and evolution history
249pub struct SchemaEvolutionManager {
250    /// Latest inferred schema per event type
251    schemas: DashMap<String, InferredSchema>,
252    /// Evolution history
253    history: DashMap<String, Vec<EvolutionRecord>>,
254    /// Version counter per event type
255    versions: DashMap<String, u32>,
256    history_bytes: Tally,
257}
258
259impl Default for SchemaEvolutionManager {
260    fn default() -> Self {
261        Self::new()
262    }
263}
264
265/// Heap one evolution record holds beyond its slot: its event type and the
266/// field names it lists.
267fn record_owned_bytes(record: &EvolutionRecord) -> u64 {
268    (record.event_type.len()
269        + record.added_fields.iter().map(String::len).sum::<usize>()
270        + record.removed_fields.iter().map(String::len).sum::<usize>()) as u64
271}
272
273impl SchemaEvolutionManager {
274    pub fn new() -> Self {
275        Self {
276            schemas: DashMap::new(),
277            history: DashMap::new(),
278            versions: DashMap::new(),
279            history_bytes: Tally::new(Owner::SchemaEvolution),
280        }
281    }
282
283    fn push_history(&self, record: EvolutionRecord) {
284        self.history_bytes
285            .add(std::mem::size_of::<EvolutionRecord>() as u64 + record_owned_bytes(&record));
286        self.history
287            .entry(record.event_type.clone())
288            .or_default()
289            .push(record);
290    }
291
292    /// Analyze an event and evolve the schema if needed
293    ///
294    /// Returns the evolution action taken (if any)
295    pub fn analyze_event(&self, event_type: &str, payload: &JsonValue) -> Option<EvolutionAction> {
296        let new_schema = infer_schema(payload);
297
298        if !self.schemas.contains_key(event_type) {
299            // First event of this type — infer and register
300            self.schemas.insert(event_type.to_string(), new_schema);
301            self.versions.insert(event_type.to_string(), 1);
302            self.push_history(EvolutionRecord {
303                id: Uuid::new_v4(),
304                event_type: event_type.to_string(),
305                action: EvolutionAction::Inferred,
306                from_version: None,
307                to_version: Some(1),
308                added_fields: vec![],
309                removed_fields: vec![],
310                type_changes: vec![],
311                timestamp: Utc::now(),
312            });
313            return Some(EvolutionAction::Inferred);
314        }
315
316        // Compare with existing schema
317        let existing = self.schemas.get(event_type).unwrap().clone();
318        let diff = compute_diff(&existing, &new_schema);
319
320        // No changes
321        if diff.added_fields.is_empty()
322            && diff.removed_fields.is_empty()
323            && diff.type_changes.is_empty()
324        {
325            return None;
326        }
327
328        let current_version = *self.versions.get(event_type).unwrap();
329
330        if diff.is_backward_compatible {
331            // Auto-evolve: merge new fields into existing schema
332            let mut merged = existing;
333            for (key, field) in new_schema.fields {
334                merged.fields.entry(key).or_insert(FieldSchema {
335                    nullable: true, // New fields are optional
336                    ..field
337                });
338            }
339
340            let new_version = current_version + 1;
341            self.schemas.insert(event_type.to_string(), merged);
342            self.versions.insert(event_type.to_string(), new_version);
343            self.push_history(EvolutionRecord {
344                id: Uuid::new_v4(),
345                event_type: event_type.to_string(),
346                action: EvolutionAction::AutoEvolved,
347                from_version: Some(current_version),
348                to_version: Some(new_version),
349                added_fields: diff.added_fields,
350                removed_fields: vec![],
351                type_changes: vec![],
352                timestamp: Utc::now(),
353            });
354            Some(EvolutionAction::AutoEvolved)
355        } else {
356            // Breaking change — record but don't auto-evolve
357            self.push_history(EvolutionRecord {
358                id: Uuid::new_v4(),
359                event_type: event_type.to_string(),
360                action: EvolutionAction::BreakingChangeDetected,
361                from_version: Some(current_version),
362                to_version: None,
363                added_fields: diff.added_fields,
364                removed_fields: diff.removed_fields,
365                type_changes: diff.type_changes,
366                timestamp: Utc::now(),
367            });
368            Some(EvolutionAction::BreakingChangeDetected)
369        }
370    }
371
372    /// Get the current inferred schema for an event type
373    pub fn get_schema(&self, event_type: &str) -> Option<InferredSchema> {
374        self.schemas.get(event_type).map(|s| s.clone())
375    }
376
377    /// Get the evolution history for an event type
378    pub fn get_history(&self, event_type: &str) -> Vec<EvolutionRecord> {
379        self.history
380            .get(event_type)
381            .map(|h| h.clone())
382            .unwrap_or_default()
383    }
384
385    /// Get all tracked event types
386    pub fn list_event_types(&self) -> Vec<String> {
387        self.schemas.iter().map(|e| e.key().clone()).collect()
388    }
389
390    /// Get the current version for an event type
391    pub fn get_version(&self, event_type: &str) -> Option<u32> {
392        self.versions.get(event_type).map(|v| *v)
393    }
394
395    /// Statistics
396    pub fn stats(&self) -> SchemaEvolutionStats {
397        let total_evolutions: usize = self.history.iter().map(|h| h.value().len()).sum();
398        let breaking_changes: usize = self
399            .history
400            .iter()
401            .map(|h| {
402                h.value()
403                    .iter()
404                    .filter(|r| r.action == EvolutionAction::BreakingChangeDetected)
405                    .count()
406            })
407            .sum();
408        SchemaEvolutionStats {
409            tracked_event_types: self.schemas.len(),
410            total_evolutions,
411            breaking_changes,
412        }
413    }
414}
415
416/// Schema evolution statistics
417#[derive(Debug, Clone, Serialize)]
418pub struct SchemaEvolutionStats {
419    pub tracked_event_types: usize,
420    pub total_evolutions: usize,
421    pub breaking_changes: usize,
422}
423
424#[cfg(test)]
425mod tests {
426    use super::*;
427
428    #[test]
429    fn test_infer_schema_basic() {
430        let payload = serde_json::json!({"name": "Alice", "age": 30, "active": true});
431        let schema = infer_schema(&payload);
432        assert_eq!(schema.fields.len(), 3);
433        assert_eq!(schema.fields["name"].inferred_type, InferredType::String);
434        assert_eq!(schema.fields["age"].inferred_type, InferredType::Number);
435        assert_eq!(schema.fields["active"].inferred_type, InferredType::Boolean);
436    }
437
438    #[test]
439    fn test_infer_schema_nested() {
440        let payload = serde_json::json!({"address": {"city": "NYC", "zip": 10001}});
441        let schema = infer_schema(&payload);
442        let addr = &schema.fields["address"];
443        assert_eq!(addr.inferred_type, InferredType::Object);
444        assert_eq!(addr.nested.len(), 2);
445        assert_eq!(addr.nested["city"].inferred_type, InferredType::String);
446    }
447
448    #[test]
449    fn test_to_json_schema() {
450        let payload = serde_json::json!({"name": "Alice", "age": 30});
451        let schema = infer_schema(&payload);
452        let json_schema = to_json_schema(&schema);
453        assert_eq!(json_schema["type"], "object");
454        assert!(json_schema["properties"]["name"].is_object());
455        assert_eq!(json_schema["properties"]["name"]["type"], "string");
456    }
457
458    #[test]
459    fn test_compute_diff_no_changes() {
460        let payload = serde_json::json!({"name": "Alice"});
461        let schema = infer_schema(&payload);
462        let diff = compute_diff(&schema, &schema);
463        assert!(diff.added_fields.is_empty());
464        assert!(diff.removed_fields.is_empty());
465        assert!(diff.type_changes.is_empty());
466        assert!(diff.is_backward_compatible);
467    }
468
469    #[test]
470    fn test_compute_diff_added_field() {
471        let old = infer_schema(&serde_json::json!({"name": "Alice"}));
472        let new = infer_schema(&serde_json::json!({"name": "Alice", "email": "a@b.com"}));
473        let diff = compute_diff(&old, &new);
474        assert_eq!(diff.added_fields, vec!["email"]);
475        assert!(diff.is_backward_compatible);
476    }
477
478    #[test]
479    fn test_compute_diff_type_change() {
480        let old = infer_schema(&serde_json::json!({"age": 30}));
481        let new = infer_schema(&serde_json::json!({"age": "thirty"}));
482        let diff = compute_diff(&old, &new);
483        assert_eq!(diff.type_changes.len(), 1);
484        assert_eq!(diff.type_changes[0].field, "age");
485        assert!(!diff.is_backward_compatible);
486    }
487
488    #[test]
489    fn test_compute_diff_removed_required_field() {
490        let old = infer_schema(&serde_json::json!({"name": "Alice", "age": 30}));
491        let new = infer_schema(&serde_json::json!({"name": "Alice"}));
492        let diff = compute_diff(&old, &new);
493        assert_eq!(diff.removed_fields, vec!["age"]);
494        assert!(!diff.is_backward_compatible);
495    }
496
497    #[test]
498    fn test_manager_first_event_infers() {
499        let mgr = SchemaEvolutionManager::new();
500        let action = mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
501        assert_eq!(action, Some(EvolutionAction::Inferred));
502        assert_eq!(mgr.get_version("user.created"), Some(1));
503    }
504
505    #[test]
506    fn test_manager_same_schema_no_action() {
507        let mgr = SchemaEvolutionManager::new();
508        mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
509        let action = mgr.analyze_event("user.created", &serde_json::json!({"name": "Bob"}));
510        assert_eq!(action, None);
511    }
512
513    #[test]
514    fn test_manager_auto_evolve() {
515        let mgr = SchemaEvolutionManager::new();
516        mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
517        let action = mgr.analyze_event(
518            "user.created",
519            &serde_json::json!({"name": "Bob", "email": "bob@example.com"}),
520        );
521        assert_eq!(action, Some(EvolutionAction::AutoEvolved));
522        assert_eq!(mgr.get_version("user.created"), Some(2));
523        // Email field should now be in the schema
524        let schema = mgr.get_schema("user.created").unwrap();
525        assert!(schema.fields.contains_key("email"));
526    }
527
528    #[test]
529    fn test_manager_breaking_change() {
530        let mgr = SchemaEvolutionManager::new();
531        mgr.analyze_event(
532            "user.created",
533            &serde_json::json!({"name": "Alice", "age": 30}),
534        );
535        let action = mgr.analyze_event(
536            "user.created",
537            &serde_json::json!({"name": "Bob", "age": "thirty"}),
538        );
539        assert_eq!(action, Some(EvolutionAction::BreakingChangeDetected));
540        // Version should NOT have incremented
541        assert_eq!(mgr.get_version("user.created"), Some(1));
542    }
543
544    #[test]
545    fn test_manager_history() {
546        let mgr = SchemaEvolutionManager::new();
547        mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
548        mgr.analyze_event(
549            "user.created",
550            &serde_json::json!({"name": "Bob", "email": "b@b.com"}),
551        );
552        let history = mgr.get_history("user.created");
553        assert_eq!(history.len(), 2);
554        assert_eq!(history[0].action, EvolutionAction::Inferred);
555        assert_eq!(history[1].action, EvolutionAction::AutoEvolved);
556    }
557
558    #[test]
559    fn test_manager_stats() {
560        let mgr = SchemaEvolutionManager::new();
561        mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
562        mgr.analyze_event("order.placed", &serde_json::json!({"total": 99.99}));
563        let stats = mgr.stats();
564        assert_eq!(stats.tracked_event_types, 2);
565        assert_eq!(stats.total_evolutions, 2);
566        assert_eq!(stats.breaking_changes, 0);
567    }
568
569    #[test]
570    fn test_manager_list_event_types() {
571        let mgr = SchemaEvolutionManager::new();
572        mgr.analyze_event("user.created", &serde_json::json!({"name": "Alice"}));
573        mgr.analyze_event("order.placed", &serde_json::json!({"total": 99.99}));
574        let types = mgr.list_event_types();
575        assert_eq!(types.len(), 2);
576        assert!(types.contains(&"user.created".to_string()));
577        assert!(types.contains(&"order.placed".to_string()));
578    }
579
580    #[test]
581    fn test_null_field_compatible() {
582        let old = infer_schema(&serde_json::json!({"name": "Alice", "bio": null}));
583        let new = infer_schema(&serde_json::json!({"name": "Alice", "bio": "Hello"}));
584        let diff = compute_diff(&old, &new);
585        // null → string is not a breaking change (null is compatible with any type)
586        assert!(diff.type_changes.is_empty());
587        assert!(diff.is_backward_compatible);
588    }
589}