feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx

Consolidated snapshot (previously WIP in working tree).

- core/pipeline_config: new module loading config/pipeline_flows.json as the
  source of truth for stage execution mode (parallel/blocking) and dependencies
- worker/job_worker: dispatch Scene VLM to a background task when the stage is
  declared parallel, unblocking the worker poll loop; resolve processor
  dependencies from pipeline_flows.json (fallback to built-in)
- config/pipeline_flows.json: asrx depends on [cut, asr]
- scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold
  to 6h, skip jobs with recent processor activity
- rust_asrx: Rust speaker diarization CLI + processor wiring
- processor metadata helper; fast_face_clustering script; file_progress pipeline
  API; scan API; VAD updates
This commit is contained in:
Accusys
2026-10-15 13:01:12 +08:00
parent 667e279768
commit 882e31ab96
76 changed files with 10117 additions and 300 deletions
+216 -28
View File
@@ -26,6 +26,86 @@ const FACE_IO_ACQUIRE_TIMEOUT: Duration = Duration::from_secs(600);
static FACE_TRACE_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSet<String>>> =
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
/// Bounds concurrent Scene VLM runs. Scene VLM can take hours per file and each run
/// loads frames + calls the multimodal LLM; without a bound, dispatching many files
/// in parallel would exhaust memory. One at a time mirrors the previous inline
/// (sequential) behavior without blocking the worker poll loop.
static SCENE_VLM_SEM: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(1));
/// Tracks uuids with a Scene VLM task currently spawned (or queued for a permit).
/// Prevents the per-poll loop from spawning duplicate tasks before `scenes.json`
/// exists. Cleared by the spawned task when it finishes.
static SCENE_VLM_INFLIGHT: LazyLock<tokio::sync::Mutex<std::collections::HashSet<String>>> =
LazyLock::new(|| tokio::sync::Mutex::new(std::collections::HashSet::new()));
/// Resolve a processor's dependencies, preferring the declarative
/// `config/pipeline_flows.json` (`register` flow) and falling back to the built-in
/// `ProcessorType::dependencies()` when the stage is not declared. Names in the
/// config that do not map to a `ProcessorType` (e.g. `tkg`) are ignored.
fn stage_dependencies(
processor_type: crate::core::db::ProcessorType,
) -> Vec<crate::core::db::ProcessorType> {
use crate::core::db::ProcessorType;
let cfg = crate::core::pipeline_config::get();
match cfg.stage("register", processor_type.as_str()) {
Some(stage) => stage
.dependencies
.iter()
.filter_map(|name| ProcessorType::from_db_str(name))
.collect(),
None => processor_type.dependencies(),
}
}
/// Ensure an existing processor output file records its metadata (tool/version/time).
///
/// When the worker skips a processor because its output file already exists, the
/// processor itself never runs to add metadata. Upstream writers (e.g. SwiftFacePose)
/// can emit face.json/ocr.json without a metadata block, leaving tool/version/time
/// unrecorded. This patches such files in place; it is a no-op when metadata is present
/// or for processors that do not use the embedded metadata convention.
fn ensure_output_metadata(
processor_type: crate::core::db::ProcessorType,
output_path: &std::path::Path,
uuid: &str,
) {
use crate::core::db::ProcessorType;
let json_str = match std::fs::read_to_string(output_path) {
Ok(s) => s,
Err(_) => return,
};
let path = output_path.to_string_lossy();
match processor_type {
ProcessorType::Face => {
if let Ok(mut result) =
serde_json::from_str::<crate::core::processor::FaceResult>(&json_str)
{
if result.metadata.is_none() {
result.add_metadata("face", "swift_face", Some(uuid));
match result.save_to_file(&path) {
Ok(()) => info!("[METADATA] Wrote face tool/version/time for {}", uuid),
Err(e) => warn!("Failed to write face metadata for {}: {}", uuid, e),
}
}
}
}
ProcessorType::Ocr => {
if let Ok(mut result) =
serde_json::from_str::<crate::core::processor::OcrResult>(&json_str)
{
if result.metadata.is_none() {
result.add_metadata("ocr", "swift_ocr", Some(uuid));
match result.save_to_file(&path) {
Ok(()) => info!("[METADATA] Wrote ocr tool/version/time for {}", uuid),
Err(e) => warn!("Failed to write ocr metadata for {}: {}", uuid, e),
}
}
}
}
_ => {}
}
}
use crate::api::files::{register_single_file, unregister_internal};
use crate::core::chunk::rule1_ingest;
use crate::core::config::{FACE_MIN_CONFIDENCE_DEFAULT, FACE_MIN_SIZE_DEFAULT, OUTPUT_DIR};
@@ -830,14 +910,14 @@ impl JobWorker {
.await?;
// Clear any stale PipelineProgress from previous jobs
let progress_key = format!(
"{}progress:{}:pipeline",
crate::core::config::REDIS_KEY_PREFIX.as_str(),
job.uuid
);
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
let progress_key = format!("{}progress:{}:pipeline", prefix, job.uuid);
// Also reset the phase progress high-water mark used by the phases API
let phase_hwm_key = format!("{}progress:{}:phase_hwm", prefix, job.uuid);
if let Ok(mut conn) = self.redis.get_conn().await {
let _: Option<String> = redis::cmd("DEL")
.arg(&progress_key)
.arg(&phase_hwm_key)
.query_async(&mut conn)
.await
.ok();
@@ -1011,6 +1091,9 @@ impl JobWorker {
"Processor {} output file exists, marking completed and skipping",
processor_type.as_str()
);
// The processor is not run on this path, so ensure the pre-existing
// output still records its processor metadata (tool/version/time).
ensure_output_metadata(*processor_type, &output_path, &job.uuid);
self.db
.update_processor_progress(
&job.uuid,
@@ -1737,7 +1820,7 @@ impl JobWorker {
}
// Check dependencies: all dependent processors must be completed
let deps = processor_type.dependencies();
let deps = stage_dependencies(*processor_type);
if !deps.is_empty() {
let mut any_dep_failed = false;
let all_deps_met =
@@ -2605,7 +2688,7 @@ impl JobWorker {
}
// Check if all dependencies are met
let deps = processor_type.dependencies();
let deps = stage_dependencies(processor_type);
let deps_met = deps.iter().all(|dep| completed_set.contains(dep));
if !deps_met {
@@ -2802,16 +2885,76 @@ impl JobWorker {
false
};
if !scene_vlm_complete {
info!("[Scene VLM] Starting for {} after CUT completion", uuid);
// Guard on `scene_vlm_exhausted`: once retry_count >= 3 the job is
// marked failed elsewhere, so re-spawning would only create a tight
// retry loop now that dispatch is non-blocking.
if !scene_vlm_complete && !scene_vlm_exhausted {
// Execution mode is declared in config/pipeline_flows.json:
// "parallel": true → dispatch to a background task (non-blocking)
// "parallel": false → await inline (blocking, original behavior)
let scene_parallel =
crate::core::pipeline_config::get().is_parallel("register", "scene");
match self.process_scene_vlm(uuid, &output_dir).await {
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = self.db.mark_scene_vlm_failed(uuid).await {
error!("[Scene VLM] Failed to mark {} failed: {}", uuid, e2);
if scene_parallel {
// Non-blocking: spawn so Scene VLM (which can run for hours) does not
// block the worker poll loop. Guarded by SCENE_VLM_INFLIGHT to avoid
// duplicate spawns on each poll, and SCENE_VLM_SEM to bound concurrency.
let mut inflight = SCENE_VLM_INFLIGHT.lock().await;
if inflight.insert(uuid.to_string()) {
drop(inflight);
info!(
"[Scene VLM] (parallel) dispatching for {} after CUT completion",
uuid
);
let db = self.db.clone();
let uuid_owned = uuid.to_string();
let output_dir_owned = output_dir.clone();
tokio::spawn(async move {
let _permit = match SCENE_VLM_SEM.acquire().await {
Ok(p) => p,
Err(_) => {
SCENE_VLM_INFLIGHT.lock().await.remove(&uuid_owned);
return;
}
};
match Self::process_scene_vlm(
db.clone(),
&uuid_owned,
&output_dir_owned,
)
.await
{
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid_owned),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid_owned, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = db.mark_scene_vlm_failed(&uuid_owned).await {
error!(
"[Scene VLM] Failed to mark {} failed: {}",
uuid_owned, e2
);
}
}
}
SCENE_VLM_INFLIGHT.lock().await.remove(&uuid_owned);
});
} else {
drop(inflight);
debug!("[Scene VLM] already in-flight for {}, skipping spawn", uuid);
}
} else {
info!(
"[Scene VLM] (blocking) Starting for {} after CUT completion",
uuid
);
match Self::process_scene_vlm(self.db.clone(), uuid, &output_dir).await {
Ok(_) => info!("[Scene VLM] ✅ Completed for {}", uuid),
Err(e) => {
warn!("[Scene VLM] ❌ Failed for {}: {}", uuid, e);
// 標 failed + retry_count++,讓 job 保持 running 由 poll 重試(上限 3 次)
if let Err(e2) = self.db.mark_scene_vlm_failed(uuid).await {
error!("[Scene VLM] Failed to mark {} failed: {}", uuid, e2);
}
}
}
}
@@ -4349,11 +4492,20 @@ impl JobWorker {
Ok(())
}
pub async fn process_scene_vlm(&self, uuid: &str, output_dir: &str) -> anyhow::Result<()> {
/// Run Scene VLM for a file.
///
/// This is an associated function (not a method) so it can be dispatched to a
/// background task with only the `Arc<PostgresDb>` it needs — see the `parallel`
/// handling in `check_and_complete_job`.
pub async fn process_scene_vlm(
db: Arc<PostgresDb>,
uuid: &str,
output_dir: &str,
) -> anyhow::Result<()> {
use crate::core::processor::scene_vlm::SceneVlmProcessor;
// Mark Scene VLM as running in processor_results
self.db.upsert_scene_vlm_result(uuid, "running").await?;
db.upsert_scene_vlm_result(uuid, "running").await?;
let (_enabled, interval_sec, samples, use_cuts, max_workers) =
crate::core::config::get_scene_vlm_config();
@@ -4363,8 +4515,7 @@ impl JobWorker {
// return Ok(());
// }
let video = self
.db
let video = db
.get_video_by_uuid(uuid)
.await?
.ok_or_else(|| anyhow::anyhow!("Video not found: {}", uuid))?;
@@ -4380,7 +4531,7 @@ impl JobWorker {
"[Scene VLM] Invalid video metadata for {}, marking complete (not applicable)",
uuid
);
self.db.upsert_scene_vlm_result(uuid, "completed").await?;
db.upsert_scene_vlm_result(uuid, "completed").await?;
return Ok(());
}
@@ -4428,8 +4579,7 @@ impl JobWorker {
);
// Update progress: frames extracted
self.db
.update_scene_vlm_progress(uuid, extracted.len() as i32, total_scenes as i32)
db.update_scene_vlm_progress(uuid, extracted.len() as i32, total_scenes as i32)
.await?;
// Generate VLM descriptions for extracted frames
@@ -4499,8 +4649,7 @@ impl JobWorker {
processed += 1;
// Update progress every 10 scenes
if processed % 10 == 0 || processed == total_scenes {
self.db
.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32)
db.update_scene_vlm_progress(uuid, processed as i32, total_scenes as i32)
.await?;
}
}
@@ -4582,7 +4731,7 @@ impl JobWorker {
.bind(scene.has_cut)
.bind(scene.cut_count as i32)
.bind("pending")
.execute(self.db.pool())
.execute(db.pool())
.await?;
let embedding = embedder.embed_document(desc).await?;
@@ -4616,7 +4765,7 @@ impl JobWorker {
.bind(format!("{:x}", point_id))
.bind(&profile.file_uuid)
.bind(scene.index as i32)
.execute(self.db.pool())
.execute(db.pool())
.await?;
indexed += 1;
@@ -4628,7 +4777,27 @@ impl JobWorker {
);
// Mark Scene VLM as completed
self.db.upsert_scene_vlm_result(uuid, "completed").await?;
db.upsert_scene_vlm_result(uuid, "completed").await?;
// Update Redis progress for scene_vlm
if let Ok(redis) = crate::core::db::RedisClient::new() {
if let Ok(mut conn) = redis.get_conn().await {
let prefix = crate::core::config::REDIS_KEY_PREFIX.as_str();
let redis_key = format!("{}progress:{}:pipeline", prefix, uuid);
let _: Result<(), _> = redis::AsyncCommands::set(
&mut conn,
&redis_key,
serde_json::json!({
"stage": "scene_vlm",
"progress": 1.0,
"status": "completed",
"detail": format!("{} scenes processed", profile.total_scenes)
})
.to_string(),
)
.await;
}
}
Ok(())
}
@@ -4657,4 +4826,23 @@ mod tests {
assert!(config.enabled);
assert!(config.max_concurrent >= 1);
}
#[test]
fn test_stage_dependencies_from_config() {
use crate::core::db::ProcessorType;
assert_eq!(
stage_dependencies(ProcessorType::Asrx),
vec![ProcessorType::Cut, ProcessorType::Asr]
);
assert_eq!(
stage_dependencies(ProcessorType::Scene),
vec![ProcessorType::Cut]
);
assert_eq!(
stage_dependencies(ProcessorType::FaceCluster),
vec![ProcessorType::Face]
);
// Stages without declared dependencies resolve to none.
assert!(stage_dependencies(ProcessorType::Cut).is_empty());
}
}
+20 -5
View File
@@ -705,13 +705,16 @@ impl ProcessorPool {
ProcessorType::Cut => {
let cut_path =
std::path::Path::new(&output_dir).join(format!("{}.cut.json", job.uuid));
let result = if cut_path.exists() {
let mut result: processor::CutResult = if cut_path.exists() {
let content =
std::fs::read_to_string(&cut_path).context("Failed to read cut.json")?;
serde_json::from_str(&content).context("Failed to parse cut.json")?
} else {
processor::process_cut(video_path, output_path.to_str().unwrap(), uuid).await?
};
result.add_metadata("cut", "ffmpeg_native", uuid);
let chunks_produced = result.scenes.len() as i32;
tracing::info!(
"CUT completed, storing {} scenes for {}",
@@ -751,13 +754,16 @@ impl ProcessorPool {
})
}
ProcessorType::Ocr => {
let result = processor::process_ocr(
let mut result = processor::process_ocr(
video_path,
output_path.to_str().unwrap(),
uuid,
Some(&sample_frames),
)
.await?;
result.add_metadata("ocr", "swift_ocr", uuid);
let chunks_produced = result.frames.len() as i32;
tracing::info!(
"OCR completed, storing {} frames for {}",
@@ -798,13 +804,16 @@ impl ProcessorPool {
})
}
ProcessorType::Face => {
let result = processor::process_face(
let mut result = processor::process_face(
video_path,
output_path.to_str().unwrap(),
uuid,
Some(&sample_frames),
)
.await?;
result.add_metadata("face", "swift_face", uuid);
let chunks_produced = result.frames.len() as i32;
let face_status = result.status.clone();
let total_faces = result.total_faces;
@@ -1022,8 +1031,11 @@ impl ProcessorPool {
})
}
ProcessorType::Asr => {
let result =
let mut result =
processor::process_asr(video_path, output_path.to_str().unwrap(), uuid).await?;
result.add_metadata("asr", "whisper_mlx", uuid);
let chunks_produced = result.segments.len() as i32;
let asr_status = result.status.clone();
let segment_count = result.segment_count;
@@ -1073,9 +1085,12 @@ impl ProcessorPool {
})
}
ProcessorType::Asrx => {
let result =
let mut result =
processor::process_asrx(video_path, output_path.to_str().unwrap(), uuid)
.await?;
result.add_metadata("asrx", "pyannote_diarization", uuid);
let chunks_produced = result.segments.len() as i32;
let asr_status = result.status.clone();
let segment_count = result.segment_count;