fix: worker finalize stuck processing files

- Improve face fast-path trigger: recognize has_faces with empty frames
- Add re-evaluation mechanism: check PROCESSING files every 10 mins
- Enhance ASRX silent fast-path: detect empty segments array
- Fix files stuck in PROCESSING status when all data is produced

Related: M4ProMini deep scan (114 files, 89 bad + 2 stuck)
Issue: ASRX & FACE_CLUSTER forever running/0, no completion trigger
This commit is contained in:
Accusys
2026-10-07 13:11:10 +08:00
parent ab54382834
commit cd00a7fec5
2 changed files with 385 additions and 39 deletions
+162 -39
View File
@@ -95,8 +95,15 @@ impl JobWorker {
warn!("[HEALTH-CHECK] Initial health check failed: {}", e);
}
// Layer 3b: Re-evaluate stuck PROCESSING files
if let Err(e) = self.re_evaluate_stuck_processing().await {
warn!("[RE-EVALUATE] Initial re-evaluation failed: {}", e);
}
let mut last_health_check = std::time::Instant::now();
let health_check_interval = std::time::Duration::from_secs(300); // 5 minutes
let mut last_reevaluate = std::time::Instant::now();
let reevaluate_interval = std::time::Duration::from_secs(600); // 10 minutes
let mut last_billing_agg = std::time::Instant::now();
let billing_agg_interval = std::time::Duration::from_secs(3600); // 1 hour
@@ -115,6 +122,14 @@ impl JobWorker {
last_health_check = std::time::Instant::now();
}
// Layer 3b: Re-evaluate stuck PROCESSING files every 10 minutes
if last_reevaluate.elapsed() > reevaluate_interval {
if let Err(e) = self.re_evaluate_stuck_processing().await {
warn!("[RE-EVALUATE] Periodic re-evaluation failed: {}", e);
}
last_reevaluate = std::time::Instant::now();
}
// Billing aggregation every hour
if last_billing_agg.elapsed() > billing_agg_interval {
let current_month = format!("{}", chrono::Utc::now().format("%Y-%m"));
@@ -559,18 +574,15 @@ impl JobWorker {
// 2. (force || !already_exists) AND file is video AND auto_pipeline is enabled globally
let auto_pipeline_enabled = crate::core::config::get_auto_pipeline_enabled();
let is_video = resp.file_type.as_deref() == Some("video");
let should_trigger = auto_pipeline_override
|| ((force || !resp.already_exists) && auto_pipeline_enabled);
let should_trigger =
auto_pipeline_override || ((force || !resp.already_exists) && auto_pipeline_enabled);
info!(
"[COMMAND_QUEUE] Auto-pipeline conditions: auto_pipeline_override={}, force={}, already_exists={}, auto_pipeline_enabled={}, is_video={}, should_trigger={}",
auto_pipeline_override, force, resp.already_exists, auto_pipeline_enabled, is_video, should_trigger
);
if should_trigger
&& resp.success
&& is_video
{
if should_trigger && resp.success && is_video {
let file_uuid = resp.file_uuid.clone();
let face_settings_ref = face_settings.as_ref();
if let Ok(job) = self
@@ -582,8 +594,7 @@ impl JobWorker {
"[COMMAND_QUEUE] Auto-pipeline job {} created for {}",
job.id, file_uuid
);
let all_procs: Vec<&str> =
vec!["cut", "asr", "asrx", "ocr", "face"];
let all_procs: Vec<&str> = vec!["cut", "asr", "asrx", "ocr", "face"];
let total: i64 = sqlx::query_scalar(&format!(
"SELECT COALESCE(total_frames, 0) FROM {} WHERE file_uuid = $1",
schema::table_name("videos")
@@ -647,6 +658,76 @@ impl JobWorker {
Ok(())
}
/// Re-evaluate stuck PROCESSING files: if all data is produced but status hasn't updated,
/// force completion. This handles cases where fast-path or other completion logic failed.
async fn re_evaluate_stuck_processing(&self) -> Result<()> {
info!("[RE-EVALUATE] Starting re-evaluation of stuck PROCESSING files");
// Get all PROCESSING videos
let processing_videos = sqlx::query_as::<_, (String, String)>(&format!(
"SELECT file_uuid, file_name FROM {} WHERE status = 'PROCESSING'",
crate::core::db::schema::table_name("videos")
))
.fetch_all(self.db.pool())
.await?;
let mut total_completed = 0;
for (uuid, file_name) in processing_videos {
// Get job for this video
if let Some(job) = self.db.get_monitor_job_by_uuid(&uuid).await? {
// Check if ingestion is actually complete
if Self::ingestion_complete(self.db.pool(), &uuid, &job.processors).await {
info!(
"[RE-EVALUATE] File {} has all data produced, forcing COMPLETED status",
uuid
);
// Update job status
self.db
.update_job_status(job.id, crate::core::db::MonitorJobStatus::Completed)
.await?;
// Update video status
self.db
.update_video_status(&uuid, crate::core::db::VideoStatus::Completed)
.await?;
// Update processing status
let video = self.db.get_video_by_uuid(&uuid).await?;
let total_frames = video.and_then(|v| {
if v.total_frames > 0 {
Some(v.total_frames)
} else if v.duration > 0.0 && v.fps > 0.0 {
Some((v.duration * v.fps).floor() as u64)
} else {
None
}
}).unwrap_or(0);
self.db
.update_processing_status_completed(&uuid, total_frames)
.await?;
total_completed += 1;
info!(
"[RE-EVALUATE] ✅ Forced completion for {} ({})",
uuid, file_name
);
}
}
}
if total_completed > 0 {
info!(
"[RE-EVALUATE] Completed {} stuck files",
total_completed
);
}
Ok(())
}
async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
// Check if job still exists in database (may have been deleted by unregister)
let current_job = self.db.get_monitor_job_by_uuid(&job.uuid).await?;
@@ -661,10 +742,15 @@ impl JobWorker {
info!("Processing job: {} ({})", job.uuid, job.id);
// Set preferred language from admin config
let config = crate::core::admin_config::ADMIN_CONFIG.get_full_config().await;
let config = crate::core::admin_config::ADMIN_CONFIG
.get_full_config()
.await;
let language = config.search.vlm_output_language.clone();
crate::core::config::set_preferred_language(language);
tracing::info!("[WORKER] Set preferred language from admin config: {}", config.search.vlm_output_language);
tracing::info!(
"[WORKER] Set preferred language from admin config: {}",
config.search.vlm_output_language
);
// Read face_settings from job and set environment variables for face processor
let mut face_settings_backup: Option<(String, String)> = None;
@@ -1518,7 +1604,7 @@ impl JobWorker {
}
}
// Special handling for ASRX: if ASR output exists with no_audio_track/silent_audio, skip processing
// Enhanced ASRX fast-path: check for silent/no-audio or empty segments
if *processor_type == crate::core::db::ProcessorType::Asrx {
let asr_output_path = format!(
"{}/{}.asr.json",
@@ -1530,9 +1616,24 @@ impl JobWorker {
if let Ok(asr_json) = std::fs::read_to_string(&asr_output_path) {
if let Ok(asr_data) = serde_json::from_str::<serde_json::Value>(&asr_json) {
let asr_status = asr_data.get("status").and_then(|s| s.as_str());
let segments_empty = asr_data
.get("segments")
.and_then(|s| s.as_array())
.map(|a| a.is_empty())
.unwrap_or(false);
// Fast-path trigger conditions:
// 1. status == "no_audio_track" or "silent_audio" (explicit)
// 2. segments array is empty (implicit silent)
if let Some(status) = asr_status {
if status == "no_audio_track" || status == "silent_audio" {
info!("ASRX: ASR status={}, skipping ASRX processing", status);
if status == "no_audio_track" || status == "silent_audio" || segments_empty {
let effective_status = if segments_empty && status != "no_audio_track" && status != "silent_audio" {
"silent_audio"
} else {
status
};
info!("ASRX: fast-path (status={}, segments_empty={})", effective_status, segments_empty);
// Write asrx.json output file (so sync-status sees it)
let asrx_output_path = format!(
@@ -1543,7 +1644,7 @@ impl JobWorker {
job.uuid
);
let asrx_result = serde_json::json!({
"status": status,
"status": effective_status,
"language": asr_data.get("language").and_then(|l| l.as_str()),
"segments": [],
"segment_count": 0
@@ -1573,7 +1674,7 @@ impl JobWorker {
"UPDATE {} SET asr_status = $1, segment_count = 0 WHERE job_id = $2 AND processor = 'asrx'",
crate::core::db::schema::table_name("processor_results")
))
.bind(status)
.bind(effective_status)
.bind(job.id)
.execute(self.db.pool())
.await;
@@ -1851,6 +1952,7 @@ impl JobWorker {
/// 檢查所有入庫步驟是否已完成(與 ingestion-status endpoint 同步邏輯)
async fn ingestion_complete(pool: &PgPool, uuid: &str, job_processors: &[String]) -> bool {
let chunk_t = schema::table_name("chunk");
let pre_chunks_t = schema::table_name("pre_chunks");
let pr_t = schema::table_name("processor_results");
let tkg_nodes_t = schema::table_name("tkg_nodes");
let tkg_edges_t = schema::table_name("tkg_edges");
@@ -2009,10 +2111,10 @@ impl JobWorker {
true
};
// 5. Rule 3 Scene Chunks: chunk_type = 'cut' 存在
// 5. Rule 3 Scene Chunks: pre_chunks 有 processor_type = 'cut'(cut/scene 只寫入 pre_chunks,chunk 表從不落 cut)
let rule3_done: bool = if has_cut {
sqlx::query_scalar::<_, i32>(&format!(
"SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'cut' LIMIT 1"
"SELECT 1 FROM {pre_chunks_t} WHERE file_uuid = $1 AND processor_type = 'cut' LIMIT 1"
))
.bind(uuid)
.fetch_optional(pool)
@@ -2335,11 +2437,11 @@ impl JobWorker {
let mut created_deferred = false;
// [DISABLED] FS VLM Summary - controlled by admin_config
// [DISABLED] FS VLM Summary - controlled by admin_config
// System now only uses Scene VLM (10 sec moment vlm)
// To enable: set fs_vlm_enabled=true in admin_config table
let fs_vlm_enabled = crate::core::admin_config::get_fs_vlm_enabled(self.db.pool()).await;
if fs_vlm_enabled {
// [ORIGINAL FS VLM CODE - DISABLED BY DEFAULT]
// Check VLM summary progress — if incomplete, trigger/restart
@@ -2412,10 +2514,10 @@ impl JobWorker {
}
}
} // end if fs_vlm_enabled
// Initialize vlm_done for moment check (always 0 since FS VLM is disabled)
let vlm_done: i64 = 0;
let chunk_t = schema::table_name("chunk");
let moment_exists: bool = sqlx::query_scalar(&format!(
"SELECT EXISTS(SELECT 1 FROM {chunk_t} WHERE file_uuid = $1 AND chunk_type = 'moment')"
@@ -2746,7 +2848,7 @@ impl JobWorker {
"✅ Rule 1 Ingestion completed: {} chunks inserted.",
count
);
if count > 0 {
info!(
"📝 Starting automatic vectorize for {} chunks...",
@@ -2838,12 +2940,15 @@ impl JobWorker {
);
// ✅ V2: Check data integrity, not just file existence
let trace_complete = if std::path::Path::new(&traced_path).exists() {
info!("✅ Face trace already done for {} (face_traced.json exists)", uuid);
info!(
"✅ Face trace already done for {} (face_traced.json exists)",
uuid
);
true
} else {
false
};
if trace_complete {
info!("✅ Face trace already done for {}, skipping spawn", uuid);
} else {
@@ -2863,11 +2968,23 @@ impl JobWorker {
if let Ok(face_data) =
serde_json::from_str::<serde_json::Value>(&content)
{
face_data
let status = face_data
.get("status")
.and_then(|s| s.as_str())
.map(|s| s == "no_faces")
.unwrap_or(false)
.unwrap_or("");
// Fast-path trigger conditions:
// 1. status == "no_faces" (explicit)
// 2. status == "has_faces" but frames array is empty (implicit)
let frames_empty = face_data
.get("frames")
.and_then(|f| match f {
serde_json::Value::Array(arr) => Some(arr.is_empty()),
_ => Some(true),
})
.unwrap_or(true);
status == "no_faces" || (status == "has_faces" && frames_empty)
} else {
false
}
@@ -3404,7 +3521,7 @@ impl JobWorker {
let filter = serde_json::json!({
"must": [{"key": "file_uuid", "match": {"value": uuid}}]
});
let mut attempts = 0;
let max_attempts = 60;
let mut stable_trace_count: Option<i64> = None;
@@ -3724,7 +3841,7 @@ impl JobWorker {
"Job {}: all processors done, waiting for ingestion...",
job_id
);
return Ok(false);
}
@@ -4311,17 +4428,22 @@ impl JobWorker {
// Get preferred language
let preferred_language = crate::core::config::get_preferred_language();
// Generate English description (for indexing)
match SceneVlmProcessor::generate_scene_description(&frame_path, "en").await {
Ok((description_en, objects, tags)) => {
scene.vlm_description = Some(description_en.clone());
scene.vlm_objects = objects.clone();
scene.vlm_tags = tags.clone();
// Generate localized description if needed
if preferred_language != "en" {
match SceneVlmProcessor::generate_scene_description(&frame_path, &preferred_language).await {
match SceneVlmProcessor::generate_scene_description(
&frame_path,
&preferred_language,
)
.await
{
Ok((description_localized, _, _)) => {
scene.vlm_description_localized = Some(description_localized);
scene.vlm_status = VlmStatus::Completed;
@@ -4332,16 +4454,17 @@ impl JobWorker {
);
}
Err(e) => {
tracing::warn!("[Scene VLM] ⚠️ Scene {} localized failed: {}", idx, e);
tracing::warn!(
"[Scene VLM] ⚠️ Scene {} localized failed: {}",
idx,
e
);
scene.vlm_status = VlmStatus::Completed;
}
}
} else {
scene.vlm_status = VlmStatus::Completed;
tracing::info!(
"[Scene VLM] ✅ Scene {}: EN only",
idx
);
tracing::info!("[Scene VLM] ✅ Scene {}: EN only", idx);
}
}
Err(e) => {