use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; /// Version of the lifecycle schema. const LIFECYCLE_VERSION: &str = "1.0"; // ─── Data Types ─── /// Complete lifecycle state for a file #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FileLifecycle { pub version: String, pub file_uuid: String, pub updated_at: String, // RFC3339 pub stages: LifecycleStages, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LifecycleStages { /// Stage 0: Registration (profile.json, probe.json, cut.json) pub registration: StageState, /// Stage 1: First-level processors (asr, ocr, face) pub stage_1_processors: ProcessorGroupState, /// Stage 2: Second-level processors (asrx, face_vector, speaker_vector) pub stage_2_processors: ProcessorGroupState, /// Stage 3: Third-level processors (pose, appearance) pub stage_3_processors: ProcessorGroupState, /// Rule 1: Text ingestion (sentence chunks → PG + Qdrant) pub rule_1_ingestion: IngestionState, /// Rule 2: Node ingestion (face/speaker TKG nodes) pub rule_2_ingestion: IngestionState, /// Rule 3: Edge ingestion (TKG edges) pub rule_3_ingestion: IngestionState, /// Final completion pub completed: StageState, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct StageState { pub status: String, // pending / in_progress / completed / failed / skipped #[serde(skip_serializing_if = "Option::is_none")] pub started_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub completed_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProcessorGroupState { pub status: String, // pending / in_progress / completed / partial / failed pub processors: HashMap, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProcessorState { pub status: String, // pending / running / completed / failed / skipped #[serde(skip_serializing_if = "Option::is_none")] pub started_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub completed_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub progress: Option, #[serde(skip_serializing_if = "Option::is_none")] pub output_count: Option, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, #[serde(skip_serializing_if = "Option::is_none")] pub retry_count: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ProgressInfo { pub current: i64, pub total: i64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IngestionState { pub status: String, // pending / in_progress / completed / failed / skipped #[serde(skip_serializing_if = "Option::is_none")] pub started_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub completed_at: Option, #[serde(skip_serializing_if = "Option::is_none")] pub items_ingested: Option, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option, } // ─── Processor Definitions ─── /// Stage 1 processors (no dependencies, run in parallel) pub const STAGE_1_PROCESSORS: &[&str] = &["asr", "ocr", "face"]; /// Stage 2 processors (depend on stage 1) pub const STAGE_2_PROCESSORS: &[&str] = &[ "asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", ]; /// Stage 3 processors (depend on stage 2 or face) pub const STAGE_3_PROCESSORS: &[&str] = &["pose", "appearance"]; /// All processors in order pub const ALL_PROCESSORS: &[&str] = &[ "cut", // Registration "asr", "ocr", "face", // Stage 1 "asrx", "face_vector", "face_trace", "speaker_vector", "face_cluster", // Stage 2 "pose", "appearance", // Stage 3 ]; /// Get processor dependencies pub fn get_dependencies(processor: &str) -> Vec<&'static str> { match processor { "asrx" => vec!["cut", "asr"], "face_vector" => vec!["face"], "face_trace" => vec!["face_vector"], // trace after vectorization "speaker_vector" => vec!["asrx"], "face_cluster" => vec!["face_trace"], // deduplication after trace "pose" => vec!["face"], "appearance" => vec!["pose"], _ => vec![], } } /// Get processor stage pub fn get_stage(processor: &str) -> &'static str { match processor { "cut" => "registration", "asr" | "ocr" | "face" => "stage_1", "asrx" | "face_vector" | "face_trace" | "speaker_vector" | "face_cluster" => "stage_2", "pose" | "appearance" => "stage_3", _ => "unknown", } } // ─── Construction ─── impl FileLifecycle { /// Create a new lifecycle for a file pub fn new(file_uuid: &str) -> Self { let now = chrono::Utc::now().to_rfc3339(); let mut stage_1_processors = HashMap::new(); for proc in STAGE_1_PROCESSORS { stage_1_processors.insert(proc.to_string(), ProcessorState::new("pending")); } let mut stage_2_processors = HashMap::new(); for proc in STAGE_2_PROCESSORS { stage_2_processors.insert(proc.to_string(), ProcessorState::new("pending")); } let mut stage_3_processors = HashMap::new(); for proc in STAGE_3_PROCESSORS { stage_3_processors.insert(proc.to_string(), ProcessorState::new("pending")); } Self { version: LIFECYCLE_VERSION.to_string(), file_uuid: file_uuid.to_string(), updated_at: now, stages: LifecycleStages { registration: StageState::new("pending"), stage_1_processors: ProcessorGroupState { status: "pending".to_string(), processors: stage_1_processors, }, stage_2_processors: ProcessorGroupState { status: "pending".to_string(), processors: stage_2_processors, }, stage_3_processors: ProcessorGroupState { status: "pending".to_string(), processors: stage_3_processors, }, rule_1_ingestion: IngestionState::new("pending"), rule_2_ingestion: IngestionState::new("pending"), rule_3_ingestion: IngestionState::new("pending"), completed: StageState::new("pending"), }, } } /// Create lifecycle from existing outputs (for recovery) pub fn from_existing_outputs(output_dir: &str, file_uuid: &str) -> Self { let mut lifecycle = Self::new(file_uuid); // Check registration outputs let has_profile = Path::new(output_dir) .join(format!("{}.profile.json", file_uuid)) .exists(); let has_probe = Path::new(output_dir) .join(format!("{}.probe.json", file_uuid)) .exists(); let has_cut = Path::new(output_dir) .join(format!("{}.cut.json", file_uuid)) .exists(); if has_profile && has_probe && has_cut { lifecycle.mark_stage_completed("registration"); } // Check stage 1 processors for proc in STAGE_1_PROCESSORS { let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc)); if path.exists() { lifecycle.mark_processor_completed(proc, None); } } // Check stage 2 processors let has_asrx = Path::new(output_dir) .join(format!("{}.asrx.json", file_uuid)) .exists(); if has_asrx { lifecycle.mark_processor_completed("asrx", None); // speaker_vector comes from asrx lifecycle.mark_processor_completed("speaker_vector", None); } // face_vector: check if face.json exists (vectors stored in Qdrant) let has_face = Path::new(output_dir) .join(format!("{}.face.json", file_uuid)) .exists(); if has_face { lifecycle.mark_processor_completed("face_vector", None); } // face_trace: check face_traced.json (continuous face tracking) let has_face_traced = Path::new(output_dir) .join(format!("{}.face_traced.json", file_uuid)) .exists(); if has_face_traced { lifecycle.mark_processor_completed("face_trace", None); } // face_cluster: check face_cluster.json (deduplication of traces) let has_face_cluster = Path::new(output_dir) .join(format!("{}.face_cluster.json", file_uuid)) .exists(); if has_face_cluster { lifecycle.mark_processor_completed("face_cluster", None); } // Check stage 3 processors for proc in STAGE_3_PROCESSORS { let path = Path::new(output_dir).join(format!("{}.{}.json", file_uuid, proc)); if path.exists() { lifecycle.mark_processor_completed(proc, None); } } lifecycle.update_group_status(); lifecycle } // ─── Persistence ─── /// Return the lifecycle file path: `{output_dir}/{file_uuid}.lifecycle.json` pub fn lifecycle_path(output_dir: &str, file_uuid: &str) -> PathBuf { Path::new(output_dir).join(format!("{}.lifecycle.json", file_uuid)) } /// Save lifecycle to disk pub fn save_to_disk(&self, output_dir: &str) -> Result<()> { let path = Self::lifecycle_path(output_dir, &self.file_uuid); let json = serde_json::to_string_pretty(self).context("Failed to serialize lifecycle")?; std::fs::write(&path, json) .with_context(|| format!("Failed to write lifecycle to {}", path.display()))?; tracing::debug!("[Lifecycle] Saved for {}", self.file_uuid); Ok(()) } /// Load lifecycle from disk pub fn load_from_disk(output_dir: &str, file_uuid: &str) -> Option { let path = Self::lifecycle_path(output_dir, file_uuid); let content = std::fs::read_to_string(&path).ok()?; serde_json::from_str(&content).ok() } /// Load or create new lifecycle pub fn load_or_create(output_dir: &str, file_uuid: &str) -> Self { Self::load_from_disk(output_dir, file_uuid) .unwrap_or_else(|| Self::from_existing_outputs(output_dir, file_uuid)) } // ─── State Updates ─── /// Mark a stage as started pub fn mark_stage_started(&mut self, stage: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); match stage { "registration" => { self.stages.registration.status = "in_progress".to_string(); self.stages.registration.started_at = Some(now); } "stage_1" => { self.stages.stage_1_processors.status = "in_progress".to_string(); } "stage_2" => { self.stages.stage_2_processors.status = "in_progress".to_string(); } "stage_3" => { self.stages.stage_3_processors.status = "in_progress".to_string(); } "rule_1" => { self.stages.rule_1_ingestion.status = "in_progress".to_string(); self.stages.rule_1_ingestion.started_at = Some(now); } "rule_2" => { self.stages.rule_2_ingestion.status = "in_progress".to_string(); self.stages.rule_2_ingestion.started_at = Some(now); } "rule_3" => { self.stages.rule_3_ingestion.status = "in_progress".to_string(); self.stages.rule_3_ingestion.started_at = Some(now); } _ => {} } } /// Mark a stage as completed pub fn mark_stage_completed(&mut self, stage: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); match stage { "registration" => { self.stages.registration.status = "completed".to_string(); self.stages.registration.completed_at = Some(now); } "rule_1" => { self.stages.rule_1_ingestion.status = "completed".to_string(); self.stages.rule_1_ingestion.completed_at = Some(now); } "rule_2" => { self.stages.rule_2_ingestion.status = "completed".to_string(); self.stages.rule_2_ingestion.completed_at = Some(now); } "rule_3" => { self.stages.rule_3_ingestion.status = "completed".to_string(); self.stages.rule_3_ingestion.completed_at = Some(now); } "completed" => { self.stages.completed.status = "completed".to_string(); self.stages.completed.completed_at = Some(now); } _ => {} } } /// Mark a processor as started pub fn mark_processor_started(&mut self, processor: &str) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, "stage_2" => &mut self.stages.stage_2_processors, "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "running".to_string(); proc_state.started_at = Some(now); } // Update group status group.status = "in_progress".to_string(); } /// Mark a processor as completed pub fn mark_processor_completed(&mut self, processor: &str, output_count: Option) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, "stage_2" => &mut self.stages.stage_2_processors, "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "completed".to_string(); proc_state.completed_at = Some(now); proc_state.output_count = output_count; } self.update_group_status(); } /// Mark a processor as failed pub fn mark_processor_failed(&mut self, processor: &str, error: &str, retry_count: i32) { let now = chrono::Utc::now().to_rfc3339(); self.updated_at = now.clone(); let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, "stage_2" => &mut self.stages.stage_2_processors, "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.status = "failed".to_string(); proc_state.error = Some(error.to_string()); proc_state.retry_count = Some(retry_count); } self.update_group_status(); } /// Update processor progress pub fn update_processor_progress(&mut self, processor: &str, current: i64, total: i64) { self.updated_at = chrono::Utc::now().to_rfc3339(); let stage = get_stage(processor); let group = match stage { "stage_1" => &mut self.stages.stage_1_processors, "stage_2" => &mut self.stages.stage_2_processors, "stage_3" => &mut self.stages.stage_3_processors, _ => return, }; if let Some(proc_state) = group.processors.get_mut(processor) { proc_state.progress = Some(ProgressInfo { current, total }); } } /// Update group status based on processor states fn update_group_status(&mut self) { // Update stage 1 let stage_1 = &mut self.stages.stage_1_processors; stage_1.status = compute_group_status(&stage_1.processors); // Update stage 2 let stage_2 = &mut self.stages.stage_2_processors; stage_2.status = compute_group_status(&stage_2.processors); // Update stage 3 let stage_3 = &mut self.stages.stage_3_processors; stage_3.status = compute_group_status(&stage_3.processors); } // ─── Queries ─── /// Check if a processor can run (dependencies met) pub fn can_run_processor(&self, processor: &str) -> bool { let deps = get_dependencies(processor); if deps.is_empty() { return true; } for dep in deps { if !self.is_processor_completed(dep) { return false; } } true } /// Check if a processor is completed pub fn is_processor_completed(&self, processor: &str) -> bool { let stage = get_stage(processor); let group = match stage { "stage_1" => &self.stages.stage_1_processors, "stage_2" => &self.stages.stage_2_processors, "stage_3" => &self.stages.stage_3_processors, _ => return processor == "cut" && self.stages.registration.status == "completed", }; group .processors .get(processor) .map(|p| p.status == "completed") .unwrap_or(false) } /// Get next processors to run pub fn get_next_processors(&self) -> Vec { let mut next = Vec::new(); // Check stage 1 if self.stages.registration.status != "completed" { return next; // Registration must complete first } for proc in STAGE_1_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } if !next.is_empty() { return next; } // Check stage 2 for proc in STAGE_2_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } if !next.is_empty() { return next; } // Check stage 3 for proc in STAGE_3_PROCESSORS { if !self.is_processor_completed(proc) && self.can_run_processor(proc) { next.push(proc.to_string()); } } next } /// Check if all processors are complete pub fn all_processors_complete(&self) -> bool { for proc in ALL_PROCESSORS { if !self.is_processor_completed(proc) { return false; } } true } /// Check if Rule 1 can run (text ingestion) pub fn can_run_rule_1(&self) -> bool { self.is_processor_completed("asrx") } /// Check if Rule 2 can run (TKG nodes) pub fn can_run_rule_2(&self) -> bool { self.is_processor_completed("face_trace") && self.is_processor_completed("speaker_vector") } /// Check if Rule 3 can run (TKG edges) pub fn can_run_rule_3(&self) -> bool { self.stages.rule_2_ingestion.status == "completed" } /// Check if file is fully complete pub fn is_complete(&self) -> bool { self.all_processors_complete() && self.stages.rule_1_ingestion.status == "completed" && self.stages.rule_2_ingestion.status == "completed" && self.stages.rule_3_ingestion.status == "completed" } /// Get overall progress percentage pub fn overall_progress(&self) -> f64 { let mut completed = 0; let mut total = 0; // Registration total += 1; if self.stages.registration.status == "completed" { completed += 1; } // Stage 1 for proc in STAGE_1_PROCESSORS { total += 1; if self.is_processor_completed(proc) { completed += 1; } } // Stage 2 for proc in STAGE_2_PROCESSORS { total += 1; if self.is_processor_completed(proc) { completed += 1; } } // Stage 3 for proc in STAGE_3_PROCESSORS { total += 1; if self.is_processor_completed(proc) { completed += 1; } } // Rules total += 3; if self.stages.rule_1_ingestion.status == "completed" { completed += 1; } if self.stages.rule_2_ingestion.status == "completed" { completed += 1; } if self.stages.rule_3_ingestion.status == "completed" { completed += 1; } if total == 0 { 0.0 } else { (completed as f64 / total as f64) * 100.0 } } } impl StageState { fn new(status: &str) -> Self { Self { status: status.to_string(), started_at: None, completed_at: None, error: None, } } } impl ProcessorState { fn new(status: &str) -> Self { Self { status: status.to_string(), started_at: None, completed_at: None, progress: None, output_count: None, error: None, retry_count: None, } } } impl IngestionState { fn new(status: &str) -> Self { Self { status: status.to_string(), started_at: None, completed_at: None, items_ingested: None, error: None, } } } /// Compute group status from processor states fn compute_group_status(processors: &HashMap) -> String { let mut has_running = false; let mut has_failed = false; let mut has_pending = false; let mut completed_count = 0; for proc in processors.values() { match proc.status.as_str() { "running" => has_running = true, "failed" => has_failed = true, "pending" => has_pending = true, "completed" => completed_count += 1, _ => {} } } if has_running { "in_progress".to_string() } else if has_failed { "failed".to_string() } else if has_pending { if completed_count > 0 { "partial".to_string() } else { "pending".to_string() } } else { "completed".to_string() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_lifecycle_new() { let lifecycle = FileLifecycle::new("test_uuid"); assert_eq!(lifecycle.file_uuid, "test_uuid"); assert_eq!(lifecycle.stages.registration.status, "pending"); assert_eq!(lifecycle.stages.stage_1_processors.status, "pending"); } #[test] fn test_processor_dependencies() { assert!(get_dependencies("asr").is_empty()); assert_eq!(get_dependencies("asrx"), vec!["cut", "asr"]); assert_eq!(get_dependencies("pose"), vec!["face"]); } #[test] fn test_can_run_processor() { let mut lifecycle = FileLifecycle::new("test"); // Initially, asrx cannot run (needs cut + asr) assert!(!lifecycle.can_run_processor("asrx")); // After registration, still cannot run (needs asr) lifecycle.mark_stage_completed("registration"); assert!(!lifecycle.can_run_processor("asrx")); // After asr completes, can run lifecycle.mark_processor_completed("asr", Some(10)); assert!(lifecycle.can_run_processor("asrx")); } #[test] fn test_overall_progress() { let mut lifecycle = FileLifecycle::new("test"); assert_eq!(lifecycle.overall_progress(), 0.0); lifecycle.mark_stage_completed("registration"); let progress = lifecycle.overall_progress(); assert!(progress > 0.0 && progress < 100.0); } }