Skip to main content

feagi_evolutionary/genome/migration/
mod.rs

1// Copyright 2025 Neuraville Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stepwise genome migration: traits, registry, and chain runner.
5//!
6//! A `Migrator` performs a single `vN -> vN+1` transformation on a JSON
7//! genome. Migrators are registered in a `ChainRegistry` keyed by their
8//! `from_version`. The `ChainRunner` walks a genome from its detected
9//! schema version up to a target version, invoking each migrator in
10//! sequence and per-version validators between hops.
11//!
12//! See `feagi-core/docs/GENOME_SCHEMA_VERSIONING.md` for the system-level
13//! design, and `crates/feagi-evolutionary/src/genome/README.md` for the
14//! contributor contract (invariants, retention, anti-patterns).
15
16use std::collections::BTreeMap;
17
18use serde_json::Value;
19use thiserror::Error;
20
21use crate::genome::normalizers::{NormalizationDiagnostics, Normalizer};
22use crate::genome::schema::GenomeSchemaVersion;
23use crate::genome::validators::{ValidationReport, Validator};
24
25pub mod chain;
26pub mod membership;
27pub mod v2_to_v3;
28pub mod v3_to_v4;
29pub mod v4_to_v5;
30pub mod v5_to_v6;
31pub mod v6_to_v7;
32
33pub use chain::ChainRunner;
34pub use v2_to_v3::V2ToV3Migrator;
35pub use v3_to_v4::V3ToV4Migrator;
36pub use v4_to_v5::V4ToV5Migrator;
37pub use v5_to_v6::V5ToV6Migrator;
38pub use v6_to_v7::V6ToV7Migrator;
39
40/// Errors emitted by migrators and by the chain machinery itself.
41#[derive(Debug, Error)]
42pub enum MigrationError {
43    /// A migrator returned an error during its `migrate` call.
44    #[error("Migrator '{name}' ({from} -> {to}) failed: {reason}")]
45    StepFailed {
46        name: &'static str,
47        from: GenomeSchemaVersion,
48        to: GenomeSchemaVersion,
49        reason: String,
50    },
51
52    /// The runner needed a migrator for a version but the registry didn't
53    /// have one. Indicates a gap in the chain.
54    #[error("No migrator registered with from_version={from} (needed to reach v{target})")]
55    MissingMigrator {
56        from: GenomeSchemaVersion,
57        target: GenomeSchemaVersion,
58    },
59
60    /// A migrator's declared `to_version` is not exactly `from_version + 1`,
61    /// or two migrators share a `from_version`. The runner refuses to start
62    /// in either case; see the README's "registry MUST be contiguous" rule.
63    #[error("Registry violates the contiguity invariant: {0}")]
64    InvalidRegistry(String),
65
66    /// The genome's detected schema version is newer than the requested
67    /// target. Forward-only migrations are by design.
68    #[error("Cannot migrate downward: genome is at v{from} but target is v{target}")]
69    DowngradeRefused {
70        from: GenomeSchemaVersion,
71        target: GenomeSchemaVersion,
72    },
73
74    /// `detect_schema_version` could not resolve the input genome.
75    #[error("Failed to detect genome schema version: {0}")]
76    DetectionFailed(String),
77}
78
79/// Diagnostic record produced by a single migrator step.
80///
81/// Per the contributor contract, every transformation a migrator performs
82/// MUST contribute at least one entry to `transformations`. A migrator that
83/// runs and produces zero diagnostics is a bug.
84#[derive(Debug, Clone)]
85pub struct MigrationStepDiagnostics {
86    pub from_version: GenomeSchemaVersion,
87    pub to_version: GenomeSchemaVersion,
88    pub transformations: Vec<String>,
89    /// Deterministic identifier rewrites produced by this migration step.
90    ///
91    /// Brain-artifact migration consumes these mappings to rewrite
92    /// connectome-lite references after its embedded genome is migrated.
93    pub identifier_remaps: BTreeMap<String, String>,
94}
95
96impl MigrationStepDiagnostics {
97    pub fn new(from: GenomeSchemaVersion, to: GenomeSchemaVersion) -> Self {
98        Self {
99            from_version: from,
100            to_version: to,
101            transformations: Vec::new(),
102            identifier_remaps: BTreeMap::new(),
103        }
104    }
105
106    pub fn record(&mut self, msg: impl Into<String>) {
107        self.transformations.push(msg.into());
108    }
109
110    pub fn record_identifier_remap(
111        &mut self,
112        source: impl Into<String>,
113        destination: impl Into<String>,
114    ) {
115        self.identifier_remaps
116            .insert(source.into(), destination.into());
117    }
118}
119
120/// Single `vN -> vN+1` migration step.
121///
122/// Implementations operate on `serde_json::Value` and MUST satisfy the
123/// invariants documented in the module-level README:
124/// determinism, idempotence, bounded compute, no side channels, JSON only,
125/// diagnostics over silence.
126///
127/// Migrators MUST NOT mutate the `genome_schema_version` field on the
128/// input `Value`. The chain runner stamps the new version after each
129/// successful step. This keeps the migrator focused on shape changes and
130/// lets the runner be the single source of truth for version bookkeeping.
131#[allow(clippy::wrong_self_convention)]
132// The `from_*`/`to_*` accessor names describe the migrator's *schema
133// version range*, not constructors. Renaming would hurt readability for
134// every caller (`source_version`/`target_version` were considered and
135// rejected in design review).
136pub trait Migrator: Send + Sync {
137    /// Schema version this migrator accepts as input.
138    fn from_version(&self) -> GenomeSchemaVersion;
139
140    /// Schema version this migrator produces. MUST equal
141    /// `from_version() + 1`; the registry rejects anything else.
142    fn to_version(&self) -> GenomeSchemaVersion;
143
144    /// Stable identifier for diagnostics and logs. Should not change
145    /// across releases for a given step.
146    fn name(&self) -> &'static str;
147
148    /// Perform the transformation in place. Return diagnostics describing
149    /// what changed, or an error.
150    fn migrate(&self, genome: &mut Value) -> Result<MigrationStepDiagnostics, MigrationError>;
151}
152
153/// Aggregate result returned by a successful chain run.
154///
155/// Contains everything `validate-and-repair` needs to surface to clients
156/// per decision #8 in the design doc: the version range traversed, which
157/// named migrators and normalizers ran, per-step diagnostics, advisory
158/// warnings collected between hops, and any blocking errors raised by
159/// the final validator.
160#[derive(Debug, Clone)]
161pub struct ChainResult {
162    pub from_version: GenomeSchemaVersion,
163    pub to_version: GenomeSchemaVersion,
164    pub migrators_applied: Vec<&'static str>,
165    pub normalizers_applied: Vec<&'static str>,
166    pub per_step_diagnostics: Vec<MigrationStepDiagnostics>,
167    pub per_normalizer_diagnostics: Vec<NormalizationDiagnostics>,
168    pub advisory_warnings: Vec<String>,
169    pub blocking_errors: Vec<String>,
170}
171
172impl ChainResult {
173    /// True when the final-version validator reported zero errors.
174    pub fn is_blocking_clean(&self) -> bool {
175        self.blocking_errors.is_empty()
176    }
177}
178
179/// Holds the registered migrators, normalizers, and validators that the
180/// chain runner will dispatch through.
181///
182/// Migrators are keyed by `from_version` (one per integer; duplicates are
183/// rejected at registration). Normalizers are keyed by `schema_version`,
184/// at most one per version. Validators are keyed by `schema_version`.
185/// Contiguity (no gaps in the migrator chain) is checked at runner-start
186/// time over the actual range being traversed, not at registration time.
187pub struct ChainRegistry {
188    migrators: BTreeMap<u32, Box<dyn Migrator>>,
189    normalizers: BTreeMap<u32, Box<dyn Normalizer>>,
190    validators: BTreeMap<u32, Box<dyn Validator>>,
191}
192
193impl ChainRegistry {
194    pub fn new() -> Self {
195        Self {
196            migrators: BTreeMap::new(),
197            normalizers: BTreeMap::new(),
198            validators: BTreeMap::new(),
199        }
200    }
201
202    /// Register a migrator. Rejects duplicates and migrators whose
203    /// `to_version` is not exactly `from_version + 1`.
204    pub fn register_migrator(&mut self, migrator: Box<dyn Migrator>) -> Result<(), MigrationError> {
205        let from = migrator.from_version();
206        let to = migrator.to_version();
207        if to.as_u32() != from.as_u32().saturating_add(1) {
208            return Err(MigrationError::InvalidRegistry(format!(
209                "migrator '{}' declares from={} to={}, expected to=from+1",
210                migrator.name(),
211                from,
212                to
213            )));
214        }
215        if self.migrators.contains_key(&from.as_u32()) {
216            return Err(MigrationError::InvalidRegistry(format!(
217                "duplicate migrator with from_version={from}"
218            )));
219        }
220        self.migrators.insert(from.as_u32(), migrator);
221        Ok(())
222    }
223
224    /// Register a normalizer. Rejects duplicates at the same schema
225    /// version. At most one normalizer per version is supported on
226    /// purpose: composing multiple normalizers in a stable order is
227    /// future work and not needed today.
228    pub fn register_normalizer(
229        &mut self,
230        normalizer: Box<dyn Normalizer>,
231    ) -> Result<(), MigrationError> {
232        let v = normalizer.schema_version();
233        if self.normalizers.contains_key(&v.as_u32()) {
234            return Err(MigrationError::InvalidRegistry(format!(
235                "duplicate normalizer at schema_version={v}"
236            )));
237        }
238        self.normalizers.insert(v.as_u32(), normalizer);
239        Ok(())
240    }
241
242    /// Register a validator. Replaces any existing validator at the same
243    /// schema version (validators are policy-bearing; the latest registered
244    /// one wins).
245    pub fn register_validator(&mut self, validator: Box<dyn Validator>) {
246        let v = validator.schema_version().as_u32();
247        self.validators.insert(v, validator);
248    }
249
250    /// Look up the migrator that consumes genomes at `from`.
251    pub fn migrator_for(&self, from: GenomeSchemaVersion) -> Option<&dyn Migrator> {
252        self.migrators.get(&from.as_u32()).map(|b| b.as_ref())
253    }
254
255    /// Look up the normalizer at `version`.
256    pub fn normalizer_for(&self, version: GenomeSchemaVersion) -> Option<&dyn Normalizer> {
257        self.normalizers.get(&version.as_u32()).map(|b| b.as_ref())
258    }
259
260    /// Look up the validator at `version`.
261    pub fn validator_for(&self, version: GenomeSchemaVersion) -> Option<&dyn Validator> {
262        self.validators.get(&version.as_u32()).map(|b| b.as_ref())
263    }
264
265    /// Run the validator at `version` if one is registered, otherwise
266    /// return an empty advisory report stamped with that version. Used by
267    /// the chain runner so callers always see a consistent shape.
268    pub fn run_validator(&self, version: GenomeSchemaVersion, genome: &Value) -> ValidationReport {
269        match self.validator_for(version) {
270            Some(v) => v.validate(genome),
271            None => ValidationReport::new(version),
272        }
273    }
274
275    /// Number of migrators currently registered.
276    pub fn migrator_count(&self) -> usize {
277        self.migrators.len()
278    }
279
280    /// Number of normalizers currently registered.
281    pub fn normalizer_count(&self) -> usize {
282        self.normalizers.len()
283    }
284
285    /// Number of validators currently registered.
286    pub fn validator_count(&self) -> usize {
287        self.validators.len()
288    }
289}
290
291impl Default for ChainRegistry {
292    fn default() -> Self {
293        Self::new()
294    }
295}
296
297/// Test-only helpers shared with `chain.rs`.
298///
299/// Lives in its own non-`tests` module so that `pub(super)` re-exports
300/// don't trip `clippy::items_after_test_module`.
301#[cfg(test)]
302pub(super) mod test_support {
303    use super::*;
304    use serde_json::json;
305
306    /// Synthetic migrator that bumps a `step_count` field, used to
307    /// exercise the runner mechanics without depending on real domain
308    /// transforms.
309    pub struct SyntheticMigrator {
310        from: GenomeSchemaVersion,
311        to: GenomeSchemaVersion,
312        name: &'static str,
313        fail: bool,
314    }
315
316    impl SyntheticMigrator {
317        pub fn ok(from: u32, name: &'static str) -> Box<Self> {
318            Box::new(Self {
319                from: GenomeSchemaVersion(from),
320                to: GenomeSchemaVersion(from + 1),
321                name,
322                fail: false,
323            })
324        }
325
326        pub fn failing(from: u32, name: &'static str) -> Box<Self> {
327            Box::new(Self {
328                from: GenomeSchemaVersion(from),
329                to: GenomeSchemaVersion(from + 1),
330                name,
331                fail: true,
332            })
333        }
334    }
335
336    impl Migrator for SyntheticMigrator {
337        fn from_version(&self) -> GenomeSchemaVersion {
338            self.from
339        }
340
341        fn to_version(&self) -> GenomeSchemaVersion {
342            self.to
343        }
344
345        fn name(&self) -> &'static str {
346            self.name
347        }
348
349        fn migrate(&self, genome: &mut Value) -> Result<MigrationStepDiagnostics, MigrationError> {
350            if self.fail {
351                return Err(MigrationError::StepFailed {
352                    name: self.name,
353                    from: self.from,
354                    to: self.to,
355                    reason: "synthetic failure".to_string(),
356                });
357            }
358            let mut diag = MigrationStepDiagnostics::new(self.from, self.to);
359            let count = genome
360                .get("step_count")
361                .and_then(|v| v.as_u64())
362                .unwrap_or(0)
363                + 1;
364            genome
365                .as_object_mut()
366                .expect("test genome must be a JSON object")
367                .insert("step_count".to_string(), json!(count));
368            diag.record(format!("incremented step_count to {count}"));
369            Ok(diag)
370        }
371    }
372
373    pub fn make_ok(from: u32, name: &'static str) -> Box<dyn Migrator> {
374        SyntheticMigrator::ok(from, name)
375    }
376
377    pub fn make_failing(from: u32, name: &'static str) -> Box<dyn Migrator> {
378        SyntheticMigrator::failing(from, name)
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::test_support::SyntheticMigrator;
385    use super::*;
386    use serde_json::json;
387
388    #[test]
389    fn registry_accepts_a_well_formed_migrator() {
390        let mut reg = ChainRegistry::new();
391        reg.register_migrator(SyntheticMigrator::ok(2, "v2_to_v3"))
392            .unwrap();
393        assert_eq!(reg.migrator_count(), 1);
394        assert!(reg.migrator_for(GenomeSchemaVersion(2)).is_some());
395        assert!(reg.migrator_for(GenomeSchemaVersion(3)).is_none());
396    }
397
398    #[test]
399    fn registry_rejects_to_version_not_equal_to_from_plus_one() {
400        struct Skipping;
401        impl Migrator for Skipping {
402            fn from_version(&self) -> GenomeSchemaVersion {
403                GenomeSchemaVersion(2)
404            }
405            fn to_version(&self) -> GenomeSchemaVersion {
406                GenomeSchemaVersion(4)
407            }
408            fn name(&self) -> &'static str {
409                "skip"
410            }
411            fn migrate(
412                &self,
413                _genome: &mut Value,
414            ) -> Result<MigrationStepDiagnostics, MigrationError> {
415                unreachable!()
416            }
417        }
418        let mut reg = ChainRegistry::new();
419        let err = reg.register_migrator(Box::new(Skipping)).unwrap_err();
420        assert!(matches!(err, MigrationError::InvalidRegistry(_)));
421    }
422
423    #[test]
424    fn registry_rejects_duplicate_from_version() {
425        let mut reg = ChainRegistry::new();
426        reg.register_migrator(SyntheticMigrator::ok(2, "first"))
427            .unwrap();
428        let err = reg
429            .register_migrator(SyntheticMigrator::ok(2, "second"))
430            .unwrap_err();
431        assert!(matches!(err, MigrationError::InvalidRegistry(_)));
432    }
433
434    #[test]
435    fn migration_step_diagnostics_records_transformations() {
436        let mut diag =
437            MigrationStepDiagnostics::new(GenomeSchemaVersion(2), GenomeSchemaVersion(3));
438        diag.record("converted blueprint keys");
439        diag.record("renamed legacy fields");
440        assert_eq!(diag.transformations.len(), 2);
441        assert_eq!(diag.from_version, GenomeSchemaVersion(2));
442        assert_eq!(diag.to_version, GenomeSchemaVersion(3));
443    }
444
445    #[test]
446    fn run_validator_returns_empty_when_unregistered() {
447        let reg = ChainRegistry::new();
448        let report = reg.run_validator(GenomeSchemaVersion(3), &json!({}));
449        assert_eq!(report.schema_version, Some(GenomeSchemaVersion(3)));
450        assert!(report.is_clean());
451    }
452}