feagi_evolutionary/genome/migration/
mod.rs1use 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#[derive(Debug, Error)]
42pub enum MigrationError {
43 #[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 #[error("No migrator registered with from_version={from} (needed to reach v{target})")]
55 MissingMigrator {
56 from: GenomeSchemaVersion,
57 target: GenomeSchemaVersion,
58 },
59
60 #[error("Registry violates the contiguity invariant: {0}")]
64 InvalidRegistry(String),
65
66 #[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 #[error("Failed to detect genome schema version: {0}")]
76 DetectionFailed(String),
77}
78
79#[derive(Debug, Clone)]
85pub struct MigrationStepDiagnostics {
86 pub from_version: GenomeSchemaVersion,
87 pub to_version: GenomeSchemaVersion,
88 pub transformations: Vec<String>,
89 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#[allow(clippy::wrong_self_convention)]
132pub trait Migrator: Send + Sync {
137 fn from_version(&self) -> GenomeSchemaVersion;
139
140 fn to_version(&self) -> GenomeSchemaVersion;
143
144 fn name(&self) -> &'static str;
147
148 fn migrate(&self, genome: &mut Value) -> Result<MigrationStepDiagnostics, MigrationError>;
151}
152
153#[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 pub fn is_blocking_clean(&self) -> bool {
175 self.blocking_errors.is_empty()
176 }
177}
178
179pub 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 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 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 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 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 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 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 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 pub fn migrator_count(&self) -> usize {
277 self.migrators.len()
278 }
279
280 pub fn normalizer_count(&self) -> usize {
282 self.normalizers.len()
283 }
284
285 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#[cfg(test)]
302pub(super) mod test_support {
303 use super::*;
304 use serde_json::json;
305
306 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}