refactor: replace P5 polling with JOIN-based verification + timeout

B: Replace wait_for_traces polling with verify_traces_ready
   - Uses JOIN query: trace_profiles INNER JOIN tkg_nodes
   - Ensures trace_profiles data is consistent with TKG before VLM runs
   - Single query instead of 30 retry attempts

C: Add 5-minute timeout to VLM generation
   - tokio::time::timeout(300s) prevents worker from hanging
   - Logs completion stats or timeout error

This fixes the root cause: P5 no longer polls blindly waiting for
TKG to finish. The JOIN query only returns rows when both
trace_profiles AND tkg_nodes face_track entries exist.
This commit is contained in:
Accusys
2026-08-22 22:17:21 +08:00
parent 165af40f3c
commit 906243fdc1
+73 -44
View File
@@ -1860,16 +1860,23 @@ impl JobWorker {
} }
} }
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done; // VLM summary: blocking for files with face traces
let vlm_done_bool: bool = if has_face {
if let (Some(total), Some(done)) = (vlm_total, vlm_done_count) {
total == 0 || done == total
} else { true }
} else { true };
let all_ok = asr_done && trace_done && tkg_done && face_cluster_done && qdrant_face_done && vlm_done_bool;
tracing::info!( tracing::info!(
"[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}) for uuid={}", "[Ingestion] all_ok={} (asr={}, trace={}, tkg={}, face_cluster={}, rule3={}, scene_meta={}, qdrant_face={}, vlm={}) for uuid={}",
all_ok, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, uuid all_ok, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool, uuid
); );
if !all_ok { if !all_ok {
tracing::info!( tracing::info!(
"[Ingestion] waiting (uuid={}): asr={} trace={} tkg={} face_cluster={} rule3={} scene_meta={} qdrant_face={}", "[Ingestion] waiting (uuid={}): asr={} trace={} tkg={} face_cluster={} rule3={} scene_meta={} qdrant_face={} vlm={}",
uuid, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done uuid, asr_done, trace_done, tkg_done, face_cluster_done, rule3_done, scene_meta_done, qdrant_face_done, vlm_done_bool
); );
} }
all_ok all_ok
@@ -2962,23 +2969,38 @@ impl JobWorker {
} }
// 🚀 P5 Trigger: VLM Summary (after TKG, key_frame exists) // 🚀 P5 Trigger: VLM Summary (after TKG, key_frame exists)
// Uses JOIN query to verify trace_profiles is consistent with tkg_nodes.
// Spawned with 5-min timeout to prevent blocking worker indefinitely.
let db_p5 = db_clone.clone(); let db_p5 = db_clone.clone();
let redis_p5 = redis_clone.clone(); let redis_p5 = redis_clone.clone();
let uuid_p5 = uuid_clone.clone(); let uuid_p5 = uuid_clone.clone();
let output_dir_p5 = output_dir_clone.clone(); let output_dir_p5 = output_dir_clone.clone();
let pool_p5 = db_clone.pool().clone(); let pool_p5 = db_clone.pool().clone();
tokio::spawn(async move { tokio::spawn(async move {
let face_count = Self::wait_for_traces(&pool_p5, &uuid_p5, 60).await; // Verify data consistency: trace_profiles JOIN tkg_nodes
let face_count = Self::verify_traces_ready(&pool_p5, &uuid_p5).await;
if face_count > 0 { if face_count > 0 {
vlm_summary::generate_vlm_summaries( info!("[VLM] Starting for {}: {} traces verified", uuid_p5, face_count);
&db_p5, // Apply timeout to prevent hanging indefinitely
&uuid_p5, let result = tokio::time::timeout(
&output_dir_p5, std::time::Duration::from_secs(300),
Some(redis_p5), vlm_summary::generate_vlm_summaries(
&db_p5,
&uuid_p5,
&output_dir_p5,
Some(redis_p5),
),
) )
.await; .await;
match result {
Ok(stats) => info!(
"[VLM] Completed for {}: {}/{} summarized, {} embedded",
uuid_p5, stats.summarized, stats.total, stats.embedded
),
Err(_) => error!("[VLM] Timed out after 5 min for {}", uuid_p5),
}
} else { } else {
info!("[VLM] Skipping for {} (no face traces after 60s wait)", uuid_p5); info!("[VLM] Skipping for {} (no verified face traces)", uuid_p5);
} }
}); });
}); });
@@ -3071,17 +3093,29 @@ impl JobWorker {
let output_dir_p5 = output_dir_clone.clone(); let output_dir_p5 = output_dir_clone.clone();
let pool_p5 = db_clone.pool().clone(); let pool_p5 = db_clone.pool().clone();
tokio::spawn(async move { tokio::spawn(async move {
let face_count = Self::wait_for_traces(&pool_p5, &uuid_p5, 60).await; // Verify data consistency: trace_profiles JOIN tkg_nodes
let face_count = Self::verify_traces_ready(&pool_p5, &uuid_p5).await;
if face_count > 0 { if face_count > 0 {
vlm_summary::generate_vlm_summaries( info!("[VLM] Starting for {}: {} traces verified", uuid_p5, face_count);
&db_p5, let result = tokio::time::timeout(
&uuid_p5, std::time::Duration::from_secs(300),
&output_dir_p5, vlm_summary::generate_vlm_summaries(
Some(redis_p5), &db_p5,
&uuid_p5,
&output_dir_p5,
Some(redis_p5),
),
) )
.await; .await;
match result {
Ok(stats) => info!(
"[VLM] Completed for {}: {}/{} summarized, {} embedded",
uuid_p5, stats.summarized, stats.total, stats.embedded
),
Err(_) => error!("[VLM] Timed out after 5 min for {}", uuid_p5),
}
} else { } else {
info!("[VLM] Skipping for {} (no face traces after 60s wait)", uuid_p5); info!("[VLM] Skipping for {} (no verified face traces)", uuid_p5);
} }
}); });
}); });
@@ -3389,32 +3423,27 @@ impl JobWorker {
Ok(()) Ok(())
} }
/// Poll trace_profiles table until rows appear (TKG may still be writing). /// Verify trace_profiles data is consistent with tkg_nodes (JOIN check).
/// Returns count if found within timeout, 0 otherwise. /// Ensures TKG has fully committed before P5 runs.
async fn wait_for_traces(pool: &PgPool, uuid: &str, max_secs: u64) -> i64 { async fn verify_traces_ready(pool: &PgPool, uuid: &str) -> i64 {
let tp_table = crate::core::db::schema::table_name("trace_profiles"); let tp_table = crate::core::db::schema::table_name("trace_profiles");
let interval = std::time::Duration::from_secs(2); let tkg_table = crate::core::db::schema::table_name("tkg_nodes");
let max_attempts = (max_secs / 2).max(1); // JOIN ensures trace_profiles has matching tkg_nodes face_track entries
let count: i64 = sqlx::query_scalar(&format!(
for attempt in 0..max_attempts { "SELECT COUNT(*) FROM {tp_table} tp \
let count: i64 = sqlx::query_scalar(&format!( INNER JOIN {tkg_table} tn \
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1" ON tn.file_uuid = tp.file_uuid \
)) AND tn.node_type = 'face_track' \
.bind(uuid) AND (tn.properties->>'trace_id')::int = tp.trace_id \
.fetch_optional(pool) WHERE tp.file_uuid = $1"
.await ))
.ok() .bind(uuid)
.flatten() .fetch_optional(pool)
.unwrap_or(0); .await
if count > 0 { .ok()
return count; .flatten()
} .unwrap_or(0);
if attempt == 0 { count
info!("[P5-wait] Waiting for trace_profiles to appear for {}", uuid);
}
tokio::time::sleep(interval).await;
}
0
} }
async fn update_face_track_labels( async fn update_face_track_labels(