fix: Library Re-run 完整重建搜尋索引 (ASR/ASRX/OCR/Scene VLM)
- trigger_processing: force 時僅刪除指定 processor 的輸出檔與 processor_results
(其他 processor 資料保留),並設定 rerun_rebuild Redis flag 要求重建索引
- worker: 單一 processor Re-run 時強制 Rule 1 重新 chunk + vectorize
(清除 momentry_rule1 舊 vectors,避免 stale 搜尋結果)
- Scene VLM Re-run: job_processors 含 scene_vlm 即 dispatch,
scene-only job 完成條件改以 scenes.json 完整度判定
- 前端 redoProcessor 傳 force=true,Scene VLM 新增 🔄 Re-run 按鈕
This commit is contained in:
+115
-4
@@ -44,6 +44,39 @@ fn delete_output_files_for_uuid(uuid: &str, output_dir: &str) -> u64 {
|
||||
deleted_count
|
||||
}
|
||||
|
||||
/// Delete only the output files of the given processors (single-processor re-run).
|
||||
/// Other processors' outputs (and the combined `{uuid}.json`) are preserved so the
|
||||
/// rest of the pipeline data stays intact.
|
||||
fn delete_processor_output_files(uuid: &str, processors: &[String], output_dir: &str) -> u64 {
|
||||
let mut files: Vec<String> = Vec::new();
|
||||
for proc in processors {
|
||||
match proc.as_str() {
|
||||
"asr" => files.push(format!("{}.asr.json", uuid)),
|
||||
"asr_asrx" | "asrx" => files.push(format!("{}.asrx.json", uuid)),
|
||||
"ocr" => files.push(format!("{}.ocr.json", uuid)),
|
||||
"cut" => files.push(format!("{}.cut.json", uuid)),
|
||||
"face" => files.push(format!("{}.face.json", uuid)),
|
||||
"face_cluster" => files.push(format!("{}.face_cluster.json", uuid)),
|
||||
"face_trace" => files.push(format!("{}.face_traced.json", uuid)),
|
||||
"scene_vlm" | "scene" => files.push(format!("{}.scenes.json", uuid)),
|
||||
"pose" => files.push(format!("{}.pose.json", uuid)),
|
||||
"hand" => files.push(format!("{}.hand.json", uuid)),
|
||||
"appearance" => files.push(format!("{}.appearance.json", uuid)),
|
||||
"tkg" => files.push(format!("{}.tkg.json", uuid)),
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
let mut deleted_count = 0u64;
|
||||
for name in files {
|
||||
let path = std::path::Path::new(output_dir).join(&name);
|
||||
if path.exists() && std::fs::remove_file(&path).is_ok() {
|
||||
tracing::info!("[FORCE_RESCAN] Deleted output file: {}", name);
|
||||
deleted_count += 1;
|
||||
}
|
||||
}
|
||||
deleted_count
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
struct JobListResponse {
|
||||
jobs: Vec<JobInfoResponse>,
|
||||
@@ -327,9 +360,28 @@ async fn trigger_processing(
|
||||
// Clean up stale processor_results from previous runs
|
||||
// Old entries with status='running' from a dead worker session
|
||||
// would block the worker from actually running processors.
|
||||
// For single-processor re-runs, only the requested processors are reset
|
||||
// so other processors' completed results are preserved.
|
||||
let pr_table = schema::table_name("processor_results");
|
||||
sqlx::query(&format!("DELETE FROM {pr_table} WHERE job_id = $1"))
|
||||
if processors_to_run.is_empty() {
|
||||
sqlx::query(&format!("DELETE FROM {pr_table} WHERE job_id = $1"))
|
||||
.bind(job_id)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
"[TRIGGER] Failed to clean processor_results for job {}: {}",
|
||||
job_id,
|
||||
e
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
} else {
|
||||
sqlx::query(&format!(
|
||||
"DELETE FROM {pr_table} WHERE job_id = $1 AND (processor = ANY($2) OR processor_type = ANY($2))"
|
||||
))
|
||||
.bind(job_id)
|
||||
.bind(&processors_to_run)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
@@ -340,17 +392,76 @@ async fn trigger_processing(
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
// Scene VLM rows are file-keyed with job_id = NULL, delete them separately
|
||||
if processors_to_run
|
||||
.iter()
|
||||
.any(|p| p == "scene_vlm" || p == "scene")
|
||||
{
|
||||
sqlx::query(&format!(
|
||||
"DELETE FROM {pr_table} WHERE file_uuid = $1 AND processor_type = 'scene_vlm'"
|
||||
))
|
||||
.bind(&file_uuid)
|
||||
.execute(state.db.pool())
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tracing::error!(
|
||||
"[TRIGGER] Failed to clean scene_vlm results for {}: {}",
|
||||
file_uuid,
|
||||
e
|
||||
);
|
||||
StatusCode::INTERNAL_SERVER_ERROR
|
||||
})?;
|
||||
}
|
||||
}
|
||||
tracing::info!("[TRIGGER] Cleaned processor_results for job {}", job_id);
|
||||
|
||||
// If force=true, delete output files to force re-processing
|
||||
if req.force {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.to_string();
|
||||
let deleted_count = delete_output_files_for_uuid(&file_uuid, &output_dir);
|
||||
let deleted_count = if processors_to_run.is_empty() {
|
||||
// Full re-scan: delete all output files
|
||||
delete_output_files_for_uuid(&file_uuid, &output_dir)
|
||||
} else {
|
||||
// Single-processor re-run: delete only that processor's output
|
||||
delete_processor_output_files(&file_uuid, &processors_to_run, &output_dir)
|
||||
};
|
||||
tracing::info!(
|
||||
"[TRIGGER] Force re-scan: deleted {} output files for {}",
|
||||
"[TRIGGER] Force re-scan: deleted {} output files for {} (processors={:?})",
|
||||
deleted_count,
|
||||
file_uuid
|
||||
file_uuid,
|
||||
processors_to_run
|
||||
);
|
||||
|
||||
// Re-running ASR/OCR/Scene VLM must also rebuild the search index:
|
||||
// - asr/asrx/ocr → Rule 1 re-chunking + re-vectorize (chunk table + momentry_rule1)
|
||||
// - scene_vlm → _scenes collection regeneration
|
||||
// Signal the worker via Redis so the Rule 1 guard doesn't skip re-chunking
|
||||
// just because old chunks still exist.
|
||||
let rebuild_procs = ["asr", "asr_asrx", "asrx", "ocr", "scene_vlm", "scene"];
|
||||
let needs_rebuild = processors_to_run.is_empty()
|
||||
|| processors_to_run
|
||||
.iter()
|
||||
.any(|p| rebuild_procs.contains(&p.as_str()));
|
||||
if needs_rebuild {
|
||||
let key = format!("{}rerun_rebuild:{}", REDIS_KEY_PREFIX.as_str(), file_uuid);
|
||||
let flag_value = if processors_to_run.is_empty() {
|
||||
"all".to_string()
|
||||
} else {
|
||||
processors_to_run.join(",")
|
||||
};
|
||||
let _: Result<String, _> = redis::cmd("SET")
|
||||
.arg(&key)
|
||||
.arg(&flag_value)
|
||||
.arg("EX")
|
||||
.arg(86400)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
tracing::info!(
|
||||
"[TRIGGER] Set rerun_rebuild flag for {} = {}",
|
||||
file_uuid,
|
||||
flag_value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Update existing job with new face_settings if provided
|
||||
|
||||
@@ -2189,7 +2189,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
let has_asr_or_asrx =
|
||||
job_processors.is_empty() || job_processors.iter().any(|p| p == "asrx" || p == "asr" || p == "asr_asrx");
|
||||
let has_face = job_processors.is_empty() || job_processors.iter().any(|p| p == "face");
|
||||
let has_cut = job_processors.is_empty() || job_processors.iter().any(|p| p == "cut");
|
||||
let has_cut = job_processors.is_empty()
|
||||
|| job_processors
|
||||
.iter()
|
||||
.any(|p| p == "cut" || p == "scene_vlm" || p == "scene");
|
||||
|
||||
// 1. ASR/ASRX: sentence chunks 存在
|
||||
let asr_done: bool = if has_asr_or_asrx {
|
||||
@@ -2550,10 +2553,12 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
);
|
||||
|
||||
// Scene VLM 必要檢查 (deep scan = 有 cut):
|
||||
// - has_scene_vlm_job: job 是否含 cut(決定 scene_vlm 是否必要)
|
||||
// - has_cut_job: job 是否含 cut 或 scene_vlm(決定 scene_vlm 是否必要)
|
||||
// - scene_vlm_complete: scenes.json 完整性
|
||||
// - scene_vlm_exhausted: scene_vlm 記錄 retry_count >= 3(無法自行完成)
|
||||
let has_cut_job = job_processors.iter().any(|p| p == "cut");
|
||||
let has_cut_job = job_processors
|
||||
.iter()
|
||||
.any(|p| p == "cut" || p == "scene_vlm" || p == "scene");
|
||||
let (scene_vlm_complete, scene_vlm_exhausted) = if has_cut_job {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.as_str();
|
||||
let scenes_path = format!("{}/{}.scenes.json", output_dir, uuid);
|
||||
@@ -3001,7 +3006,26 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
.await?;
|
||||
|
||||
// Scene VLM processing (mandatory, after CUT completes)
|
||||
if has_cut {
|
||||
// Also dispatches for Scene VLM Re-run jobs (processors contains
|
||||
// scene_vlm, cut already completed in a previous run).
|
||||
let wants_scene_vlm = job_processors
|
||||
.iter()
|
||||
.any(|p| p == "scene_vlm" || p == "scene");
|
||||
// A job that ONLY requests scene_vlm (Scene VLM Re-run) has no
|
||||
// essential processor results in this run — completion is decided by
|
||||
// scenes.json completeness instead.
|
||||
let scene_only_rejob = !job_processors.is_empty()
|
||||
&& wants_scene_vlm
|
||||
&& job_processors
|
||||
.iter()
|
||||
.all(|p| p == "scene_vlm" || p == "scene");
|
||||
let cut_json_exists = std::path::Path::new(&format!(
|
||||
"{}/{}.cut.json",
|
||||
crate::core::config::OUTPUT_DIR.as_str(),
|
||||
uuid
|
||||
))
|
||||
.exists();
|
||||
if has_cut || (wants_scene_vlm && cut_json_exists) {
|
||||
let output_dir = crate::core::config::OUTPUT_DIR.clone();
|
||||
let scenes_path = format!("{}/{}.scenes.json", output_dir, uuid);
|
||||
|
||||
@@ -3116,6 +3140,37 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
}
|
||||
|
||||
if has_asrx || has_ocr {
|
||||
// Read the force-rebuild flag (set by trigger_processing when a
|
||||
// single-processor re-run of asr/asrx/ocr was requested). Old chunks
|
||||
// still exist, so without this flag the Rule 1 guard would skip
|
||||
// re-chunking and the search index would keep stale text/vectors.
|
||||
let mut force_rechunk = false;
|
||||
if let Ok(mut conn) = self.redis.get_conn().await {
|
||||
let flag_key = format!("{}rerun_rebuild:{}", crate::core::config::REDIS_KEY_PREFIX.as_str(), uuid);
|
||||
let flag: Option<String> = redis::cmd("GET")
|
||||
.arg(&flag_key)
|
||||
.query_async(&mut conn)
|
||||
.await
|
||||
.unwrap_or(None);
|
||||
if let Some(ref val) = flag {
|
||||
let related = val == "all"
|
||||
|| val.split(',').any(|p| matches!(p, "asr" | "asr_asrx" | "asrx" | "ocr"));
|
||||
if related {
|
||||
force_rechunk = true;
|
||||
}
|
||||
// Only clear the key when no scene_vlm rebuild is pending
|
||||
if related {
|
||||
let _: Result<i64, _> = redis::cmd("DEL")
|
||||
.arg(&flag_key)
|
||||
.query_async(&mut conn)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
if force_rechunk {
|
||||
info!("📝 Force re-chunk requested for {} (re-run), Rule 1 will rebuild chunks + vectors", uuid);
|
||||
}
|
||||
|
||||
// Guard: only spawn Rule 1 if sentence chunks don't exist yet
|
||||
// or if OCR completed but OCR chunks are missing (OCR came after ASRX)
|
||||
let chunk_t = schema::table_name("chunk");
|
||||
@@ -3141,8 +3196,10 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
true // skip OCR check if OCR hasn't completed yet
|
||||
};
|
||||
|
||||
// Run Rule1 if no sentence chunks yet, or if OCR finished but OCR chunks missing
|
||||
let needs_rule1 = !has_sentence || (has_ocr && !has_ocr_chunks);
|
||||
// Run Rule1 if no sentence chunks yet, if OCR finished but OCR chunks missing,
|
||||
// or when a processor re-run explicitly requested a rebuild
|
||||
let needs_rule1 =
|
||||
!has_sentence || (has_ocr && !has_ocr_chunks) || force_rechunk;
|
||||
|
||||
if !needs_rule1 {
|
||||
info!("✅ Rule 1 already completed for {}, skipping spawn", uuid);
|
||||
@@ -3162,6 +3219,22 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
match db_clone.get_video_by_uuid(&uuid_clone).await {
|
||||
Ok(Some(video)) => {
|
||||
let fps = video.fps;
|
||||
// Re-run rebuild: purge stale text vectors from the default
|
||||
// collection first so removed chunks don't linger in search.
|
||||
// Fresh chunks get re-upserted by vectorize below.
|
||||
if force_rechunk {
|
||||
let qdrant = QdrantDb::new();
|
||||
match qdrant.delete_by_uuid(&uuid_clone).await {
|
||||
Ok(_) => info!(
|
||||
"🗑️ Cleared stale Qdrant vectors for {} before re-chunk",
|
||||
uuid_clone
|
||||
),
|
||||
Err(e) => warn!(
|
||||
"Failed to clear stale Qdrant vectors for {}: {}",
|
||||
uuid_clone, e
|
||||
),
|
||||
}
|
||||
}
|
||||
match rule1_ingest::execute_rule1(&db_clone, &uuid_clone, fps).await {
|
||||
Ok(count) => {
|
||||
info!(
|
||||
@@ -4267,16 +4340,18 @@ async fn process_job(&self, job: crate::core::db::MonitorJob) -> Result<()> {
|
||||
publish_pipeline_progress(self.redis.as_ref(), uuid, &pp).await;
|
||||
|
||||
info!("Job {} completed successfully (ingestion done)", job_id);
|
||||
} else if essential_completed
|
||||
} else if (essential_completed || scene_only_rejob)
|
||||
&& !all_completed
|
||||
&& !any_pending
|
||||
&& !any_skipped
|
||||
&& scene_vlm_complete
|
||||
{
|
||||
// 必要 processor 完成但部分非必要失敗 → 仍算完成(但無 pending 者才觸發)
|
||||
// Scene-only re-run jobs (Scene VLM Re-run) carry no essential results
|
||||
// in this run; they complete once scenes.json is fully regenerated.
|
||||
info!(
|
||||
"Job {} completed with non-essential failures. Essential: {:?}",
|
||||
job_id, essential_processors
|
||||
"Job {} completed (essential={:?}, scene-only-rejob={})",
|
||||
job_id, essential_processors, scene_only_rejob
|
||||
);
|
||||
self.db
|
||||
.update_job_status(job_id, MonitorJobStatus::Completed)
|
||||
|
||||
Reference in New Issue
Block a user