feat: face clustering pipeline improvements and Rust/Swift face processing

- Add Rust face processor module (detection, embedding, tracking, qdrant)
- Add Facenet CoreML/ONNX conversion scripts and tests
- Refactor swift_face into Sources/swift_face with ArgumentParser support
- Update store_traced_faces to handle face.json correctly
- Fix ASRX parsing and TKG bbox reading from Qdrant
- Improve admin_config and trace_agent APIs
- Add M4 workspace docs for face clustering, dedup, and Facenet validation
- Fix worker heartbeat TTL (poll_interval x 3, min 60s) for offline detection
This commit is contained in:
Accusys
2026-10-02 12:24:55 +08:00
parent e987fb8119
commit e0d04e242f
87 changed files with 11668 additions and 302 deletions
+83 -70
View File
@@ -11,8 +11,9 @@ use tracing::{debug, error, info, warn};
/// Bounds the number of concurrent heavy face-I/O Python tasks (store_traced_faces.py /
/// TKG build). These spawns bypass ProcessorPool (raw tokio::spawn) and each loads the
/// full face.json into numpy + scrolls all Qdrant face points, which previously caused
/// unbounded pile-up and OOM. Capacity mirrors FRAME_SLOT_MAX in processor.rs.
static FACE_IO_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(2));
/// unbounded pile-up and OOM. Increased from 2 to 4 to match FRAME_SLOT_MAX and avoid
/// resource starvation when multiple videos are processed in parallel.
static FACE_IO_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));
/// Max time a spawn task waits for a FACE_IO_SEM permit before backing off.
/// A stuck task holding a permit would otherwise block every queued spawn
@@ -253,8 +254,9 @@ impl JobWorker {
.query_async(&mut conn)
.await
.ok();
// Set TTL = 3x poll_interval so stale entries expire
let ttl_secs = (self.config.poll_interval_secs * 3) as i64;
// Set TTL = max(3x poll_interval, 60s) so long-running poll iterations
// (heavy jobs, VLM, release packing) do not let the heartbeat expire
let ttl_secs = (self.config.poll_interval_secs * 3).max(60) as i64;
let _: Result<(), _> = redis::cmd("EXPIRE")
.arg(&[health_key.as_str(), &ttl_secs.to_string()])
.query_async(&mut conn)
@@ -2335,76 +2337,87 @@ impl JobWorker {
let mut created_deferred = false;
// [RE-ENABLED] FS VLM Summary with Gemma4 + Parallel processing (2026-09-22)
// Check VLM summary progress — if incomplete, trigger/restart
let tp_table = schema::table_name("trace_profiles");
let vlm_total: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let vlm_done: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
// [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
let tp_table = schema::table_name("trace_profiles");
let vlm_total: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
let vlm_done: i64 = sqlx::query_scalar(&format!(
"SELECT COUNT(*) FROM {tp_table} WHERE file_uuid = $1 AND vlm_description IS NOT NULL AND vlm_description != ''"
))
.bind(uuid)
.fetch_one(self.db.pool())
.await
.unwrap_or(0);
if vlm_total > 0 && vlm_done < vlm_total {
// VLM incomplete — check if we should trigger it
let face_cluster_done = job_processors.iter().any(|p| p == "face_cluster")
&& results.iter().any(|r| {
r.processor_type.as_str() == "face_cluster"
&& matches!(r.status, ProcessorJobStatus::Completed)
});
if face_cluster_done {
// Check if key_frame.jpg files are ready
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let trace_dir = std::path::PathBuf::from(output_dir).join(uuid);
let key_frame_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
.map(|entries| {
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().join("key_frame.jpg").exists())
.count() as i64
})
.unwrap_or(0)
} else {
0
};
if key_frame_count >= vlm_total {
info!(
"[VLM-poll] {}/{} done, {}/{} key_frames ready — triggering VLM",
vlm_done, vlm_total, key_frame_count, vlm_total
);
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 {
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_clone,
&uuid_clone,
&output_dir_clone,
Some(redis_clone),
)
.await;
if vlm_total > 0 && vlm_done < vlm_total {
// VLM incomplete — check if we should trigger it
let face_cluster_done = job_processors.iter().any(|p| p == "face_cluster")
&& results.iter().any(|r| {
r.processor_type.as_str() == "face_cluster"
&& matches!(r.status, ProcessorJobStatus::Completed)
});
} else {
info!(
"[VLM-poll] Waiting for key_frame.jpg: {}/{} ready",
key_frame_count, vlm_total
);
if face_cluster_done {
// Check if key_frame.jpg files are ready
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
let trace_dir = std::path::PathBuf::from(output_dir).join(uuid);
let key_frame_count = if trace_dir.exists() {
std::fs::read_dir(&trace_dir)
.ok()
.map(|entries| {
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().join("key_frame.jpg").exists())
.count() as i64
})
.unwrap_or(0)
} else {
0
};
if key_frame_count >= vlm_total {
info!(
"[VLM-poll] {}/{} done, {}/{} key_frames ready — triggering VLM",
vlm_done, vlm_total, key_frame_count, vlm_total
);
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 {
crate::core::processor::vlm_summary::generate_vlm_summaries(
&db_clone,
&uuid_clone,
&output_dir_clone,
Some(redis_clone),
)
.await;
});
} else {
info!(
"[VLM-poll] Waiting for key_frame.jpg: {}/{} ready",
key_frame_count, vlm_total
);
}
}
}
}
} // 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')"
+31 -26
View File
@@ -23,39 +23,42 @@ struct ProcessorCleanupGuard {
impl Drop for ProcessorCleanupGuard {
fn drop(&mut self) {
use tokio::sync::TryLockError;
if let Ok(mut guard) = self.running.try_write() {
guard.remove(&self.job_id);
} else {
warn!("[ProcessorCleanupGuard] running lock contended");
// Release running map
match self.running.try_write() {
Ok(mut guard) => { guard.remove(&self.job_id); }
Err(_) => error!("[ProcessorCleanupGuard] Failed to acquire running lock for job {} - resource may leak", self.job_id),
}
if let Ok(mut guard) = self.running_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
// Release running count
match self.running_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release running_count for job {}", self.job_id),
}
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);
// Release per-job count
match self.running_per_job.try_write() {
Ok(mut guard) => {
if let Some(c) = guard.get_mut(&self.job_id) {
if *c > 0 { *c -= 1; }
if *c == 0 { guard.remove(&self.job_id); }
}
}
Err(_) => error!("[ProcessorCleanupGuard] Failed to release running_per_job for job {}", self.job_id),
}
// Release pipeline-specific slot
match self.pipeline {
PipelineType::Frame => {
if let Ok(mut guard) = self.frame_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
match self.frame_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release frame slot for job {}", self.job_id),
}
}
PipelineType::Time => {
if let Ok(mut guard) = self.time_count.try_write() {
if *guard > 0 {
*guard -= 1;
}
match self.time_count.try_write() {
Ok(mut guard) => { if *guard > 0 { *guard -= 1; } }
Err(_) => error!("[ProcessorCleanupGuard] Failed to release time slot for job {}", self.job_id),
}
}
PipelineType::Cross => {}
@@ -109,9 +112,11 @@ pub struct ProcessorTask {
}
/// Frame pipeline max concurrent processors (hard limit).
const FRAME_SLOT_MAX: usize = 2;
/// Time pipeline max concurrent processors (audio is heavy, run 1 at a time).
const TIME_SLOT_MAX: usize = 1;
/// Increased from 2 to 4 to match max_concurrent and avoid resource starvation.
const FRAME_SLOT_MAX: usize = 4;
/// Time pipeline max concurrent processors (audio is heavy, run 2 at a time).
/// Increased from 1 to 2 to improve throughput.
const TIME_SLOT_MAX: usize = 2;
pub struct ProcessorPool {
db: Arc<PostgresDb>,