use crate::core::config::OUTPUT_DIR; use crate::core::db::ProcessorType; use anyhow::Result; use std::collections::HashMap; use std::path::PathBuf; use super::schema::{ get_schema, FieldType, FileVerificationReport, ProcessorJsonSchema, ProcessorVerification, RequiredField, }; #[derive(Debug)] pub struct VerificationResult { pub passed: bool, pub processor: String, pub file_uuid: String, pub details: Vec, } impl VerificationResult { pub fn ok(processor: &str, file_uuid: &str) -> Self { Self { passed: true, processor: processor.to_string(), file_uuid: file_uuid.to_string(), details: vec!["verification passed".to_string()], } } pub fn fail(processor: &str, file_uuid: &str, reason: &str) -> Self { Self { passed: false, processor: processor.to_string(), file_uuid: file_uuid.to_string(), details: vec![reason.to_string()], } } } #[derive(Debug)] pub struct VerifierError { pub reason: String, } /// Resolve file_uuid (supports short prefix) fn resolve_uuid(file_uuid: &str) -> String { if file_uuid.len() == 32 { file_uuid.to_string() } else { // Try to find full UUID by scanning output directory let prefix = file_uuid; if let Ok(entries) = std::fs::read_dir(OUTPUT_DIR.as_str()) { for entry in entries.flatten() { if let Some(name) = entry.file_name().to_str() { if name.starts_with(prefix) && name.ends_with(".probe.json") { return name.split('.').next().unwrap_or(prefix).to_string(); } } } } file_uuid.to_string() } } /// Layer 1: Check JSON structure and data completeness fn check_completeness(processor: &ProcessorType, value: &serde_json::Value) -> (bool, Vec) { let schema = match get_schema(processor) { Some(s) => s, None => return (true, Vec::new()), // No schema = pass }; let mut issues = Vec::new(); for field in schema.required_fields { if let Some(val) = get_value_at_path(value, field.path) { match field.field_type { FieldType::Number | FieldType::PositiveNumber => { if val.as_f64().is_none() { issues.push(format!("'{}' is not a number", field.path)); } if field.field_type == FieldType::PositiveNumber && val.as_f64() == Some(0.0) { issues.push(format!("'{}' is zero (expected positive)", field.path)); } } FieldType::Array | FieldType::NonEmptyArray => { if let Some(arr) = val.as_array() { if arr.is_empty() && !field.allow_empty { issues.push(format!("'{}' is empty", field.path)); } } else { issues.push(format!("'{}' is not an array", field.path)); } } FieldType::Object => { if val.as_object().is_none() { issues.push(format!("'{}' is not an object", field.path)); } } FieldType::String => { if val.as_str().is_none() { issues.push(format!("'{}' is not a string", field.path)); } } FieldType::OptionalNumber => { // Optional, skip if null/missing } } } else if !field.allow_empty || field.field_type != FieldType::OptionalNumber { issues.push(format!("'{}' is missing", field.path)); } } // Check data threshold let data_count = count_data_items(processor, value); if data_count < schema.min_data_threshold { issues.push(format!( "data count {} below minimum threshold {}", data_count, schema.min_data_threshold )); } (issues.is_empty(), issues) } /// Extract data count from JSON based on processor type fn count_data_items(processor: &ProcessorType, value: &serde_json::Value) -> usize { match processor { ProcessorType::Cut => value .get("scenes") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), ProcessorType::Yolo => { // YOLO uses dict-based frames value .get("frames") .and_then(|v| v.as_object()) .map(|o| o.len()) .unwrap_or(0) } ProcessorType::Ocr | ProcessorType::Face | ProcessorType::Pose | ProcessorType::Appearance => value .get("frames") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), ProcessorType::Asr => value .get("segments") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), ProcessorType::Asrx => value .get("segments") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), ProcessorType::Scene => value .get("scenes") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0), _ => 0, } } /// Get value at a JSON path (e.g., "stats.total_child_chunks") fn get_value_at_path<'a>( value: &'a serde_json::Value, path: &str, ) -> Option<&'a serde_json::Value> { let parts: Vec<&str> = path.split('.').collect(); let mut current = value; for part in parts { current = current.get(part)?; } Some(current) } /// Layer 2: Check dependency completeness fn check_dependencies( processor: &ProcessorType, all_results: &HashMap, ) -> (bool, Vec) { let deps = processor.dependencies(); let mut issues = Vec::new(); if deps.is_empty() { return (true, Vec::new()); } for dep in &deps { let dep_name = dep.as_str(); match all_results.get(dep_name) { Some(dep_result) => { if !dep_result.file_exists || !dep_result.valid_json { issues.push(format!("dependency '{}' missing or invalid", dep_name)); } else if !dep_result.completeness { issues.push(format!("dependency '{}' incomplete", dep_name)); } // Note: trust_level not checked here as it's updated after this function runs } None => { issues.push(format!("dependency '{}' not found", dep_name)); } } } (issues.is_empty(), issues) } /// Layer 3: Cross-JSON reasonableness checks fn check_reasonableness( processor: &ProcessorType, value: &serde_json::Value, probe_value: Option<&serde_json::Value>, all_values: &HashMap, ) -> (bool, Vec) { let mut issues = Vec::new(); // Get probe data if available let probe_fps = probe_value .and_then(|p| p.get("streams")) .and_then(|s| s.as_array()) .and_then(|streams| { streams .iter() .find(|s| s.get("codec_type").and_then(|c| c.as_str()) == Some("video")) }) .and_then(|v| v.get("r_frame_rate")) .and_then(|r| r.as_str()) .and_then(|fps_str| { if let Some((num, den)) = fps_str.split_once('/') { if let (Ok(n), Ok(d)) = (num.parse::(), den.parse::()) { if d > 0.0 { return Some(n / d); } } } None }); let probe_frames = probe_value .and_then(|p| p.get("streams")) .and_then(|s| s.as_array()) .and_then(|streams| { streams .iter() .find(|s| s.get("codec_type").and_then(|c| c.as_str()) == Some("video")) }) .and_then(|v| v.get("nb_frames")) .and_then(|n| n.as_str()) .and_then(|s| s.parse::().ok()); // Check fps consistency with probe if let Some(json_fps) = value.get("fps").and_then(|v| v.as_f64()) { if json_fps <= 0.0 { issues.push("fps is zero or negative".to_string()); } else if let Some(p_fps) = probe_fps { let diff = (json_fps - p_fps).abs(); if diff > 0.5 { issues.push(format!( "fps mismatch: JSON={}, probe={:.2}", json_fps, p_fps )); } } } // Check frame_count consistency with probe // For sampled processors (8Hz), frame_count should be ~total_frames/8 // Only flag if the count is wildly off (less than 10% of expected) if let Some(json_frames) = value.get("frame_count").and_then(|v| v.as_u64()) { if let Some(p_frames) = probe_frames { // Check if this is a sampled processor (most frame processors use 8Hz) let is_sampled = matches!( processor, ProcessorType::Cut | ProcessorType::Yolo | ProcessorType::Ocr | ProcessorType::Face | ProcessorType::Pose | ProcessorType::Appearance | ProcessorType::Scene ); let expected = if is_sampled { (p_frames as f64 / 8.0) as u64 } else { p_frames }; // Allow 50% tolerance for sampling variations let min_expected = (expected as f64 * 0.1) as u64; if json_frames > 0 && json_frames < min_expected && min_expected > 0 { issues.push(format!( "frame_count {} much less than expected ~{} (probe={})", json_frames, expected, p_frames )); } } } // ASR-specific: check segments vs cut scenes if *processor == ProcessorType::Asr { if let Some(cut_value) = all_values.get("cut") { let asr_segments = count_data_items(processor, value); let cut_scenes = count_data_items(&ProcessorType::Cut, cut_value); if asr_segments == 0 && cut_scenes > 5 { issues.push(format!( "ASR has 0 segments but CUT has {} scenes", cut_scenes )); } } } // ASRX-specific: check segments vs cut scenes if *processor == ProcessorType::Asrx { if let Some(cut_value) = all_values.get("cut") { let asrx_segments = count_data_items(processor, value); let cut_scenes = count_data_items(&ProcessorType::Cut, cut_value); // Only flag if CUT has many scenes but ASRX has none (likely a processing issue) if asrx_segments == 0 && cut_scenes > 5 { issues.push(format!( "ASRX has 0 segments but CUT has {} scenes", cut_scenes )); } } } // Check scene time ranges if *processor == ProcessorType::Cut || *processor == ProcessorType::Scene { if let Some(scenes) = value.get("scenes").and_then(|v| v.as_array()) { for (i, scene) in scenes.iter().enumerate() { let start = scene.get("start_time").and_then(|v| v.as_f64()); let end = scene.get("end_time").and_then(|v| v.as_f64()); if let (Some(s), Some(e)) = (start, end) { if e < s { issues.push(format!("scene {}: end_time < start_time", i)); } } } } } (issues.is_empty(), issues) } /// Build data summary for a processor JSON fn build_data_summary(processor: &ProcessorType, value: &serde_json::Value) -> serde_json::Value { let data_count = count_data_items(processor, value); let mut summary = serde_json::json!({ "data_count": data_count }); match processor { ProcessorType::Cut => { if let Some(scenes) = value.get("scenes").and_then(|v| v.as_array()) { summary["scene_count"] = serde_json::json!(scenes.len()); if let Some(first) = scenes.first() { summary["first_scene_start"] = first.get("start_time").and_then(|v| v.as_f64()).into(); } if let Some(last) = scenes.last() { summary["last_scene_end"] = last.get("end_time").and_then(|v| v.as_f64()).into(); } } } ProcessorType::Face | ProcessorType::Ocr | ProcessorType::Pose | ProcessorType::Appearance => { if let Some(frames) = value.get("frames").and_then(|v| v.as_array()) { let total_detections: usize = frames .iter() .map(|f| { f.get("faces") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0) + f.get("objects") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0) + f.get("texts") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0) + f.get("persons") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0) }) .sum(); summary["total_detections"] = serde_json::json!(total_detections); summary["frames_with_data"] = serde_json::json!(frames .iter() .filter(|f| { f.get("faces") .and_then(|v| v.as_array()) .map(|a| !a.is_empty()) .unwrap_or(false) || f.get("objects") .and_then(|v| v.as_array()) .map(|a| !a.is_empty()) .unwrap_or(false) || f.get("texts") .and_then(|v| v.as_array()) .map(|a| !a.is_empty()) .unwrap_or(false) || f.get("persons") .and_then(|v| v.as_array()) .map(|a| !a.is_empty()) .unwrap_or(false) }) .count()); } } ProcessorType::Yolo => { if let Some(frames) = value.get("frames").and_then(|v| v.as_object()) { let total_detections: usize = frames .values() .map(|f| { f.get("objects") .and_then(|v| v.as_array()) .map(|a| a.len()) .unwrap_or(0) }) .sum(); summary["total_detections"] = serde_json::json!(total_detections); summary["frames_with_data"] = serde_json::json!(frames .values() .filter(|f| { f.get("objects") .and_then(|v| v.as_array()) .map(|a| !a.is_empty()) .unwrap_or(false) }) .count()); } } ProcessorType::Asr => { if let Some(segments) = value.get("segments").and_then(|v| v.as_array()) { summary["segment_count"] = serde_json::json!(segments.len()); if let Some(lang) = value.get("language").and_then(|v| v.as_str()) { summary["language"] = serde_json::json!(lang); } } } ProcessorType::Asrx => { if let Some(segments) = value.get("segments").and_then(|v| v.as_array()) { let speakers: std::collections::HashSet = segments .iter() .filter_map(|s| { s.get("speaker_id") .and_then(|v| v.as_str()) .map(|s| s.to_string()) }) .collect(); summary["segment_count"] = serde_json::json!(segments.len()); summary["speaker_count"] = serde_json::json!(speakers.len()); } } _ => {} } summary } /// Load probe.json for a file fn load_probe_json(file_uuid: &str) -> Option { let probe_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!("{}.probe.json", file_uuid)); if let Ok(content) = std::fs::read_to_string(&probe_path) { serde_json::from_str(&content).ok() } else { None } } /// Main verification function for a file pub fn verify_file(file_uuid: &str) -> FileVerificationReport { let full_uuid = resolve_uuid(file_uuid); let processors = ProcessorType::all(); let mut report = FileVerificationReport { file_uuid: full_uuid.clone(), trust_level: "untrusted".to_string(), processors: Vec::new(), summary: serde_json::json!({}), }; // Load probe.json once let probe_value = load_probe_json(&full_uuid); // Phase 1: Load all JSON values let mut all_values: HashMap = HashMap::new(); for processor in &processors { let proc_name = processor.as_str(); let filename = format!("{}.{}.json", full_uuid, proc_name); let path = PathBuf::from(OUTPUT_DIR.as_str()).join(&filename); if let Ok(content) = std::fs::read_to_string(&path) { if let Ok(value) = serde_json::from_str(&content) { all_values.insert(proc_name.to_string(), value); } } } // Phase 2: Verify each processor let mut verifications: Vec = Vec::new(); let mut value_refs: HashMap = HashMap::new(); for processor in &processors { let proc_name = processor.as_str(); let mut pv = ProcessorVerification::new(proc_name); if let Some(value) = all_values.get(proc_name) { pv.file_exists = true; pv.valid_json = true; value_refs.insert(proc_name.to_string(), value); // Layer 1: Completeness let (complete, issues) = check_completeness(processor, value); pv.completeness = complete; pv.issues.extend(issues); // Data summary pv.data_summary = build_data_summary(processor, value); } else { pv.issues.push("JSON file not found".to_string()); } verifications.push(pv); } // Phase 3: Check dependencies and reasonableness // Build references once outside the loop let mut all_value_refs: HashMap = HashMap::new(); for (name, value) in &all_values { all_value_refs.insert(name.clone(), value); } let probe_ref = probe_value.as_ref(); // Collect updates first, then apply let updates: Vec<(String, bool, bool, Vec)> = verifications .iter() .map(|pv| { let processor = ProcessorType::all() .iter() .find(|p| p.as_str() == pv.processor) .cloned(); if let Some(ref proc_type) = processor { // Build verification refs for dependency checking // Use completeness/valid_json/file_exists from Layer 1 results, not trust_level let mut verif_refs: HashMap = HashMap::new(); for v in &verifications { verif_refs.insert(v.processor.clone(), v); } // Layer 2: Dependencies (check completeness, not trust_level) let (deps_ok, dep_issues) = check_dependencies(proc_type, &verif_refs); // Layer 3: Reasonableness let (reasonable, reason_issues) = if let Some(val) = all_values.get(&pv.processor) { check_reasonableness(proc_type, val, probe_ref, &all_value_refs) } else { (true, Vec::new()) }; let mut all_issues = dep_issues.clone(); all_issues.extend(reason_issues); (pv.processor.clone(), deps_ok, reasonable, all_issues) } else { (pv.processor.clone(), true, true, Vec::new()) } }) .collect(); // Apply updates for (i, update) in updates.into_iter().enumerate() { verifications[i].dependency_ok = update.1; verifications[i].reasonableness = update.2; verifications[i].issues.extend(update.3); verifications[i].update_trust_level(); } report.processors = verifications; report.update_overall_trust(); report } /// Legacy verification function (backward compatible) pub fn verify_output(processor: &ProcessorType, file_uuid: &str) -> VerificationResult { let proc_name = processor.as_str(); let filename = format!("{}.{}.json", file_uuid, proc_name); let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(&filename); if !output_path.exists() { return VerificationResult::fail(proc_name, file_uuid, "output file not found"); } let json_str = match std::fs::read_to_string(&output_path) { Ok(s) => s, Err(e) => { return VerificationResult::fail(proc_name, file_uuid, &format!("unreadable: {}", e)) } }; let value: serde_json::Value = match serde_json::from_str(&json_str) { Ok(v) => v, Err(e) => { return VerificationResult::fail(proc_name, file_uuid, &format!("invalid JSON: {}", e)) } }; // Use new completeness check let (complete, issues) = check_completeness(processor, &value); if !complete { return VerificationResult::fail(proc_name, file_uuid, &issues.join("; ")); } VerificationResult::ok(proc_name, file_uuid) } /// Clean up temp files for a processor pub fn cleanup_temp_files(processor: &ProcessorType, file_uuid: &str) { let proc_name = processor.as_str(); let prefix = format!("{}.{}.", file_uuid, proc_name); let canonical = format!("{}.{}.json", file_uuid, proc_name); if let Ok(dir) = std::fs::read_dir(OUTPUT_DIR.as_str()) { let mut removed = 0u32; for entry in dir.flatten() { let name = entry.file_name(); let name = name.to_string_lossy().to_string(); if !name.starts_with(&prefix) { continue; } if name == canonical { continue; } if let Err(e) = std::fs::remove_file(entry.path()) { tracing::warn!("Failed to cleanup {}: {}", name, e); } else { removed += 1; } } if removed > 0 { tracing::info!( "Cleaned up {} temp files for {}.{}", removed, file_uuid, proc_name ); } } }