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
+19 -8
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,7 +269,14 @@ 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(
script_name,
args,
uuid,
log_prefix,
timeout_duration,
Some(1),
)
.await .await
} }
@@ -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;
+202 -56
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);
@@ -2134,7 +2180,8 @@ impl JobWorker {
{ {
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() { let executor = match crate::core::processor::PythonExecutor::new() {
Ok(ex) => ex, Ok(ex) => ex,
@@ -2145,12 +2192,13 @@ impl JobWorker {
} }
}; };
match executor match executor
.run( .run_with_output_idx(
"store_traced_faces.py", "store_traced_faces.py",
&["--file-uuid", &uuid_clone], &["--file-uuid", &uuid_clone],
Some(&uuid_clone), Some(&uuid_clone),
"TRACE_STORE", "TRACE_STORE",
Some(std::time::Duration::from_secs(600)), Some(std::time::Duration::from_secs(600)),
None,
) )
.await .await
{ {
@@ -2220,11 +2268,18 @@ impl JobWorker {
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) => { Err(e) => {
error!("❌ Face trace + DB store failed for {}: {}", uuid_clone, e) error!(
"❌ Face trace + DB store failed for {}: {}",
uuid_clone, e
)
} }
} }
// Clear in-flight marker so this uuid can be retried later // Clear in-flight marker so this uuid can be retried later
@@ -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
); );
@@ -2497,7 +2627,8 @@ impl JobWorker {
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,
@@ -2555,8 +2686,18 @@ impl JobWorker {
// Mark rule2_ingestion as running // Mark rule2_ingestion as running
{ {
let mut pp = PipelineProgress::new(&uuid_clone); let mut pp = PipelineProgress::new(&uuid_clone);
pp.update_stage("rule2_ingestion", 0.0, "running", None); pp.update_stage(
publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp).await; "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( match crate::core::chunk::rule2_ingest::ingest_rule2(
db_clone.pool(), db_clone.pool(),
@@ -2611,7 +2752,10 @@ 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 (no-faces) semaphore closed for {}",
uuid_clone
);
return; return;
} }
}; };
@@ -2667,11 +2811,7 @@ impl JobWorker {
"completed", "completed",
Some(format!("{} edges", total_edges)), Some(format!("{} edges", total_edges)),
); );
publish_pipeline_progress( publish_pipeline_progress(redis_clone.as_ref(), &uuid_clone, &pp)
redis_clone.as_ref(),
&uuid_clone,
&pp,
)
.await; .await;
} }
Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e), Err(e) => error!("❌ TKG build failed for {}: {}", uuid_clone, e),
@@ -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
}; };