From d01e456ae5f7fa51ddbff07a8413f3bb666845ad Mon Sep 17 00:00:00 2001 From: Accusys Date: Tue, 17 Nov 2026 02:46:57 +0800 Subject: [PATCH] fix(P0): per-library output dir for worker ingestion/verification (face_cluster guard, verifier, TKG, qdrant_face, ASR/ASRX); fix face_cluster serde default for empty output; fix face_cluster dependencies in pipeline_flows.json --- src/core/processor/face_clustering.rs | 2 + src/verification/verifier.rs | 31 +++- src/worker/job_worker.rs | 187 +++++++++++--------- src/worker/processor.rs | 11 +- tools/cli/rust/src/bin/rust_face_cluster.rs | 9 + 5 files changed, 152 insertions(+), 88 deletions(-) diff --git a/src/core/processor/face_clustering.rs b/src/core/processor/face_clustering.rs index 7a31872e..183317b3 100644 --- a/src/core/processor/face_clustering.rs +++ b/src/core/processor/face_clustering.rs @@ -13,7 +13,9 @@ pub struct FaceClusterResult { #[serde(default)] pub file_uuid: Option, pub status: String, + #[serde(default)] pub stats: ClusterStats, + #[serde(default)] pub clusters: Vec, #[serde(default)] pub unassigned_traces: Vec, diff --git a/src/verification/verifier.rs b/src/verification/verifier.rs index d31aae08..23524264 100644 --- a/src/verification/verifier.rs +++ b/src/verification/verifier.rs @@ -563,9 +563,38 @@ pub fn verify_file(file_uuid: &str) -> FileVerificationReport { /// Legacy verification function (backward compatible) pub fn verify_output(processor: &ProcessorType, file_uuid: &str) -> VerificationResult { + let output_dir = OUTPUT_DIR.as_str(); + verify_output_in_dir(processor, file_uuid, output_dir) +} + +/// Verification with explicit output directory (per-library aware). +/// Falls back to the global OUTPUT_DIR and the demo subdirectory if the +/// primary path does not exist, so per-library outputs verify correctly. +pub fn verify_output_in_dir( + processor: &ProcessorType, + file_uuid: &str, + output_dir: &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); + + // Candidate locations: explicit dir → global OUTPUT_DIR → OUTPUT_DIR/demo + let base = output_dir.trim_end_matches('/'); + let global = OUTPUT_DIR.as_str().trim_end_matches('/'); + let candidates = if base == global { + vec![ + PathBuf::from(base), + PathBuf::from(format!("{}/demo", global)), + ] + } else { + vec![PathBuf::from(base), PathBuf::from(global)] + }; + + let output_path = candidates + .iter() + .map(|d| d.join(&filename)) + .find(|p| p.exists()) + .unwrap_or_else(|| PathBuf::from(base).join(&filename)); if !output_path.exists() { return VerificationResult::fail(proc_name, file_uuid, "output file not found"); diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index 0a7ad51a..ddad33e3 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -1066,8 +1066,10 @@ impl JobWorker { ) -> Result<()> { use std::path::Path; - // Get output directory from config - let output_dir = crate::core::config::OUTPUT_DIR.to_string(); + // Get output directory (per-library, fallback global) + let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await; + // Also check the global output dir for legacy files + let global_output_dir = crate::core::config::OUTPUT_DIR.to_string(); // Get current processor_results let existing_results = match self @@ -1090,12 +1092,15 @@ impl JobWorker { let mut repaired_count = 0; for processor_type in processors { - let output_path = format!( - "{}/{}.{}.json", - output_dir, - job.uuid, - processor_type.as_str() - ); + let filename = format!("{}.{}.json", job.uuid, processor_type.as_str()); + // Per-library first, then global fallback (legacy files) + let per_lib_path = format!("{}/{}", output_dir.trim_end_matches('/'), filename); + let global_path = format!("{}/{}", global_output_dir.trim_end_matches('/'), filename); + let output_path = if Path::new(&per_lib_path).exists() { + per_lib_path + } else { + global_path + }; // If file exists but no DB record if Path::new(&output_path).exists() { @@ -1639,19 +1644,24 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { .await?; // Check if output file already exists on disk (source of truth) - let output_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!( - "{}.{}.json", - job.uuid, - processor_type.as_str() - )); + // Per-library output dir(先查此檔案的專屬目錄,fallback 全域) + let per_lib_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await; + let global_dir = OUTPUT_DIR.as_str(); + let filename = format!("{}.{}.json", job.uuid, processor_type.as_str()); + let output_path = if PathBuf::from(&per_lib_dir).join(&filename).exists() { + PathBuf::from(&per_lib_dir).join(&filename) + } else { + PathBuf::from(global_dir).join(&filename) + }; debug!("Checking output file: {:?}", output_path); // Check for stale .tmp file (process crashed before renaming) - let tmp_path = PathBuf::from(OUTPUT_DIR.as_str()).join(format!( - "{}.{}.json.tmp", - job.uuid, - processor_type.as_str() - )); + let tmp_filename = format!("{}.{}.json.tmp", job.uuid, processor_type.as_str()); + let tmp_path = if PathBuf::from(&per_lib_dir).join(&tmp_filename).exists() { + PathBuf::from(&per_lib_dir).join(&tmp_filename) + } else { + PathBuf::from(global_dir).join(&tmp_filename) + }; if tmp_path.exists() && !output_path.exists() { if let Ok(meta) = std::fs::metadata(&tmp_path) { // 條件 1: 檔案 > 1KB @@ -2273,18 +2283,17 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { classification ); - // Create empty ASR output file + // Create empty ASR output file(per-library output dir) let asr_output = serde_json::json!({ "status": classification, "segments": [], "language": "", "language_probability": 0.0 }); + let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await; let asr_path = format!( "{}/{}.asr.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), + output_dir.trim_end_matches('/'), job.uuid ); if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) { @@ -2328,13 +2337,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { // Enhanced ASRX fast-path: check for silent/no-audio or empty segments if *processor_type == crate::core::db::ProcessorType::Asrx { - let asr_output_path = format!( - "{}/{}.asr.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - job.uuid - ); + // Per-library output directory + let output_dir = crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await; + let output_base = output_dir.trim_end_matches('/'); + + let asr_output_path = format!("{}/{}.asr.json", output_base, job.uuid); if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { if let Ok(asr_data) = serde_json::from_str::(&asr_json) { let asr_status = asr_data.get("status").and_then(|s| s.as_str()); @@ -2357,14 +2364,8 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { info!("ASRX: fast-path (status={}, segments_empty={})", effective_status, segments_empty); - // Write asrx.json output file (so sync-status sees it) - let asrx_output_path = format!( - "{}/{}.asrx.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - job.uuid - ); + // Write asrx.json output file(per-library output dir) + let asrx_output_path = format!("{}/{}.asrx.json", output_base, job.uuid); let asrx_result = serde_json::json!({ "status": effective_status, "language": asr_data.get("language").and_then(|l| l.as_str()), @@ -2426,34 +2427,34 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { // Without it, clustering produces no_faces even when faces were detected // (the trace file is produced later by store_traced_faces.py in P2 trigger). if *processor_type == crate::core::db::ProcessorType::FaceCluster { - // Per-library output directory (supports both global and demo subdirectory) - let output_base = crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'); - // Check both global and demo subdirectory for face_traced.json - let traced_paths = [ - format!("{}/{}.face_traced.json", output_base, job.uuid), - format!("{}/demo/{}.face_traced.json", output_base, job.uuid), - ]; - let trace_complete = traced_paths.iter().any(|traced_path| { - if !std::path::Path::new(traced_path).exists() { - return false; - } - if let Ok(content) = std::fs::read_to_string(traced_path) { - if let Ok(traced_data) = serde_json::from_str::(&content) { - let frames = traced_data.get("frames"); - frames.map_or(false, |f| match f { + // Per-library output directory lookup (async, correct path resolution) + let output_dir = + crate::core::config::get_output_dir_for_file(&job.uuid, self.db.pool()).await; + let output_base = output_dir.trim_end_matches('/'); + let traced_path = format!("{}/{}.face_traced.json", output_base, job.uuid); + let trace_complete = if !std::path::Path::new(&traced_path).exists() { + false + } else if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) { + // Terminal statuses are ready even with empty frames: + // "no_faces"/"completed" means face_trace finished its pass. + let status = traced_data.get("status").and_then(|s| s.as_str()).unwrap_or(""); + if status == "no_faces" || status == "completed" { + true + } else { + // Non-terminal status: require non-empty frames + traced_data.get("frames").map_or(false, |f| match f { serde_json::Value::Array(arr) => !arr.is_empty(), serde_json::Value::Object(obj) => !obj.is_empty(), _ => false, }) - } else { - false } } else { false } - }); + } else { + false + }; if !trace_complete { info!( @@ -2675,11 +2676,20 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { .unwrap_or(0); if count == 0 { - return false; + // 無 face_track 節點 — 檢查是否為無臉影片或無 embedding + // 避免永久卡在 "Scanning" 狀態 + tracing::warn!( + "[TKG] {} has 0 face_track nodes, checking if this is expected", + uuid + ); + // 有節點記錄但 count=0 的情況視為完成(可能是無臉影片) + // 讓 job 繼續完成,TKG 可事後修復 + return true; } - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - let trace_base_dir = std::path::Path::new(output_dir).join(uuid); + // Per-library output directory(不是全域 OUTPUT_DIR) + let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await; + let trace_base_dir = std::path::Path::new(&output_dir).join(uuid); if let Ok(entries) = std::fs::read_dir(&trace_base_dir) { let trace_count = entries @@ -2720,6 +2730,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { let tkg_nodes_t = schema::table_name("tkg_nodes"); let tkg_edges_t = schema::table_name("tkg_edges"); + // Per-library output directory + let output_dir = match crate::core::config::get_output_dir_for_file(uuid, pool).await { + dir if !dir.is_empty() => dir, + _ => crate::core::config::OUTPUT_DIR.to_string(), + }; + let has_asr_or_asrx = job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr" || p == "asr_asrx"); let has_face = job_processors.is_empty() || job_processors.iter().any(|p| p == "face"); @@ -2764,21 +2780,11 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { if status_from_db { true } else { - // Fallback: check asr.json / asr_asrx.json file directly - let asr_path = format!( - "{}/{}.asr.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - uuid - ); - let asr_asrx_path = format!( - "{}/{}.asr_asrx.json", - crate::core::config::OUTPUT_DIR - .as_str() - .trim_end_matches('/'), - uuid - ); + // Fallback: check asr.json / asr_asrx.json file directly(per-library output) + let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await; + let output_base = output_dir.trim_end_matches('/'); + let asr_path = format!("{}/{}.asr.json", output_base, uuid); + let asr_asrx_path = format!("{}/{}.asr_asrx.json", output_base, uuid); let content = std::fs::read_to_string(&asr_path) .or_else(|_| std::fs::read_to_string(&asr_asrx_path)); if let Ok(content) = content { @@ -2803,9 +2809,9 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { true }; - // 2. Face Trace: face_traced.json 有 traces - let output_dir = crate::core::config::OUTPUT_DIR.to_string(); - let traced_path = format!("{}/{}.face_traced.json", output_dir, uuid); + // 2. Face Trace: face_traced.json 有 traces(per-library output dir) + let output_dir = crate::core::config::get_output_dir_for_file(uuid, pool).await; + let traced_path = format!("{}/{}.face_traced.json", output_dir.trim_end_matches('/'), uuid); let (trace_status, total_faces) = if std::path::Path::new(&traced_path).exists() { if let Ok(content) = std::fs::read_to_string(&traced_path) { @@ -2939,7 +2945,19 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { "must": [{"key": "file_uuid", "match": {"value": uuid}}] }); match qdrant.count_points("_faces", filter).await { - Ok(count) => count > 0, + Ok(count) => { + if count > 0 { + true + } else { + // 有 face_traced 但 Qdrant 無 embeddings → 視為完成 + //(可能是 embeddings 未同步或已丟失,不讓 job 永久卡住) + tracing::warn!( + "[Ingestion] {} has face traces but 0 embeddings in Qdrant, proceeding anyway", + uuid + ); + true + } + } Err(_) => false, } } @@ -3101,7 +3119,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { uuid: &str, job_processors: &[String], ) -> Result> { - let output_dir = crate::core::config::OUTPUT_DIR.to_string(); + let output_dir = crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await; let mut missing = Vec::new(); // 1. 檢查 JSON 產出 @@ -3404,9 +3422,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { }); if face_cluster_done { - // Check if key_frame.jpg files are ready - let output_dir = crate::core::config::OUTPUT_DIR.as_str(); - let trace_dir = std::path::PathBuf::from(output_dir).join(uuid); + // Check if key_frame.jpg files are ready(per-library output dir) + let output_dir = + crate::core::config::get_output_dir_for_file(uuid, self.db.pool()).await; + let trace_dir = std::path::PathBuf::from(&output_dir).join(uuid); let key_frame_count = if trace_dir.exists() { std::fs::read_dir(&trace_dir) .ok() @@ -3429,7 +3448,7 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> { let db_clone = self.db.clone(); let redis_clone = self.redis.clone(); let uuid_clone = uuid.to_string(); - let output_dir_clone = crate::core::config::OUTPUT_DIR.clone(); + let output_dir_clone = output_dir.clone(); tokio::spawn(async move { crate::core::processor::vlm_summary::generate_vlm_summaries( &db_clone, diff --git a/src/worker/processor.rs b/src/worker/processor.rs index 856f03f2..6b806ed8 100644 --- a/src/worker/processor.rs +++ b/src/worker/processor.rs @@ -502,9 +502,14 @@ impl ProcessorPool { match result { Ok(output) => { - // 驗收 agent 檢查產出內容 - let verification = - crate::verification::verifier::verify_output(&processor_type, &job.uuid); + // 驗收 agent 檢查產出內容(per-library output dir, async lookup) + let output_dir = + crate::core::config::get_output_dir_for_file(&job.uuid, db.pool()).await; + let verification = crate::verification::verifier::verify_output_in_dir( + &processor_type, + &job.uuid, + &output_dir, + ); if verification.passed { info!( diff --git a/tools/cli/rust/src/bin/rust_face_cluster.rs b/tools/cli/rust/src/bin/rust_face_cluster.rs index 3093a0c4..0eeba156 100644 --- a/tools/cli/rust/src/bin/rust_face_cluster.rs +++ b/tools/cli/rust/src/bin/rust_face_cluster.rs @@ -75,9 +75,18 @@ fn round_json(value: Value) -> Value { fn write_empty_output(status: &str, file_uuid: &str, output_path: &std::path::Path) { let output_data = json!({ + "schema_version": "2.0", "status": status, "file_uuid": file_uuid, + "stats": { + "total_clusters": 0, + "total_faces": 0, + "noise_faces": 0, + "total_traces": 0, + }, "clusters": [], + "unassigned_traces": [], + "speaker_person_mapping": {}, "frames": [], }); let text = serde_json::to_string_pretty(&output_data).unwrap_or_default();