From 524438689257ca1c00592ec10dc6930309f3dc0b Mon Sep 17 00:00:00 2001 From: Accusys Date: Sun, 2 Aug 2026 20:53:51 +0800 Subject: [PATCH] fix: executor output_idx corrupting --file-uuid arg in store_traced_faces.py The PythonExecutor.run() hardcoded output_idx=1, which treats args[1] as an output file path and rewrites it to .json.tmp. For scripts like store_traced_faces.py that use --file-uuid (not an output path) at position 1, this corrupted the UUID into a file path, causing the script to fail with exit status 1 within 90ms. - run_with_output_idx: output_idx changed from usize to Option - run_with_output_idx_and_frames: same change - run(): doc comment added, passes Some(1) for backward compatibility - job_worker.rs: store_traced_faces.py and release_pack.py calls now pass None for output_idx (no output path substitution) - appearance.rs: passes Some(2) explicitly (output at index 2) Verified: Gamma 8 file completed full pipeline with 24 face traces and 185 TKG nodes. --- src/core/processor/appearance.rs | 2 +- src/core/processor/executor.rs | 29 +- src/worker/job_worker.rs | 738 ++++++++++++++++++------------- 3 files changed, 463 insertions(+), 306 deletions(-) diff --git a/src/core/processor/appearance.rs b/src/core/processor/appearance.rs index b21238c8..604db630 100644 --- a/src/core/processor/appearance.rs +++ b/src/core/processor/appearance.rs @@ -90,7 +90,7 @@ pub async fn process_appearance( uuid, "APPEARANCE", Some(APPEARANCE_TIMEOUT), - 2, + Some(2), frames, ) .await diff --git a/src/core/processor/executor.rs b/src/core/processor/executor.rs index ea10a236..bde7c849 100644 --- a/src/core/processor/executor.rs +++ b/src/core/processor/executor.rs @@ -258,6 +258,9 @@ impl PythonExecutor { Ok(()) } + /// Run a Python script. `output_idx` specifies which arg index is the output + /// file path (rewritten to `.json.tmp` during execution, promoted on success). + /// Pass `None` if the script determines its own output path (e.g. from `--file-uuid`). pub async fn run( &self, script_name: &str, @@ -266,8 +269,15 @@ impl PythonExecutor { log_prefix: &str, timeout_duration: Option, ) -> Result<()> { - self.run_with_output_idx(script_name, args, uuid, log_prefix, timeout_duration, 1) - .await + self.run_with_output_idx( + script_name, + args, + uuid, + log_prefix, + timeout_duration, + Some(1), + ) + .await } /// Run a script with optional frame list for 8Hz sampling. @@ -430,7 +440,7 @@ impl PythonExecutor { uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, - output_idx: usize, + output_idx: Option, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); @@ -443,8 +453,8 @@ impl PythonExecutor { "Pre-execution integrity check failed — possible version mismatch or corruption", )?; - // 標記輸出檔為處理中(add .tmp suffix) - let output_path = args.get(output_idx).map(|p| std::path::PathBuf::from(p)); + let output_path = + output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); @@ -472,7 +482,7 @@ impl PythonExecutor { // Route the script's declared output path through a .tmp file so the // fresh result is written there and promoted to the real path only on // success (avoids clobbering good output with a stale/partial file). - if i == output_idx { + if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; @@ -623,7 +633,7 @@ impl PythonExecutor { uuid: Option<&str>, log_prefix: &str, timeout_duration: Option, - output_idx: usize, + output_idx: Option, frames: Option<&[i64]>, ) -> Result<()> { let script_path = self.scripts_dir.join(script_name); @@ -636,7 +646,8 @@ impl PythonExecutor { "Pre-execution integrity check failed — possible version mismatch or corruption", )?; - let output_path = args.get(output_idx).map(|p| std::path::PathBuf::from(p)); + let output_path = + output_idx.and_then(|idx| args.get(idx).map(|p| std::path::PathBuf::from(p))); let tmp_path = output_path.as_ref().map(|p| { let mut tmp = p.to_path_buf(); tmp.set_extension("json.tmp"); @@ -661,7 +672,7 @@ impl PythonExecutor { // Route the script's declared output path through a .tmp file so the // fresh result is written there and promoted to the real path only on // success (avoids clobbering good output with a stale/partial file). - if i == output_idx { + if Some(i) == output_idx { if let Some(ref tmp) = tmp_path { cmd.arg(tmp); continue; diff --git a/src/worker/job_worker.rs b/src/worker/job_worker.rs index dc256430..49441953 100644 --- a/src/worker/job_worker.rs +++ b/src/worker/job_worker.rs @@ -817,19 +817,23 @@ impl JobWorker { .await; } } - + // Extract key frames from each scene for VLM analysis - if let Some(video_row) = self.db.get_video_by_uuid(&job.uuid).await.ok().flatten() { + if let Some(video_row) = + self.db.get_video_by_uuid(&job.uuid).await.ok().flatten() + { let output_dir = crate::core::config::OUTPUT_DIR.as_str(); if let Err(e) = crate::core::proxy::extract_cut_key_frames( &job.uuid, &video_row.file_path, output_dir, - ).await { + ) + .await + { error!("Failed to extract cut key frames: {}", e); } } - + Ok(()) } else { error!( @@ -1151,9 +1155,15 @@ impl JobWorker { .flatten(); if let Some(ref classification) = audio_track { - if matches!(classification.as_str(), "no_audio" | "silent_audio" | "music_only") { - info!("ASR: audio_track={}, creating empty ASR output", classification); - + if matches!( + classification.as_str(), + "no_audio" | "silent_audio" | "music_only" + ) { + info!( + "ASR: audio_track={}, creating empty ASR output", + classification + ); + // Create empty ASR output file let asr_output = serde_json::json!({ "status": classification, @@ -1163,13 +1173,15 @@ impl JobWorker { }); let asr_path = format!( "{}/{}.asr.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), job.uuid ); if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) { error!("Failed to write empty ASR output: {}", e); } - + // Mark as completed if let Err(e) = self .db @@ -1183,7 +1195,7 @@ impl JobWorker { { error!("Failed to create ASR result: {}", e); } - + let _ = self .redis .update_worker_processor_status( @@ -1198,7 +1210,7 @@ impl JobWorker { 0, ) .await; - + started_count += 1; continue; } @@ -1209,7 +1221,9 @@ impl JobWorker { 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('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), job.uuid ); if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { @@ -1222,7 +1236,9 @@ impl JobWorker { // 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('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), job.uuid ); let asrx_result = serde_json::json!({ @@ -1231,7 +1247,10 @@ impl JobWorker { "segments": [], "segment_count": 0 }); - if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) { + if let Err(e) = std::fs::write( + &asrx_output_path, + serde_json::to_string_pretty(&asrx_result).unwrap_or_default(), + ) { warn!("Failed to write ASRX output file: {}", e); } @@ -1542,17 +1561,20 @@ impl JobWorker { // Fallback: check asr.json file directly let asr_path = format!( "{}/{}.asr.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); if let Ok(content) = std::fs::read_to_string(&asr_path) { if let Ok(data) = serde_json::from_str::(&content) { match data.get("status").and_then(|s| s.as_str()) { Some("no_audio_track") | Some("silent_audio") => true, - Some("has_transcript") => { - data.get("segments").and_then(|s| s.as_array()) - .map(|a| !a.is_empty()).unwrap_or(false) - } + Some("has_transcript") => data + .get("segments") + .and_then(|s| s.as_array()) + .map(|a| !a.is_empty()) + .unwrap_or(false), _ => false, } } else { @@ -1574,7 +1596,11 @@ impl JobWorker { let trace_status = if std::path::Path::new(&traced_path).exists() { if let Ok(content) = std::fs::read_to_string(&traced_path) { if let Ok(traced_data) = serde_json::from_str::(&content) { - traced_data.get("status").and_then(|s| s.as_str()).unwrap_or("").to_string() + traced_data + .get("status") + .and_then(|s| s.as_str()) + .unwrap_or("") + .to_string() } else { "".to_string() } @@ -1635,7 +1661,10 @@ impl JobWorker { "clusters": [], "frames": [] }); - let _ = std::fs::write(&cluster_path, serde_json::to_string_pretty(&empty_output).unwrap_or_default()); + let _ = std::fs::write( + &cluster_path, + serde_json::to_string_pretty(&empty_output).unwrap_or_default(), + ); } true } else { @@ -1655,7 +1684,8 @@ impl JobWorker { .fetch_optional(pool) .await .unwrap_or(None) - .unwrap_or(0) > 0 + .unwrap_or(0) + > 0 } else { true }; @@ -1839,7 +1869,9 @@ impl JobWorker { 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('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { @@ -1855,7 +1887,9 @@ impl JobWorker { // 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('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); let asrx_result = serde_json::json!({ @@ -1864,7 +1898,10 @@ impl JobWorker { "segments": [], "segment_count": 0 }); - if let Err(e) = std::fs::write(&asrx_output_path, serde_json::to_string_pretty(&asrx_result).unwrap_or_default()) { + if let Err(e) = std::fs::write( + &asrx_output_path, + serde_json::to_string_pretty(&asrx_result).unwrap_or_default(), + ) { warn!("Failed to write ASRX output file: {}", e); } @@ -2063,12 +2100,13 @@ impl JobWorker { } }; match executor - .run( + .run_with_output_idx( "release_pack.py", &["--phase", "1", "--file-uuid", &uuid_clone], None, "RELEASE_P1", Some(std::time::Duration::from_secs(120)), + None, ) .await { @@ -2078,7 +2116,10 @@ impl JobWorker { // Note: Job status will be updated after Rule 2 (TKG) completion // Do not mark as completed here } - Err(e) => warn!("⚠️ Phase 1 release pack failed (non-fatal): {}", e), + Err(e) => warn!( + "⚠️ Phase 1 release pack failed (non-fatal): {}", + e + ), } } Err(e) => error!("❌ Rule 1 Ingestion failed: {}", e), @@ -2101,7 +2142,9 @@ impl JobWorker { if has_face { let traced_path = format!( "{}/{}.face_traced.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); if std::path::Path::new(&traced_path).exists() { @@ -2111,7 +2154,10 @@ impl JobWorker { // cycles (race before face_traced.json is written). let mut inflight = FACE_TRACE_INFLIGHT.lock().await; if inflight.contains(uuid) { - info!("⏳ Face trace already in-flight for {}, skipping duplicate spawn", uuid); + info!( + "⏳ Face trace already in-flight for {}, skipping duplicate spawn", + uuid + ); } else { inflight.insert(uuid.to_string()); drop(inflight); @@ -2132,108 +2178,117 @@ impl JobWorker { }; // Mark face_tracing as running { - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage("face_tracing", 0.0, "running", None); - publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; - } - let executor = match crate::core::processor::PythonExecutor::new() { - Ok(ex) => ex, - Err(e) => { - error!("Failed to create PythonExecutor for face trace: {}", e); - FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); - return; + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage("face_tracing", 0.0, "running", None); + publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp) + .await; } - }; - match executor - .run( - "store_traced_faces.py", - &["--file-uuid", &uuid_clone], - Some(&uuid_clone), - "TRACE_STORE", - Some(std::time::Duration::from_secs(600)), - ) - .await - { - Ok(()) => { - info!("✅ Face trace + DB store completed for {}", uuid_clone); + let executor = match crate::core::processor::PythonExecutor::new() { + Ok(ex) => ex, + Err(e) => { + error!("Failed to create PythonExecutor for face trace: {}", e); + FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); + return; + } + }; + match executor + .run_with_output_idx( + "store_traced_faces.py", + &["--file-uuid", &uuid_clone], + Some(&uuid_clone), + "TRACE_STORE", + Some(std::time::Duration::from_secs(600)), + None, + ) + .await + { + Ok(()) => { + info!("✅ Face trace + DB store completed for {}", uuid_clone); - // Query trace count and distribution - let trace_count = - match db_clone.get_trace_count_by_file(&uuid_clone).await { - Ok(c) => c, + // Query trace count and distribution + let trace_count = + match db_clone.get_trace_count_by_file(&uuid_clone).await { + Ok(c) => c, + Err(e) => { + error!( + "Failed to get trace count for {}: {}", + uuid_clone, e + ); + 0 + } + }; + + let (single_frame, multi_frame) = match db_clone + .get_trace_frame_count_distribution(&uuid_clone) + .await + { + Ok(dist) => dist, Err(e) => { error!( - "Failed to get trace count for {}: {}", + "Failed to get trace distribution for {}: {}", uuid_clone, e ); - 0 + (0, 0) } }; - let (single_frame, multi_frame) = match db_clone - .get_trace_frame_count_distribution(&uuid_clone) - .await - { - Ok(dist) => dist, - Err(e) => { - error!( - "Failed to get trace distribution for {}: {}", - uuid_clone, e + let trace_status = + crate::core::processor::TraceStatus::from_trace_count( + trace_count, ); - (0, 0) - } - }; - - let trace_status = - crate::core::processor::TraceStatus::from_trace_count( - trace_count, - ); - info!( + info!( "📊 Trace status: {} (total={}, single_frame={}, multi_frame={}) for {}", trace_status, trace_count, single_frame, multi_frame, uuid_clone ); - // Update processor_results trace_status for Face - if let Err(e) = db_clone - .update_trace_status_for_face( - &uuid_clone, - &trace_status, - trace_count, - single_frame, - multi_frame, - ) - .await - { - error!( - "Failed to update trace_status for {}: {}", - uuid_clone, e - ); - } + // Update processor_results trace_status for Face + if let Err(e) = db_clone + .update_trace_status_for_face( + &uuid_clone, + &trace_status, + trace_count, + single_frame, + multi_frame, + ) + .await + { + error!( + "Failed to update trace_status for {}: {}", + uuid_clone, e + ); + } - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage( - "face_tracing", - 1.0, - "completed", - Some(format!( - "{} traces ({} single, {} multi)", - trace_count, single_frame, multi_frame - )), - ); - publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp) + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage( + "face_tracing", + 1.0, + "completed", + Some(format!( + "{} traces ({} single, {} multi)", + trace_count, single_frame, multi_frame + )), + ); + publish_pipeline_progress( + redis_clone.as_ref(), + &uuid_clone, + &pp, + ) .await; + } + Err(e) => { + error!( + "❌ Face trace + DB store failed for {}: {}", + uuid_clone, e + ) + } } - Err(e) => { - error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e) - } - } - // Clear in-flight marker so this uuid can be retried later - // if it failed or the worker restarts before completion. - FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); - }); + // Clear in-flight marker so this uuid can be retried later + // if it failed or the worker restarts before completion. + FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone); + }); + } } } - } // 🚀 P2.5 Trigger: TMDb Face Matching (after Face, if TMDb data exists) if has_face && *crate::core::config::tmdb::PROBE_ENABLED { @@ -2335,8 +2390,72 @@ impl JobWorker { } // 🚀 P3 Trigger: Face Deduplication (Face Cluster → TKG face_track sync) + // Before running dedup, verify all 4 required files exist per trace: + // key_frame.jpg, key_face.jpg, trace_profile.json, face_traced.json if has_face { let output_dir = OUTPUT_DIR.as_str(); + let output_base = output_dir.trim_end_matches('/'); + let traced_path = format!("{}/{}.face_traced.json", output_base, uuid); + + // Check face_traced.json exists + if !std::path::Path::new(&traced_path).exists() { + info!( + "📝 Face dedup waiting: face_traced.json not yet ready for {}", + uuid + ); + } else { + // Verify trace profiles have required files (sample check) + if let Ok(content) = std::fs::read_to_string(&traced_path) { + if let Ok(traced_data) = serde_json::from_str::(&content) + { + if let Some(traces) = traced_data.get("traces") { + let trace_ids: Vec = if traces.is_object() { + traces + .as_object() + .map(|o| o.keys().filter_map(|k| k.parse().ok()).collect()) + .unwrap_or_default() + } else if traces.is_array() { + traces + .as_array() + .map(|a| { + a.iter() + .filter_map(|v| { + v.get("trace_id").and_then(|t| t.as_i64()) + }) + .collect() + }) + .unwrap_or_default() + } else { + vec![] + }; + + // Sample first 5 traces to verify required files + let sample_size = trace_ids.len().min(5); + let mut missing_count = 0; + for &tid in trace_ids.iter().take(sample_size) { + let trace_dir = + crate::core::file_profile::FaceTraceProfile::trace_dir( + output_dir, &uuid, tid, + ); + if !trace_dir.join("key_frame.jpg").exists() { + missing_count += 1; + } + if !trace_dir.join("key_face.jpg").exists() { + missing_count += 1; + } + if !trace_dir.join("trace_profile.json").exists() { + missing_count += 1; + } + } + + if missing_count > 0 { + info!("📝 Face dedup waiting: {} missing files in trace sample for {} (TKG may still be building)", missing_count, uuid); + } + } + } + } + } + let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid); if std::path::Path::new(&face_cluster_path).exists() { // Check if face_cluster data is consistent with tkg_nodes @@ -2351,16 +2470,25 @@ impl JobWorker { .unwrap_or(0); if let Ok(content) = std::fs::read_to_string(&face_cluster_path) { - if let Ok(cluster_data) = serde_json::from_str::(&content) { - let cluster_count = cluster_data.get("clusters") + if let Ok(cluster_data) = + serde_json::from_str::(&content) + { + let cluster_count = cluster_data + .get("clusters") .and_then(|c| c.as_array()) .map(|a| a.len() as i64) .unwrap_or(0); if face_track_count == cluster_count { - info!("✅ Face dedup consistent for {}: {} clusters = {} tracks", uuid, cluster_count, face_track_count); + info!( + "✅ Face dedup consistent for {}: {} clusters = {} tracks", + uuid, cluster_count, face_track_count + ); } else { - info!("📝 Face dedup running for {}: {} clusters, {} tracks", uuid, cluster_count, face_track_count); + info!( + "📝 Face dedup running for {}: {} clusters, {} tracks", + uuid, cluster_count, face_track_count + ); } } } @@ -2374,15 +2502,15 @@ impl JobWorker { // Check face.json status first to determine TKG type let face_json_path = format!( "{}/{}.face.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); let has_faces = if std::path::Path::new(&face_json_path).exists() { if let Ok(content) = std::fs::read_to_string(&face_json_path) { - if let Ok(face_data) = - serde_json::from_str::(&content) - { + if let Ok(face_data) = serde_json::from_str::(&content) { face_data .get("status") .and_then(|s| s.as_str()) @@ -2412,7 +2540,9 @@ impl JobWorker { // Has faces - wait for face_traced.json let traced_path = format!( "{}/{}.face_traced.json", - crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), + crate::core::config::OUTPUT_DIR + .as_str() + .trim_end_matches('/'), uuid ); @@ -2439,168 +2569,45 @@ impl JobWorker { 0 }; - // Wait for Qdrant to have all face points (up to 30 seconds) - let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); - let mut attempts = 0; - let max_attempts = 30; - loop { - match qdrant - .count_points( - "_faces", - serde_json::json!({ - "must": [{"key": "file_uuid", "match": {"value": uuid}}] - }), - ) - .await - { - Ok(count) if count >= expected_faces && expected_faces > 0 => { - info!("📝 Prerequisites met for TKG Build (Qdrant has {} faces, expected {}): {}", - count, expected_faces, uuid); - break; - } - Ok(count) => { - attempts += 1; - if attempts >= max_attempts { - warn!("⚠️ TKG build proceeding with {} faces (expected {}) after 30s wait: {}", - count, expected_faces, uuid); - break; - } - debug!( - "⏳ TKG waiting for Qdrant ({} of {} faces): {}", - count, expected_faces, uuid - ); - } - Err(e) => { - warn!("Qdrant count failed: {}, proceeding anyway", e); - break; - } - } - tokio::time::sleep(std::time::Duration::from_secs(1)).await; - } - - 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(); - tokio::spawn(async move { - // Bound concurrent heavy face-I/O Python tasks to avoid OOM - // (build_tkg may internally spawn store_traced_faces.py). - let _face_io_permit = match FACE_IO_SEM.acquire().await { - Ok(p) => p, - Err(_) => { - error!("❌ TKG build semaphore closed for {}", uuid_clone); - return; - } - }; - // Mark tkg_nodes + tkg_edges as running - { - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage("tkg_nodes", 0.0, "running", None); - pp.update_stage("tkg_edges", 0.0, "running", None); - publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; - } - match crate::core::processor::tkg::build_tkg( - &db_clone, - &uuid_clone, - &output_dir_clone, - Some(redis_clone.clone()), + // Wait for Qdrant to have all face points (up to 30 seconds) + let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); + let mut attempts = 0; + let max_attempts = 30; + loop { + match qdrant + .count_points( + "_faces", + serde_json::json!({ + "must": [{"key": "file_uuid", "match": {"value": uuid}}] + }), ) .await - { - Ok(r) => { - let total_nodes = r.face_track_nodes - + r.gaze_track_nodes - + r.lip_track_nodes - + r.text_region_nodes - + r.appearance_trace_nodes - + r.accessory_nodes - + r.object_nodes - + r.hand_nodes - + r.speaker_nodes; - let total_edges = r.co_occurrence_edges - + r.speaker_face_edges - + r.face_face_edges - + r.mutual_gaze_edges - + r.lip_sync_edges - + r.has_appearance_edges - + r.wears_edges - + r.hand_object_edges; - info!( - "✅ TKG build completed for {}: {} nodes, {} edges", - uuid_clone, total_nodes, total_edges - ); - - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage( - "tkg_nodes", - 1.0, - "completed", - Some(format!("{} nodes", total_nodes)), - ); - pp.update_stage( - "tkg_edges", - 1.0, - "completed", - Some(format!("{} edges", total_edges)), - ); - publish_pipeline_progress( - redis_clone.as_ref(), - &uuid_clone, - &pp, - ) - .await; - - // Trigger Rule 2 ingestion after TKG complete - if total_edges > 0 { - // Mark rule2_ingestion as running - { - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage("rule2_ingestion", 0.0, "running", None); - publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; - } - match crate::core::chunk::rule2_ingest::ingest_rule2( - db_clone.pool(), - &uuid_clone, - None, - None, - ) - .await - { - Ok(rule2_count) => { - info!("✅ Rule 2 ingestion completed for {}: {} relationship chunks", uuid_clone, rule2_count); - let mut pp = PipelineProgress::new(&uuid_clone); - pp.update_stage( - "rule2_ingestion", - 1.0, - "completed", - Some(format!("{} chunks", rule2_count)), - ); - publish_pipeline_progress( - redis_clone.as_ref(), - &uuid_clone, - &pp, - ) - .await; - } - Err(e) => error!( - "❌ Rule 2 ingestion failed for {}: {}", - uuid_clone, e - ), - } - } - } - Err(e) => { - error!("❌ TKG build failed for {}: {}", uuid_clone, e) - } + { + Ok(count) if count >= expected_faces && expected_faces > 0 => { + info!("📝 Prerequisites met for TKG Build (Qdrant has {} faces, expected {}): {}", + count, expected_faces, uuid); + break; } - }); + Ok(count) => { + attempts += 1; + if attempts >= max_attempts { + warn!("⚠️ TKG build proceeding with {} faces (expected {}) after 30s wait: {}", + count, expected_faces, uuid); + break; + } + debug!( + "⏳ TKG waiting for Qdrant ({} of {} faces): {}", + count, expected_faces, uuid + ); + } + Err(e) => { + warn!("Qdrant count failed: {}, proceeding anyway", e); + break; + } + } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; } - } else { - // No faces detected - spawn TKG without waiting for face_traced.json - info!( - "📝 TKG Build proceeding without face_traced.json (no faces detected): {}", - uuid - ); + let db_clone = self.db.clone(); let redis_clone = self.redis.clone(); let uuid_clone = uuid.to_string(); @@ -2611,16 +2618,17 @@ impl JobWorker { let _face_io_permit = match FACE_IO_SEM.acquire().await { Ok(p) => p, Err(_) => { - error!("❌ TKG build (no-faces) semaphore closed for {}", uuid_clone); + error!("❌ TKG build semaphore closed for {}", uuid_clone); return; } }; - // Mark tkg_nodes + tkg_edges as running (no-faces path) + // Mark tkg_nodes + tkg_edges as running { let mut pp = PipelineProgress::new(&uuid_clone); pp.update_stage("tkg_nodes", 0.0, "running", None); pp.update_stage("tkg_edges", 0.0, "running", None); - publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; + publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp) + .await; } match crate::core::processor::tkg::build_tkg( &db_clone, @@ -2649,11 +2657,10 @@ impl JobWorker { + r.wears_edges + r.hand_object_edges; info!( - "✅ TKG build completed (no faces) for {}: {} nodes, {} edges", + "✅ TKG build completed for {}: {} nodes, {} edges", uuid_clone, total_nodes, total_edges ); - // Update progress for no-faces case let mut pp = PipelineProgress::new(&uuid_clone); pp.update_stage( "tkg_nodes", @@ -2673,11 +2680,144 @@ impl JobWorker { &pp, ) .await; + + // Trigger Rule 2 ingestion after TKG complete + if total_edges > 0 { + // Mark rule2_ingestion as running + { + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage( + "rule2_ingestion", + 0.0, + "running", + None, + ); + publish_pipeline_progress( + redis_clone.as_ref(), + &uuid_clone, + &pp, + ) + .await; + } + match crate::core::chunk::rule2_ingest::ingest_rule2( + db_clone.pool(), + &uuid_clone, + None, + None, + ) + .await + { + Ok(rule2_count) => { + info!("✅ Rule 2 ingestion completed for {}: {} relationship chunks", uuid_clone, rule2_count); + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage( + "rule2_ingestion", + 1.0, + "completed", + Some(format!("{} chunks", rule2_count)), + ); + publish_pipeline_progress( + redis_clone.as_ref(), + &uuid_clone, + &pp, + ) + .await; + } + Err(e) => error!( + "❌ Rule 2 ingestion failed for {}: {}", + uuid_clone, e + ), + } + } + } + Err(e) => { + error!("❌ TKG build failed for {}: {}", uuid_clone, e) } - Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e), } }); } + } else { + // No faces detected - spawn TKG without waiting for face_traced.json + info!( + "📝 TKG Build proceeding without face_traced.json (no faces detected): {}", + uuid + ); + 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(); + tokio::spawn(async move { + // Bound concurrent heavy face-I/O Python tasks to avoid OOM + // (build_tkg may internally spawn store_traced_faces.py). + let _face_io_permit = match FACE_IO_SEM.acquire().await { + Ok(p) => p, + Err(_) => { + error!( + "❌ TKG build (no-faces) semaphore closed for {}", + uuid_clone + ); + return; + } + }; + // Mark tkg_nodes + tkg_edges as running (no-faces path) + { + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage("tkg_nodes", 0.0, "running", None); + pp.update_stage("tkg_edges", 0.0, "running", None); + publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; + } + match crate::core::processor::tkg::build_tkg( + &db_clone, + &uuid_clone, + &output_dir_clone, + Some(redis_clone.clone()), + ) + .await + { + Ok(r) => { + let total_nodes = r.face_track_nodes + + r.gaze_track_nodes + + r.lip_track_nodes + + r.text_region_nodes + + r.appearance_trace_nodes + + r.accessory_nodes + + r.object_nodes + + r.hand_nodes + + r.speaker_nodes; + let total_edges = r.co_occurrence_edges + + r.speaker_face_edges + + r.face_face_edges + + r.mutual_gaze_edges + + r.lip_sync_edges + + r.has_appearance_edges + + r.wears_edges + + r.hand_object_edges; + info!( + "✅ TKG build completed (no faces) for {}: {} nodes, {} edges", + uuid_clone, total_nodes, total_edges + ); + + // Update progress for no-faces case + let mut pp = PipelineProgress::new(&uuid_clone); + pp.update_stage( + "tkg_nodes", + 1.0, + "completed", + Some(format!("{} nodes", total_nodes)), + ); + pp.update_stage( + "tkg_edges", + 1.0, + "completed", + Some(format!("{} edges", total_edges)), + ); + publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp) + .await; + } + Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e), + } + }); + } } if !Self::ingestion_complete(self.db.pool(), uuid, job_processors).await { @@ -2955,7 +3095,11 @@ impl JobWorker { // Build index: (frame, face_index) → real trace_id from face_traced.json // face_cluster.json's trace_id is cluster-internal (always 0), so we match // by frame number + array index to get the actual traced trace_id. - let traced_path = format!("{}/{}.face_traced.json", crate::core::config::OUTPUT_DIR.as_str(), uuid); + let traced_path = format!( + "{}/{}.face_traced.json", + crate::core::config::OUTPUT_DIR.as_str(), + uuid + ); let mut frame_face_to_trace: HashMap<(u64, usize), i64> = HashMap::new(); if let Ok(content) = std::fs::read_to_string(&traced_path) { if let Ok(traced_data) = serde_json::from_str::(&content) { @@ -3019,14 +3163,8 @@ impl JobWorker { } // Sync name to trace_profiles - let _ = schema::upsert_trace_profile( - db.pool(), - uuid, - *trace_id as i32, - &label, - None, - ) - .await; + let _ = + schema::upsert_trace_profile(db.pool(), uuid, *trace_id as i32, &label, None).await; } // Also update traces that are NOT in any cluster (keep default Person_N name) @@ -3034,9 +3172,17 @@ impl JobWorker { if let Ok(traced_data) = serde_json::from_str::(&content) { if let Some(traces) = traced_data.get("traces") { let trace_list = if traces.is_object() { - traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::().ok()).collect::>()) + traces.as_object().map(|o| { + o.keys() + .filter_map(|k| k.parse::().ok()) + .collect::>() + }) } else if traces.is_array() { - traces.as_array().map(|a| a.iter().filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())).collect()) + traces.as_array().map(|a| { + a.iter() + .filter_map(|v| v.get("trace_id").and_then(|t| t.as_i64())) + .collect() + }) } else { None };