fix: two issues - per-job concurrency budget + face_cluster race condition
1. Per-job concurrency budget: add can_start_for_job() to ProcessorPool so multiple files process in parallel instead of one job starving others. Uses active_job_count to compute fair slot budget per job. 2. FaceCluster race condition: add face_traced.json existence check before running face_cluster processor. face_traced.json is produced by P2 store_traced_faces.py which runs AFTER process_job completes, so clustering was producing no_faces (0 clusters) despite having faces.
This commit is contained in:
@@ -131,6 +131,24 @@ impl JobWorker {
|
||||
let dynamic_max = resources.safe_max_concurrent(self.config.max_concurrent);
|
||||
self.processor_pool.sweep_stale().await;
|
||||
|
||||
// Compute active job count (pending + running) so the per-job slot budget
|
||||
// is shared fairly across files, preventing one job from starving others.
|
||||
{
|
||||
let active_running = self
|
||||
.db
|
||||
.get_all_running_jobs(self.config.batch_size)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.len();
|
||||
let active_pending = self
|
||||
.db
|
||||
.get_pending_jobs(self.config.batch_size)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
.len();
|
||||
self.processor_pool.set_active_jobs(active_running + active_pending);
|
||||
}
|
||||
|
||||
// Reset stale running jobs: jobs stuck in 'running' with no active processor results
|
||||
// Exclude jobs where all processor_results are completed (waiting for ingestion)
|
||||
let monitor_jobs_table = schema::table_name("monitor_jobs");
|
||||
@@ -256,7 +274,7 @@ impl JobWorker {
|
||||
error!("check_and_complete_job failed for {}: {}", job.uuid, e);
|
||||
false
|
||||
});
|
||||
if should_retry && self.processor_pool.can_start().await {
|
||||
if should_retry && self.processor_pool.can_start_for_job(job.id).await {
|
||||
if let Err(e) = self.process_job(job.clone()).await {
|
||||
error!("Failed to reprocess job {}: {}", job.uuid, e);
|
||||
}
|
||||
@@ -267,7 +285,7 @@ impl JobWorker {
|
||||
{
|
||||
let running_jobs = self.db.get_all_running_jobs(self.config.batch_size).await?;
|
||||
for job in running_jobs {
|
||||
if !self.processor_pool.can_start().await {
|
||||
if !self.processor_pool.can_start_for_job(job.id).await {
|
||||
break;
|
||||
}
|
||||
let results = self
|
||||
@@ -312,7 +330,7 @@ impl JobWorker {
|
||||
info!("Found {} pending jobs", pending_jobs.len());
|
||||
|
||||
for job in pending_jobs {
|
||||
if !self.processor_pool.can_start().await {
|
||||
if !self.processor_pool.can_start_for_job(job.id).await {
|
||||
info!("Max concurrent processors reached, waiting...");
|
||||
break;
|
||||
}
|
||||
@@ -1299,6 +1317,24 @@ impl JobWorker {
|
||||
}
|
||||
|
||||
// Check dependencies: all dependent processors must be completed
|
||||
// Special check for FaceCluster: face_traced.json must exist (produced by P2
|
||||
// store_traced_faces.py which runs AFTER process_job completes).
|
||||
if *processor_type == crate::core::db::ProcessorType::FaceCluster {
|
||||
let traced_path = format!(
|
||||
"{}/{}.face_traced.json",
|
||||
crate::core::config::OUTPUT_DIR.as_str().trim_end_matches('/'),
|
||||
job.uuid
|
||||
);
|
||||
if !std::path::Path::new(&traced_path).exists() {
|
||||
info!(
|
||||
"Processor {} deferred: face_traced.json not yet ready for {}",
|
||||
processor_type.as_str(),
|
||||
job.uuid
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let deps = processor_type.dependencies();
|
||||
if !deps.is_empty() {
|
||||
let mut any_dep_failed = false;
|
||||
@@ -1382,7 +1418,7 @@ impl JobWorker {
|
||||
processor_type.as_str()
|
||||
);
|
||||
// Check capacity before starting processor
|
||||
if !self.processor_pool.can_start().await {
|
||||
if !self.processor_pool.can_start_for_job(job.id).await {
|
||||
info!(
|
||||
"Max concurrent processors reached, skipping remaining processors for job {}",
|
||||
job.uuid
|
||||
|
||||
+49
-1
@@ -3,15 +3,18 @@ use libc;
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{mpsc, RwLock};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
/// Guard that ensures processor pool cleanup runs even if the task panics.
|
||||
/// Guard that ensures processor pool cleanup runs even if the task panics.
|
||||
struct ProcessorCleanupGuard {
|
||||
job_id: i32,
|
||||
running: Arc<RwLock<HashMap<i32, ProcessorHandle>>>,
|
||||
running_count: Arc<RwLock<usize>>,
|
||||
running_per_job: Arc<RwLock<HashMap<i32, usize>>>,
|
||||
frame_count: Arc<RwLock<usize>>,
|
||||
time_count: Arc<RwLock<usize>>,
|
||||
pipeline: PipelineType,
|
||||
@@ -30,6 +33,16 @@ impl Drop for ProcessorCleanupGuard {
|
||||
*guard -= 1;
|
||||
}
|
||||
}
|
||||
if let Ok(mut guard) = self.running_per_job.try_write() {
|
||||
if let Some(c) = guard.get_mut(&self.job_id) {
|
||||
if *c > 0 {
|
||||
*c -= 1;
|
||||
}
|
||||
if *c == 0 {
|
||||
guard.remove(&self.job_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
match self.pipeline {
|
||||
PipelineType::Frame => {
|
||||
if let Ok(mut guard) = self.frame_count.try_write() {
|
||||
@@ -107,6 +120,8 @@ pub struct ProcessorPool {
|
||||
config_max: usize,
|
||||
running: Arc<RwLock<HashMap<i32, ProcessorHandle>>>,
|
||||
running_count: Arc<RwLock<usize>>,
|
||||
running_per_job: Arc<RwLock<HashMap<i32, usize>>>,
|
||||
active_job_count: Arc<AtomicUsize>,
|
||||
running_frame_count: Arc<RwLock<usize>>,
|
||||
running_time_count: Arc<RwLock<usize>>,
|
||||
}
|
||||
@@ -119,11 +134,36 @@ impl ProcessorPool {
|
||||
config_max: max_concurrent,
|
||||
running: Arc::new(RwLock::new(HashMap::new())),
|
||||
running_count: Arc::new(RwLock::new(0)),
|
||||
running_per_job: Arc::new(RwLock::new(HashMap::new())),
|
||||
active_job_count: Arc::new(AtomicUsize::new(0)),
|
||||
running_frame_count: Arc::new(RwLock::new(0)),
|
||||
running_time_count: Arc::new(RwLock::new(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the number of active jobs (pending + running) so slot budgets are shared fairly.
|
||||
pub fn set_active_jobs(&self, n: usize) {
|
||||
self.active_job_count.store(n, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Checks both the global concurrency cap and the per-job budget so one job cannot
|
||||
/// monopolize all slots and starve other pending jobs.
|
||||
pub async fn can_start_for_job(&self, job_id: i32) -> bool {
|
||||
if !self.can_start().await {
|
||||
return false;
|
||||
}
|
||||
let jobs = self.active_job_count.load(Ordering::Relaxed).max(1);
|
||||
let budget = self.current_max().await.div_ceil(jobs).max(1);
|
||||
let mine = self
|
||||
.running_per_job
|
||||
.read()
|
||||
.await
|
||||
.get(&job_id)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
mine < budget
|
||||
}
|
||||
|
||||
/// 根據系統資源計算當前安全的並發上限
|
||||
pub async fn current_max(&self) -> usize {
|
||||
let resources = SystemResources::check();
|
||||
@@ -238,9 +278,15 @@ impl ProcessorPool {
|
||||
|
||||
let running = self.running.clone();
|
||||
let running_count = self.running_count.clone();
|
||||
let running_per_job = self.running_per_job.clone();
|
||||
let running_frame_count = self.running_frame_count.clone();
|
||||
let running_time_count = self.running_time_count.clone();
|
||||
let child_pid: Arc<RwLock<Option<i32>>> = Arc::new(RwLock::new(None));
|
||||
{
|
||||
let mut pj = self.running_per_job.write().await;
|
||||
let entry = pj.entry(job_id).or_insert(0);
|
||||
*entry += 1;
|
||||
}
|
||||
running.write().await.insert(
|
||||
job_id,
|
||||
ProcessorHandle {
|
||||
@@ -269,6 +315,7 @@ impl ProcessorPool {
|
||||
job_id,
|
||||
running: running.clone(),
|
||||
running_count: running_count.clone(),
|
||||
running_per_job: running_per_job.clone(),
|
||||
frame_count: running_frame_count.clone(),
|
||||
time_count: running_time_count.clone(),
|
||||
pipeline,
|
||||
@@ -1328,7 +1375,8 @@ impl ProcessorPool {
|
||||
let height = frame_height.unwrap_or(720) as f64; // Default fallback
|
||||
|
||||
// Group OCR texts by zone and proximity
|
||||
let groups: Vec<OcrGroup> = group_ocr_texts_by_zone_and_proximity(&ocr_result.frames, height);
|
||||
let groups: Vec<OcrGroup> =
|
||||
group_ocr_texts_by_zone_and_proximity(&ocr_result.frames, height);
|
||||
|
||||
tracing::info!(
|
||||
"Storing {} OCR groups (from {} frames) for video {}",
|
||||
|
||||
Reference in New Issue
Block a user