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<usize>
- 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.
This commit is contained in:
Accusys
2026-08-02 20:53:51 +08:00
parent e22393d577
commit 5244386892
3 changed files with 463 additions and 306 deletions
+1 -1
View File
@@ -90,7 +90,7 @@ pub async fn process_appearance(
uuid, uuid,
"APPEARANCE", "APPEARANCE",
Some(APPEARANCE_TIMEOUT), Some(APPEARANCE_TIMEOUT),
2, Some(2),
frames, frames,
) )
.await .await
+20 -9
View File
@@ -258,6 +258,9 @@ impl PythonExecutor {
Ok(()) 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( pub async fn run(
&self, &self,
script_name: &str, script_name: &str,
@@ -266,8 +269,15 @@ impl PythonExecutor {
log_prefix: &str, log_prefix: &str,
timeout_duration: Option<Duration>, timeout_duration: Option<Duration>,
) -> Result<()> { ) -> Result<()> {
self.run_with_output_idx(script_name, args, uuid, log_prefix, timeout_duration, 1) self.run_with_output_idx(
.await script_name,
args,
uuid,
log_prefix,
timeout_duration,
Some(1),
)
.await
} }
/// Run a script with optional frame list for 8Hz sampling. /// Run a script with optional frame list for 8Hz sampling.
@@ -430,7 +440,7 @@ impl PythonExecutor {
uuid: Option<&str>, uuid: Option<&str>,
log_prefix: &str, log_prefix: &str,
timeout_duration: Option<Duration>, timeout_duration: Option<Duration>,
output_idx: usize, output_idx: Option<usize>,
) -> Result<()> { ) -> Result<()> {
let script_path = self.scripts_dir.join(script_name); 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", "Pre-execution integrity check failed — possible version mismatch or corruption",
)?; )?;
// 標記輸出檔為處理中(add .tmp suffix) let output_path =
let output_path = args.get(output_idx).map(|p| std::path::PathBuf::from(p)); 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 tmp_path = output_path.as_ref().map(|p| {
let mut tmp = p.to_path_buf(); let mut tmp = p.to_path_buf();
tmp.set_extension("json.tmp"); tmp.set_extension("json.tmp");
@@ -472,7 +482,7 @@ impl PythonExecutor {
// Route the script's declared output path through a .tmp file so the // 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 // fresh result is written there and promoted to the real path only on
// success (avoids clobbering good output with a stale/partial file). // 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 { if let Some(ref tmp) = tmp_path {
cmd.arg(tmp); cmd.arg(tmp);
continue; continue;
@@ -623,7 +633,7 @@ impl PythonExecutor {
uuid: Option<&str>, uuid: Option<&str>,
log_prefix: &str, log_prefix: &str,
timeout_duration: Option<Duration>, timeout_duration: Option<Duration>,
output_idx: usize, output_idx: Option<usize>,
frames: Option<&[i64]>, frames: Option<&[i64]>,
) -> Result<()> { ) -> Result<()> {
let script_path = self.scripts_dir.join(script_name); 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", "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 tmp_path = output_path.as_ref().map(|p| {
let mut tmp = p.to_path_buf(); let mut tmp = p.to_path_buf();
tmp.set_extension("json.tmp"); tmp.set_extension("json.tmp");
@@ -661,7 +672,7 @@ impl PythonExecutor {
// Route the script's declared output path through a .tmp file so the // 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 // fresh result is written there and promoted to the real path only on
// success (avoids clobbering good output with a stale/partial file). // 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 { if let Some(ref tmp) = tmp_path {
cmd.arg(tmp); cmd.arg(tmp);
continue; continue;
+436 -290
View File
@@ -819,13 +819,17 @@ impl JobWorker {
} }
// Extract key frames from each scene for VLM analysis // 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(); let output_dir = crate::core::config::OUTPUT_DIR.as_str();
if let Err(e) = crate::core::proxy::extract_cut_key_frames( if let Err(e) = crate::core::proxy::extract_cut_key_frames(
&job.uuid, &job.uuid,
&video_row.file_path, &video_row.file_path,
output_dir, output_dir,
).await { )
.await
{
error!("Failed to extract cut key frames: {}", e); error!("Failed to extract cut key frames: {}", e);
} }
} }
@@ -1151,8 +1155,14 @@ impl JobWorker {
.flatten(); .flatten();
if let Some(ref classification) = audio_track { if let Some(ref classification) = audio_track {
if matches!(classification.as_str(), "no_audio" | "silent_audio" | "music_only") { if matches!(
info!("ASR: audio_track={}, creating empty ASR output", classification); classification.as_str(),
"no_audio" | "silent_audio" | "music_only"
) {
info!(
"ASR: audio_track={}, creating empty ASR output",
classification
);
// Create empty ASR output file // Create empty ASR output file
let asr_output = serde_json::json!({ let asr_output = serde_json::json!({
@@ -1163,7 +1173,9 @@ impl JobWorker {
}); });
let asr_path = format!( let asr_path = format!(
"{}/{}.asr.json", "{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid job.uuid
); );
if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) { if let Err(e) = std::fs::write(&asr_path, asr_output.to_string()) {
@@ -1209,7 +1221,9 @@ impl JobWorker {
if *processor_type == crate::core::db::ProcessorType::Asrx { if *processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!( let asr_output_path = format!(
"{}/{}.asr.json", "{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid job.uuid
); );
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { 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) // Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!( let asrx_output_path = format!(
"{}/{}.asrx.json", "{}/{}.asrx.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
job.uuid job.uuid
); );
let asrx_result = serde_json::json!({ let asrx_result = serde_json::json!({
@@ -1231,7 +1247,10 @@ impl JobWorker {
"segments": [], "segments": [],
"segment_count": 0 "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); warn!("Failed to write ASRX output file: {}", e);
} }
@@ -1542,17 +1561,20 @@ impl JobWorker {
// Fallback: check asr.json file directly // Fallback: check asr.json file directly
let asr_path = format!( let asr_path = format!(
"{}/{}.asr.json", "{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
if let Ok(content) = std::fs::read_to_string(&asr_path) { if let Ok(content) = std::fs::read_to_string(&asr_path) {
if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) { if let Ok(data) = serde_json::from_str::<serde_json::Value>(&content) {
match data.get("status").and_then(|s| s.as_str()) { match data.get("status").and_then(|s| s.as_str()) {
Some("no_audio_track") | Some("silent_audio") => true, Some("no_audio_track") | Some("silent_audio") => true,
Some("has_transcript") => { Some("has_transcript") => data
data.get("segments").and_then(|s| s.as_array()) .get("segments")
.map(|a| !a.is_empty()).unwrap_or(false) .and_then(|s| s.as_array())
} .map(|a| !a.is_empty())
.unwrap_or(false),
_ => false, _ => false,
} }
} else { } else {
@@ -1574,7 +1596,11 @@ impl JobWorker {
let trace_status = if std::path::Path::new(&traced_path).exists() { 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(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) { if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&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 { } else {
"".to_string() "".to_string()
} }
@@ -1635,7 +1661,10 @@ impl JobWorker {
"clusters": [], "clusters": [],
"frames": [] "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 true
} else { } else {
@@ -1655,7 +1684,8 @@ impl JobWorker {
.fetch_optional(pool) .fetch_optional(pool)
.await .await
.unwrap_or(None) .unwrap_or(None)
.unwrap_or(0) > 0 .unwrap_or(0)
> 0
} else { } else {
true true
}; };
@@ -1839,7 +1869,9 @@ impl JobWorker {
if processor_type == crate::core::db::ProcessorType::Asrx { if processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!( let asr_output_path = format!(
"{}/{}.asr.json", "{}/{}.asr.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) { 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) // Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!( let asrx_output_path = format!(
"{}/{}.asrx.json", "{}/{}.asrx.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
let asrx_result = serde_json::json!({ let asrx_result = serde_json::json!({
@@ -1864,7 +1898,10 @@ impl JobWorker {
"segments": [], "segments": [],
"segment_count": 0 "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); warn!("Failed to write ASRX output file: {}", e);
} }
@@ -2063,12 +2100,13 @@ impl JobWorker {
} }
}; };
match executor match executor
.run( .run_with_output_idx(
"release_pack.py", "release_pack.py",
&["--phase", "1", "--file-uuid", &uuid_clone], &["--phase", "1", "--file-uuid", &uuid_clone],
None, None,
"RELEASE_P1", "RELEASE_P1",
Some(std::time::Duration::from_secs(120)), Some(std::time::Duration::from_secs(120)),
None,
) )
.await .await
{ {
@@ -2078,7 +2116,10 @@ impl JobWorker {
// Note: Job status will be updated after Rule 2 (TKG) completion // Note: Job status will be updated after Rule 2 (TKG) completion
// Do not mark as completed here // 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), Err(e) => error!("❌ Rule 1 Ingestion failed: {}", e),
@@ -2101,7 +2142,9 @@ impl JobWorker {
if has_face { if has_face {
let traced_path = format!( let traced_path = format!(
"{}/{}.face_traced.json", "{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
if std::path::Path::new(&traced_path).exists() { if std::path::Path::new(&traced_path).exists() {
@@ -2111,7 +2154,10 @@ impl JobWorker {
// cycles (race before face_traced.json is written). // cycles (race before face_traced.json is written).
let mut inflight = FACE_TRACE_INFLIGHT.lock().await; let mut inflight = FACE_TRACE_INFLIGHT.lock().await;
if inflight.contains(uuid) { 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 { } else {
inflight.insert(uuid.to_string()); inflight.insert(uuid.to_string());
drop(inflight); drop(inflight);
@@ -2132,108 +2178,117 @@ impl JobWorker {
}; };
// Mark face_tracing as running // Mark face_tracing as running
{ {
let mut pp = PipelineProgress::new(&uuid_clone); let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage("face_tracing", 0.0, "running", None); pp.update_stage("face_tracing", 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;
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 executor = match crate::core::processor::PythonExecutor::new() {
match executor Ok(ex) => ex,
.run( Err(e) => {
"store_traced_faces.py", error!("Failed to create PythonExecutor for face trace: {}", e);
&["--file-uuid", &uuid_clone], FACE_TRACE_INFLIGHT.lock().await.remove(&uuid_clone);
Some(&uuid_clone), return;
"TRACE_STORE", }
Some(std::time::Duration::from_secs(600)), };
) match executor
.await .run_with_output_idx(
{ "store_traced_faces.py",
Ok(()) => { &["--file-uuid", &uuid_clone],
info!("✅ Face trace + DB store completed for {}", 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 // Query trace count and distribution
let trace_count = let trace_count =
match db_clone.get_trace_count_by_file(&uuid_clone).await { match db_clone.get_trace_count_by_file(&uuid_clone).await {
Ok(c) => c, 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) => { Err(e) => {
error!( error!(
"Failed to get trace count for {}: {}", "Failed to get trace distribution for {}: {}",
uuid_clone, e uuid_clone, e
); );
0 (0, 0)
} }
}; };
let (single_frame, multi_frame) = match db_clone let trace_status =
.get_trace_frame_count_distribution(&uuid_clone) crate::core::processor::TraceStatus::from_trace_count(
.await trace_count,
{
Ok(dist) => dist,
Err(e) => {
error!(
"Failed to get trace distribution for {}: {}",
uuid_clone, e
); );
(0, 0) info!(
}
};
let trace_status =
crate::core::processor::TraceStatus::from_trace_count(
trace_count,
);
info!(
"📊 Trace status: {} (total={}, single_frame={}, multi_frame={}) for {}", "📊 Trace status: {} (total={}, single_frame={}, multi_frame={}) for {}",
trace_status, trace_count, single_frame, multi_frame, uuid_clone trace_status, trace_count, single_frame, multi_frame, uuid_clone
); );
// Update processor_results trace_status for Face // Update processor_results trace_status for Face
if let Err(e) = db_clone if let Err(e) = db_clone
.update_trace_status_for_face( .update_trace_status_for_face(
&uuid_clone, &uuid_clone,
&trace_status, &trace_status,
trace_count, trace_count,
single_frame, single_frame,
multi_frame, multi_frame,
) )
.await .await
{ {
error!( error!(
"Failed to update trace_status for {}: {}", "Failed to update trace_status for {}: {}",
uuid_clone, e uuid_clone, e
); );
} }
let mut pp = PipelineProgress::new(&uuid_clone); let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage( pp.update_stage(
"face_tracing", "face_tracing",
1.0, 1.0,
"completed", "completed",
Some(format!( Some(format!(
"{} traces ({} single, {} multi)", "{} traces ({} single, {} multi)",
trace_count, single_frame, multi_frame trace_count, single_frame, multi_frame
)), )),
); );
publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp) publish_pipeline_progress(
redis_clone.as_ref(),
&uuid_clone,
&pp,
)
.await; .await;
}
Err(e) => {
error!(
"❌ Face trace + DB store failed for {}: {}",
uuid_clone, e
)
}
} }
Err(e) => { // Clear in-flight marker so this uuid can be retried later
error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e) // 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) // 🚀 P2.5 Trigger: TMDb Face Matching (after Face, if TMDb data exists)
if has_face && *crate::core::config::tmdb::PROBE_ENABLED { 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) // 🚀 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 { if has_face {
let output_dir = OUTPUT_DIR.as_str(); 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::<serde_json::Value>(&content)
{
if let Some(traces) = traced_data.get("traces") {
let trace_ids: Vec<i64> = 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); let face_cluster_path = format!("{}/{}.face_cluster.json", output_dir, uuid);
if std::path::Path::new(&face_cluster_path).exists() { if std::path::Path::new(&face_cluster_path).exists() {
// Check if face_cluster data is consistent with tkg_nodes // Check if face_cluster data is consistent with tkg_nodes
@@ -2351,16 +2470,25 @@ impl JobWorker {
.unwrap_or(0); .unwrap_or(0);
if let Ok(content) = std::fs::read_to_string(&face_cluster_path) { if let Ok(content) = std::fs::read_to_string(&face_cluster_path) {
if let Ok(cluster_data) = serde_json::from_str::<serde_json::Value>(&content) { if let Ok(cluster_data) =
let cluster_count = cluster_data.get("clusters") serde_json::from_str::<serde_json::Value>(&content)
{
let cluster_count = cluster_data
.get("clusters")
.and_then(|c| c.as_array()) .and_then(|c| c.as_array())
.map(|a| a.len() as i64) .map(|a| a.len() as i64)
.unwrap_or(0); .unwrap_or(0);
if face_track_count == cluster_count { 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 { } 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 // Check face.json status first to determine TKG type
let face_json_path = format!( let face_json_path = format!(
"{}/{}.face.json", "{}/{}.face.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
let has_faces = if std::path::Path::new(&face_json_path).exists() { 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(content) = std::fs::read_to_string(&face_json_path) {
if let Ok(face_data) = if let Ok(face_data) = serde_json::from_str::<serde_json::Value>(&content) {
serde_json::from_str::<serde_json::Value>(&content)
{
face_data face_data
.get("status") .get("status")
.and_then(|s| s.as_str()) .and_then(|s| s.as_str())
@@ -2412,7 +2540,9 @@ impl JobWorker {
// Has faces - wait for face_traced.json // Has faces - wait for face_traced.json
let traced_path = format!( let traced_path = format!(
"{}/{}.face_traced.json", "{}/{}.face_traced.json",
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'), crate::core::config::OUTPUT_DIR
.as_str()
.trim_end_matches('/'),
uuid uuid
); );
@@ -2439,168 +2569,45 @@ impl JobWorker {
0 0
}; };
// Wait for Qdrant to have all face points (up to 30 seconds) // Wait for Qdrant to have all face points (up to 30 seconds)
let qdrant = crate::core::db::qdrant_db::QdrantDb::new(); let qdrant = crate::core::db::qdrant_db::QdrantDb::new();
let mut attempts = 0; let mut attempts = 0;
let max_attempts = 30; let max_attempts = 30;
loop { loop {
match qdrant match qdrant
.count_points( .count_points(
"_faces", "_faces",
serde_json::json!({ serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}] "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()),
) )
.await .await
{ {
Ok(r) => { Ok(count) if count >= expected_faces && expected_faces > 0 => {
let total_nodes = r.face_track_nodes info!("📝 Prerequisites met for TKG Build (Qdrant has {} faces, expected {}): {}",
+ r.gaze_track_nodes count, expected_faces, uuid);
+ r.lip_track_nodes break;
+ 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) => {
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 db_clone = self.db.clone();
let redis_clone = self.redis.clone(); let redis_clone = self.redis.clone();
let uuid_clone = uuid.to_string(); let uuid_clone = uuid.to_string();
@@ -2611,16 +2618,17 @@ impl JobWorker {
let _face_io_permit = match FACE_IO_SEM.acquire().await { let _face_io_permit = match FACE_IO_SEM.acquire().await {
Ok(p) => p, Ok(p) => p,
Err(_) => { Err(_) => {
error!("❌ TKG build (no-faces) semaphore closed for {}", uuid_clone); error!("❌ TKG build semaphore closed for {}", uuid_clone);
return; 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); let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage("tkg_nodes", 0.0, "running", None); pp.update_stage("tkg_nodes", 0.0, "running", None);
pp.update_stage("tkg_edges", 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( match crate::core::processor::tkg::build_tkg(
&db_clone, &db_clone,
@@ -2649,11 +2657,10 @@ impl JobWorker {
+ r.wears_edges + r.wears_edges
+ r.hand_object_edges; + r.hand_object_edges;
info!( info!(
"✅ TKG build completed (no faces) for {}: {} nodes, {} edges", "✅ TKG build completed for {}: {} nodes, {} edges",
uuid_clone, total_nodes, total_edges uuid_clone, total_nodes, total_edges
); );
// Update progress for no-faces case
let mut pp = PipelineProgress::new(&uuid_clone); let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage( pp.update_stage(
"tkg_nodes", "tkg_nodes",
@@ -2673,11 +2680,144 @@ impl JobWorker {
&pp, &pp,
) )
.await; .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 { 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 // 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 // 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. // 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(); 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(content) = std::fs::read_to_string(&traced_path) {
if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) { if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
@@ -3019,14 +3163,8 @@ impl JobWorker {
} }
// Sync name to trace_profiles // Sync name to trace_profiles
let _ = schema::upsert_trace_profile( let _ =
db.pool(), schema::upsert_trace_profile(db.pool(), uuid, *trace_id as i32, &label, None).await;
uuid,
*trace_id as i32,
&label,
None,
)
.await;
} }
// Also update traces that are NOT in any cluster (keep default Person_N name) // 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::<serde_json::Value>(&content) { if let Ok(traced_data) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(traces) = traced_data.get("traces") { if let Some(traces) = traced_data.get("traces") {
let trace_list = if traces.is_object() { let trace_list = if traces.is_object() {
traces.as_object().map(|o| o.keys().filter_map(|k| k.parse::<i64>().ok()).collect::<Vec<_>>()) traces.as_object().map(|o| {
o.keys()
.filter_map(|k| k.parse::<i64>().ok())
.collect::<Vec<_>>()
})
} else if traces.is_array() { } 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 { } else {
None None
}; };